Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: netCDF read/write Driver
4 : * Purpose: GDAL bindings over netCDF library.
5 : * Author: Frank Warmerdam, warmerdam@pobox.com
6 : * Even Rouault <even.rouault at spatialys.com>
7 : *
8 : ******************************************************************************
9 : * Copyright (c) 2004, Frank Warmerdam
10 : * Copyright (c) 2007-2016, Even Rouault <even.rouault at spatialys.com>
11 : * Copyright (c) 2010, Kyle Shannon <kyle at pobox dot com>
12 : * Copyright (c) 2021, CLS
13 : *
14 : * SPDX-License-Identifier: MIT
15 : ****************************************************************************/
16 :
17 : #include "cpl_port.h"
18 :
19 : #include <array>
20 : #include <cassert>
21 : #include <cctype>
22 : #include <cerrno>
23 : #include <climits>
24 : #include <cmath>
25 : #include <cstdio>
26 : #include <cstdlib>
27 : #include <cstring>
28 : #include <ctime>
29 : #include <algorithm>
30 : #include <limits>
31 : #include <map>
32 : #include <set>
33 : #include <queue>
34 : #include <string>
35 : #include <tuple>
36 : #include <utility>
37 : #include <vector>
38 :
39 : // Must be included after standard includes, otherwise VS2015 fails when
40 : // including <ctime>
41 : #include "netcdfdataset.h"
42 : #include "netcdfdrivercore.h"
43 : #include "netcdfsg.h"
44 : #include "netcdfuffd.h"
45 :
46 : #include "netcdf_mem.h"
47 :
48 : #include "cpl_conv.h"
49 : #include "cpl_error.h"
50 : #include "cpl_float.h"
51 : #include "cpl_json.h"
52 : #include "cpl_minixml.h"
53 : #include "cpl_multiproc.h"
54 : #include "cpl_progress.h"
55 : #include "cpl_time.h"
56 : #include "gdal.h"
57 : #include "gdal_frmts.h"
58 : #include "gdal_priv_templates.hpp"
59 : #include "ogr_core.h"
60 : #include "ogr_srs_api.h"
61 :
62 : // netCDF 4.8 switched to expecting filenames in UTF-8 on Windows
63 : // But with netCDF 4.9 and https://github.com/Unidata/netcdf-c/pull/2277/,
64 : // this is apparently back to expecting filenames in current codepage...
65 : // Detect netCDF 4.8 with NC_ENCZARR
66 : // Detect netCDF 4.9 with NC_NOATTCREORD
67 : #if defined(NC_ENCZARR) && !defined(NC_NOATTCREORD)
68 : #define NETCDF_USES_UTF8
69 : #endif
70 :
71 : // Internal function declarations.
72 :
73 : static bool NCDFIsGDALVersionGTE(const char *pszVersion, int nTarget);
74 :
75 : static void
76 : NCDFAddGDALHistory(int fpImage, const char *pszFilename, bool bWriteGDALVersion,
77 : bool bWriteGDALHistory, const char *pszOldHist,
78 : const char *pszFunctionName,
79 : const char *pszCFVersion = GDAL_DEFAULT_NCDF_CONVENTIONS);
80 :
81 : static void NCDFAddHistory(int fpImage, const char *pszAddHist,
82 : const char *pszOldHist);
83 :
84 : static CPLErr NCDFSafeStrcat(char **ppszDest, const char *pszSrc,
85 : size_t *nDestSize);
86 :
87 : // Var / attribute helper functions.
88 : static CPLErr NCDFPutAttr(int nCdfId, int nVarId, const char *pszAttrName,
89 : const char *pszValue);
90 :
91 : // Replace this where used.
92 : static CPLErr NCDFGet1DVar(int nCdfId, int nVarId, char **pszValue);
93 : static CPLErr NCDFPut1DVar(int nCdfId, int nVarId, const char *pszValue);
94 :
95 : // Replace this where used.
96 : static char **NCDFTokenizeArray(const char *pszValue);
97 : static void CopyMetadata(GDALDataset *poSrcDS, GDALRasterBand *poSrcBand,
98 : GDALRasterBand *poDstBand, int fpImage, int CDFVarID,
99 : const char *pszMatchPrefix = nullptr);
100 :
101 : // NetCDF-4 groups helper functions.
102 : // They all work also for NetCDF-3 files which are considered as
103 : // NetCDF-4 file with only one group.
104 : static CPLErr NCDFOpenSubDataset(int nCdfId, const char *pszSubdatasetName,
105 : int *pnGroupId, int *pnVarId);
106 : static CPLErr NCDFGetVisibleDims(int nGroupId, int *pnDims, int **ppanDimIds);
107 : static CPLErr NCDFGetSubGroups(int nGroupId, int *pnSubGroups,
108 : int **ppanSubGroupIds);
109 : static CPLErr NCDFGetGroupFullName(int nGroupId, char **ppszFullName,
110 : bool bNC3Compat = true);
111 : static CPLErr NCDFGetVarFullName(int nGroupId, int nVarId, char **ppszFullName,
112 : bool bNC3Compat = true);
113 : static CPLErr NCDFGetRootGroup(int nStartGroupId, int *pnRootGroupId);
114 :
115 : static CPLErr NCDFResolveVarFullName(int nStartGroupId, const char *pszVar,
116 : char **ppszFullName,
117 : bool bMandatory = false);
118 : static CPLErr NCDFResolveAttInt(int nStartGroupId, int nStartVarId,
119 : const char *pszAtt, int *pnAtt,
120 : bool bMandatory = false);
121 : static CPLErr NCDFGetCoordAndBoundVarFullNames(int nCdfId, char ***ppapszVars);
122 :
123 : // Uncomment this for more debug output.
124 : // #define NCDF_DEBUG 1
125 :
126 : CPLMutex *hNCMutex = nullptr;
127 :
128 : // Workaround https://github.com/OSGeo/gdal/issues/6253
129 : // Having 2 netCDF handles on the same file doesn't work in a multi-threaded
130 : // way. Apparently having the same handle works better (this is OK since
131 : // we have a global mutex on the netCDF library)
132 : static std::map<std::string, int> goMapNameToNetCDFId;
133 : static std::map<int, std::pair<std::string, int>> goMapNetCDFIdToKeyAndCount;
134 :
135 652 : int GDAL_nc_open(const char *pszFilename, int nMode, int *pID)
136 : {
137 1304 : std::string osKey(pszFilename);
138 652 : osKey += "#####";
139 652 : osKey += std::to_string(nMode);
140 652 : auto oIter = goMapNameToNetCDFId.find(osKey);
141 652 : if (oIter == goMapNameToNetCDFId.end())
142 : {
143 605 : int ret = nc_open(pszFilename, nMode, pID);
144 605 : if (ret != NC_NOERR)
145 3 : return ret;
146 602 : goMapNameToNetCDFId[osKey] = *pID;
147 602 : goMapNetCDFIdToKeyAndCount[*pID] =
148 1204 : std::pair<std::string, int>(osKey, 1);
149 602 : return ret;
150 : }
151 : else
152 : {
153 47 : *pID = oIter->second;
154 47 : goMapNetCDFIdToKeyAndCount[oIter->second].second++;
155 47 : return NC_NOERR;
156 : }
157 : }
158 :
159 906 : int GDAL_nc_close(int cdfid)
160 : {
161 906 : int ret = NC_NOERR;
162 906 : auto oIter = goMapNetCDFIdToKeyAndCount.find(cdfid);
163 906 : if (oIter != goMapNetCDFIdToKeyAndCount.end())
164 : {
165 649 : if (--oIter->second.second == 0)
166 : {
167 602 : ret = nc_close(cdfid);
168 602 : goMapNameToNetCDFId.erase(oIter->second.first);
169 602 : goMapNetCDFIdToKeyAndCount.erase(oIter);
170 : }
171 : }
172 : else
173 : {
174 : // we can go here if file opened with nc_open_mem() or nc_create()
175 257 : ret = nc_close(cdfid);
176 : }
177 906 : return ret;
178 : }
179 :
180 : /************************************************************************/
181 : /* ==================================================================== */
182 : /* netCDFRasterBand */
183 : /* ==================================================================== */
184 : /************************************************************************/
185 :
186 : class netCDFRasterBand final : public GDALPamRasterBand
187 : {
188 : friend class netCDFDataset;
189 :
190 : nc_type nc_datatype;
191 : int cdfid;
192 : int nZId;
193 : int nZDim;
194 : int nLevel;
195 : int nBandXPos;
196 : int nBandYPos;
197 : int *panBandZPos;
198 : int *panBandZLev;
199 : bool m_bNoDataSet = false;
200 : double m_dfNoDataValue = 0;
201 : bool m_bNoDataSetAsInt64 = false;
202 : int64_t m_nNodataValueInt64 = 0;
203 : bool m_bNoDataSetAsUInt64 = false;
204 : uint64_t m_nNodataValueUInt64 = 0;
205 : bool bValidRangeValid = false;
206 : double adfValidRange[2]{0, 0};
207 : bool m_bHaveScale = false;
208 : bool m_bHaveOffset = false;
209 : double m_dfScale = 1;
210 : double m_dfOffset = 0;
211 : CPLString m_osUnitType{};
212 : bool bSignedData;
213 : bool bCheckLongitude;
214 : bool m_bCreateMetadataFromOtherVarsDone = false;
215 :
216 : void CreateMetadataFromAttributes();
217 : void CreateMetadataFromOtherVars();
218 :
219 : template <class T>
220 : void CheckData(void *pImage, void *pImageNC, size_t nTmpBlockXSize,
221 : size_t nTmpBlockYSize, bool bCheckIsNan = false);
222 : template <class T>
223 : void CheckDataCpx(void *pImage, void *pImageNC, size_t nTmpBlockXSize,
224 : size_t nTmpBlockYSize, bool bCheckIsNan = false);
225 : void SetBlockSize();
226 :
227 : bool FetchNetcdfChunk(size_t xstart, size_t ystart, void *pImage);
228 :
229 : void SetNoDataValueNoUpdate(double dfNoData);
230 : void SetNoDataValueNoUpdate(int64_t nNoData);
231 : void SetNoDataValueNoUpdate(uint64_t nNoData);
232 :
233 : void SetOffsetNoUpdate(double dfVal);
234 : void SetScaleNoUpdate(double dfVal);
235 : void SetUnitTypeNoUpdate(const char *pszNewValue);
236 :
237 : protected:
238 : CPLXMLNode *SerializeToXML(const char *pszUnused) override;
239 :
240 : public:
241 : struct CONSTRUCTOR_OPEN
242 : {
243 : };
244 :
245 : struct CONSTRUCTOR_CREATE
246 : {
247 : };
248 :
249 : netCDFRasterBand(const CONSTRUCTOR_OPEN &, netCDFDataset *poDS,
250 : int nGroupId, int nZId, int nZDim, int nLevel,
251 : const int *panBandZLen, const int *panBandPos, int nBand);
252 : netCDFRasterBand(const CONSTRUCTOR_CREATE &, netCDFDataset *poDS,
253 : GDALDataType eType, int nBand, bool bSigned = true,
254 : const char *pszBandName = nullptr,
255 : const char *pszLongName = nullptr, int nZId = -1,
256 : int nZDim = 2, int nLevel = 0,
257 : const int *panBandZLev = nullptr,
258 : const int *panBandZPos = nullptr,
259 : const int *paDimIds = nullptr);
260 : virtual ~netCDFRasterBand();
261 :
262 : virtual double GetNoDataValue(int *) override;
263 : virtual int64_t GetNoDataValueAsInt64(int *pbSuccess = nullptr) override;
264 : virtual uint64_t GetNoDataValueAsUInt64(int *pbSuccess = nullptr) override;
265 : virtual CPLErr SetNoDataValue(double) override;
266 : virtual CPLErr SetNoDataValueAsInt64(int64_t nNoData) override;
267 : virtual CPLErr SetNoDataValueAsUInt64(uint64_t nNoData) override;
268 : // virtual CPLErr DeleteNoDataValue();
269 : virtual double GetOffset(int *) override;
270 : virtual CPLErr SetOffset(double) override;
271 : virtual double GetScale(int *) override;
272 : virtual CPLErr SetScale(double) override;
273 : virtual const char *GetUnitType() override;
274 : virtual CPLErr SetUnitType(const char *) override;
275 : virtual CPLErr IReadBlock(int, int, void *) override;
276 : virtual CPLErr IWriteBlock(int, int, void *) override;
277 :
278 : char **GetMetadata(const char *pszDomain = "") override;
279 : const char *GetMetadataItem(const char *pszName,
280 : const char *pszDomain = "") override;
281 :
282 : virtual CPLErr SetMetadataItem(const char *pszName, const char *pszValue,
283 : const char *pszDomain = "") override;
284 : virtual CPLErr SetMetadata(char **papszMD,
285 : const char *pszDomain = "") override;
286 : };
287 :
288 : /************************************************************************/
289 : /* netCDFRasterBand() */
290 : /************************************************************************/
291 :
292 468 : netCDFRasterBand::netCDFRasterBand(const netCDFRasterBand::CONSTRUCTOR_OPEN &,
293 : netCDFDataset *poNCDFDS, int nGroupId,
294 : int nZIdIn, int nZDimIn, int nLevelIn,
295 : const int *panBandZLevIn,
296 468 : const int *panBandZPosIn, int nBandIn)
297 : : nc_datatype(NC_NAT), cdfid(nGroupId), nZId(nZIdIn), nZDim(nZDimIn),
298 468 : nLevel(nLevelIn), nBandXPos(panBandZPosIn[0]),
299 468 : nBandYPos(nZDim == 1 ? -1 : panBandZPosIn[1]), panBandZPos(nullptr),
300 : panBandZLev(nullptr),
301 : bSignedData(true), // Default signed, except for Byte.
302 936 : bCheckLongitude(false)
303 : {
304 468 : poDS = poNCDFDS;
305 468 : nBand = nBandIn;
306 :
307 : // Take care of all other dimensions.
308 468 : if (nZDim > 2)
309 : {
310 168 : panBandZPos = static_cast<int *>(CPLCalloc(nZDim - 1, sizeof(int)));
311 168 : panBandZLev = static_cast<int *>(CPLCalloc(nZDim - 1, sizeof(int)));
312 :
313 462 : for (int i = 0; i < nZDim - 2; i++)
314 : {
315 294 : panBandZPos[i] = panBandZPosIn[i + 2];
316 294 : panBandZLev[i] = panBandZLevIn[i];
317 : }
318 : }
319 :
320 468 : nRasterXSize = poDS->GetRasterXSize();
321 468 : nRasterYSize = poDS->GetRasterYSize();
322 468 : nBlockXSize = poDS->GetRasterXSize();
323 468 : nBlockYSize = 1;
324 :
325 : // Get the type of the "z" variable, our target raster array.
326 468 : if (nc_inq_var(cdfid, nZId, nullptr, &nc_datatype, nullptr, nullptr,
327 468 : nullptr) != NC_NOERR)
328 : {
329 0 : CPLError(CE_Failure, CPLE_AppDefined, "Error in nc_var_inq() on 'z'.");
330 0 : return;
331 : }
332 :
333 468 : if (NCDFIsUserDefinedType(cdfid, nc_datatype))
334 : {
335 : // First enquire and check that the number of fields is 2
336 : size_t nfields, compoundsize;
337 5 : if (nc_inq_compound(cdfid, nc_datatype, nullptr, &compoundsize,
338 5 : &nfields) != NC_NOERR)
339 : {
340 0 : CPLError(CE_Failure, CPLE_AppDefined,
341 : "Error in nc_inq_compound() on 'z'.");
342 0 : return;
343 : }
344 :
345 5 : if (nfields != 2)
346 : {
347 0 : CPLError(CE_Failure, CPLE_AppDefined,
348 : "Unsupported data type encountered in nc_inq_compound() "
349 : "on 'z'.");
350 0 : return;
351 : }
352 :
353 : // Now check that that two types are the same in the struct.
354 : nc_type field_type1, field_type2;
355 : int field_dims1, field_dims2;
356 5 : if (nc_inq_compound_field(cdfid, nc_datatype, 0, nullptr, nullptr,
357 : &field_type1, &field_dims1,
358 5 : nullptr) != NC_NOERR)
359 : {
360 0 : CPLError(
361 : CE_Failure, CPLE_AppDefined,
362 : "Error in querying Field 1 in nc_inq_compound_field() on 'z'.");
363 0 : return;
364 : }
365 :
366 5 : if (nc_inq_compound_field(cdfid, nc_datatype, 0, nullptr, nullptr,
367 : &field_type2, &field_dims2,
368 5 : nullptr) != NC_NOERR)
369 : {
370 0 : CPLError(
371 : CE_Failure, CPLE_AppDefined,
372 : "Error in querying Field 2 in nc_inq_compound_field() on 'z'.");
373 0 : return;
374 : }
375 :
376 5 : if ((field_type1 != field_type2) || (field_dims1 != field_dims2) ||
377 5 : (field_dims1 != 0))
378 : {
379 0 : CPLError(CE_Failure, CPLE_AppDefined,
380 : "Error in interpreting compound data type on 'z'.");
381 0 : return;
382 : }
383 :
384 5 : if (field_type1 == NC_SHORT)
385 0 : eDataType = GDT_CInt16;
386 5 : else if (field_type1 == NC_INT)
387 0 : eDataType = GDT_CInt32;
388 5 : else if (field_type1 == NC_FLOAT)
389 4 : eDataType = GDT_CFloat32;
390 1 : else if (field_type1 == NC_DOUBLE)
391 1 : eDataType = GDT_CFloat64;
392 : else
393 : {
394 0 : CPLError(CE_Failure, CPLE_AppDefined,
395 : "Unsupported netCDF compound data type encountered.");
396 0 : return;
397 : }
398 : }
399 : else
400 : {
401 463 : if (nc_datatype == NC_BYTE)
402 142 : eDataType = GDT_Byte;
403 321 : else if (nc_datatype == NC_CHAR)
404 0 : eDataType = GDT_Byte;
405 321 : else if (nc_datatype == NC_SHORT)
406 41 : eDataType = GDT_Int16;
407 280 : else if (nc_datatype == NC_INT)
408 89 : eDataType = GDT_Int32;
409 191 : else if (nc_datatype == NC_FLOAT)
410 115 : eDataType = GDT_Float32;
411 76 : else if (nc_datatype == NC_DOUBLE)
412 40 : eDataType = GDT_Float64;
413 36 : else if (nc_datatype == NC_UBYTE)
414 14 : eDataType = GDT_Byte;
415 22 : else if (nc_datatype == NC_USHORT)
416 4 : eDataType = GDT_UInt16;
417 18 : else if (nc_datatype == NC_UINT)
418 3 : eDataType = GDT_UInt32;
419 15 : else if (nc_datatype == NC_INT64)
420 8 : eDataType = GDT_Int64;
421 7 : else if (nc_datatype == NC_UINT64)
422 7 : eDataType = GDT_UInt64;
423 : else
424 : {
425 0 : if (nBand == 1)
426 0 : CPLError(CE_Warning, CPLE_AppDefined,
427 : "Unsupported netCDF datatype (%d), treat as Float32.",
428 0 : static_cast<int>(nc_datatype));
429 0 : eDataType = GDT_Float32;
430 0 : nc_datatype = NC_FLOAT;
431 : }
432 : }
433 :
434 : // Find and set No Data for this variable.
435 468 : nc_type atttype = NC_NAT;
436 468 : size_t attlen = 0;
437 468 : const char *pszNoValueName = nullptr;
438 :
439 : // Find attribute name, either _FillValue or missing_value.
440 468 : int status = nc_inq_att(cdfid, nZId, NCDF_FillValue, &atttype, &attlen);
441 468 : if (status == NC_NOERR)
442 : {
443 248 : pszNoValueName = NCDF_FillValue;
444 : }
445 : else
446 : {
447 220 : status = nc_inq_att(cdfid, nZId, "missing_value", &atttype, &attlen);
448 220 : if (status == NC_NOERR)
449 : {
450 12 : pszNoValueName = "missing_value";
451 : }
452 : }
453 :
454 : // Fetch missing value.
455 468 : double dfNoData = 0.0;
456 468 : bool bGotNoData = false;
457 468 : int64_t nNoDataAsInt64 = 0;
458 468 : bool bGotNoDataAsInt64 = false;
459 468 : uint64_t nNoDataAsUInt64 = 0;
460 468 : bool bGotNoDataAsUInt64 = false;
461 468 : if (status == NC_NOERR)
462 : {
463 260 : nc_type nAttrType = NC_NAT;
464 260 : size_t nAttrLen = 0;
465 260 : status = nc_inq_att(cdfid, nZId, pszNoValueName, &nAttrType, &nAttrLen);
466 260 : if (status == NC_NOERR && nAttrLen == 1 && nAttrType == NC_INT64)
467 : {
468 : long long v;
469 7 : nc_get_att_longlong(cdfid, nZId, pszNoValueName, &v);
470 7 : bGotNoData = true;
471 7 : bGotNoDataAsInt64 = true;
472 7 : nNoDataAsInt64 = static_cast<int64_t>(v);
473 : }
474 253 : else if (status == NC_NOERR && nAttrLen == 1 && nAttrType == NC_UINT64)
475 : {
476 : unsigned long long v;
477 7 : nc_get_att_ulonglong(cdfid, nZId, pszNoValueName, &v);
478 7 : bGotNoData = true;
479 7 : bGotNoDataAsUInt64 = true;
480 7 : nNoDataAsUInt64 = static_cast<uint64_t>(v);
481 : }
482 246 : else if (NCDFGetAttr(cdfid, nZId, pszNoValueName, &dfNoData) == CE_None)
483 : {
484 245 : bGotNoData = true;
485 : }
486 : }
487 :
488 : // If NoData was not found, use the default value, but for non-Byte types
489 : // as it is not recommended:
490 : // https://www.unidata.ucar.edu/software/netcdf/docs/attribute_conventions.html
491 468 : nc_type vartype = NC_NAT;
492 468 : if (!bGotNoData)
493 : {
494 209 : nc_inq_vartype(cdfid, nZId, &vartype);
495 209 : if (vartype == NC_INT64)
496 : {
497 : nNoDataAsInt64 =
498 1 : NCDFGetDefaultNoDataValueAsInt64(cdfid, nZId, bGotNoData);
499 1 : bGotNoDataAsInt64 = bGotNoData;
500 : }
501 208 : else if (vartype == NC_UINT64)
502 : {
503 : nNoDataAsUInt64 =
504 0 : NCDFGetDefaultNoDataValueAsUInt64(cdfid, nZId, bGotNoData);
505 0 : bGotNoDataAsUInt64 = bGotNoData;
506 : }
507 208 : else if (vartype != NC_CHAR && vartype != NC_BYTE &&
508 89 : vartype != NC_UBYTE)
509 : {
510 81 : dfNoData =
511 81 : NCDFGetDefaultNoDataValue(cdfid, nZId, vartype, bGotNoData);
512 81 : if (bGotNoData)
513 : {
514 70 : CPLDebug("GDAL_netCDF",
515 : "did not get nodata value for variable #%d, using "
516 : "default %f",
517 : nZId, dfNoData);
518 : }
519 : }
520 : }
521 :
522 468 : bool bHasUnderscoreUnsignedAttr = false;
523 468 : bool bUnderscoreUnsignedAttrVal = false;
524 : {
525 468 : char *pszTemp = nullptr;
526 468 : if (NCDFGetAttr(cdfid, nZId, "_Unsigned", &pszTemp) == CE_None)
527 : {
528 134 : if (EQUAL(pszTemp, "true"))
529 : {
530 126 : bHasUnderscoreUnsignedAttr = true;
531 126 : bUnderscoreUnsignedAttrVal = true;
532 : }
533 8 : else if (EQUAL(pszTemp, "false"))
534 : {
535 8 : bHasUnderscoreUnsignedAttr = true;
536 8 : bUnderscoreUnsignedAttrVal = false;
537 : }
538 134 : CPLFree(pszTemp);
539 : }
540 : }
541 :
542 : // Look for valid_range or valid_min/valid_max.
543 :
544 : // First look for valid_range.
545 468 : if (CPLFetchBool(poNCDFDS->GetOpenOptions(), "HONOUR_VALID_RANGE", true))
546 : {
547 466 : char *pszValidRange = nullptr;
548 466 : if (NCDFGetAttr(cdfid, nZId, "valid_range", &pszValidRange) ==
549 127 : CE_None &&
550 593 : pszValidRange[0] == '{' &&
551 127 : pszValidRange[strlen(pszValidRange) - 1] == '}')
552 : {
553 : const std::string osValidRange =
554 381 : std::string(pszValidRange).substr(1, strlen(pszValidRange) - 2);
555 : const CPLStringList aosValidRange(
556 254 : CSLTokenizeString2(osValidRange.c_str(), ",", 0));
557 127 : if (aosValidRange.size() == 2 &&
558 254 : CPLGetValueType(aosValidRange[0]) != CPL_VALUE_STRING &&
559 127 : CPLGetValueType(aosValidRange[1]) != CPL_VALUE_STRING)
560 : {
561 127 : bValidRangeValid = true;
562 127 : adfValidRange[0] = CPLAtof(aosValidRange[0]);
563 127 : adfValidRange[1] = CPLAtof(aosValidRange[1]);
564 : }
565 : }
566 466 : CPLFree(pszValidRange);
567 :
568 : // If not found look for valid_min and valid_max.
569 466 : if (!bValidRangeValid)
570 : {
571 339 : double dfMin = 0;
572 339 : double dfMax = 0;
573 354 : if (NCDFGetAttr(cdfid, nZId, "valid_min", &dfMin) == CE_None &&
574 15 : NCDFGetAttr(cdfid, nZId, "valid_max", &dfMax) == CE_None)
575 : {
576 8 : adfValidRange[0] = dfMin;
577 8 : adfValidRange[1] = dfMax;
578 8 : bValidRangeValid = true;
579 : }
580 : }
581 :
582 466 : if (bValidRangeValid &&
583 135 : (adfValidRange[0] < 0 || adfValidRange[1] < 0) &&
584 17 : nc_datatype == NC_SHORT && bHasUnderscoreUnsignedAttr &&
585 : bUnderscoreUnsignedAttrVal)
586 : {
587 2 : if (adfValidRange[0] < 0)
588 0 : adfValidRange[0] += 65536;
589 2 : if (adfValidRange[1] < 0)
590 2 : adfValidRange[1] += 65536;
591 2 : if (adfValidRange[0] <= adfValidRange[1])
592 : {
593 : // Updating metadata item
594 2 : GDALPamRasterBand::SetMetadataItem(
595 : "valid_range",
596 2 : CPLSPrintf("{%d,%d}", static_cast<int>(adfValidRange[0]),
597 2 : static_cast<int>(adfValidRange[1])));
598 : }
599 : }
600 :
601 466 : if (bValidRangeValid && adfValidRange[0] > adfValidRange[1])
602 : {
603 0 : CPLError(CE_Warning, CPLE_AppDefined,
604 : "netCDFDataset::valid_range: min > max:\n"
605 : " min: %lf\n max: %lf\n",
606 : adfValidRange[0], adfValidRange[1]);
607 0 : bValidRangeValid = false;
608 0 : adfValidRange[0] = 0.0;
609 0 : adfValidRange[1] = 0.0;
610 : }
611 : }
612 :
613 : // Special For Byte Bands: check for signed/unsigned byte.
614 468 : if (nc_datatype == NC_BYTE)
615 : {
616 : // netcdf uses signed byte by default, but GDAL uses unsigned by default
617 : // This may cause unexpected results, but is needed for back-compat.
618 142 : if (poNCDFDS->bIsGdalFile)
619 121 : bSignedData = false;
620 : else
621 21 : bSignedData = true;
622 :
623 : // For NC4 format NC_BYTE is (normally) signed, NC_UBYTE is unsigned.
624 : // But in case a NC3 file was converted automatically and has hints
625 : // that it is unsigned, take them into account
626 142 : if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
627 : {
628 3 : bSignedData = true;
629 : }
630 :
631 : // If we got valid_range, test for signed/unsigned range.
632 : // https://docs.unidata.ucar.edu/netcdf-c/current/attribute_conventions.html
633 142 : if (bValidRangeValid)
634 : {
635 : // If we got valid_range={0,255}, treat as unsigned.
636 123 : if (adfValidRange[0] == 0 && adfValidRange[1] == 255)
637 : {
638 115 : bSignedData = false;
639 : // Reset valid_range.
640 115 : bValidRangeValid = false;
641 : }
642 : // If we got valid_range={-128,127}, treat as signed.
643 8 : else if (adfValidRange[0] == -128 && adfValidRange[1] == 127)
644 : {
645 8 : bSignedData = true;
646 : // Reset valid_range.
647 8 : bValidRangeValid = false;
648 : }
649 : }
650 : // Else test for _Unsigned.
651 : // https://docs.unidata.ucar.edu/nug/current/best_practices.html
652 : else
653 : {
654 19 : if (bHasUnderscoreUnsignedAttr)
655 7 : bSignedData = !bUnderscoreUnsignedAttrVal;
656 : }
657 :
658 142 : if (bSignedData)
659 : {
660 20 : eDataType = GDT_Int8;
661 : }
662 122 : else if (dfNoData < 0)
663 : {
664 : // Fix nodata value as it was stored signed.
665 6 : dfNoData += 256;
666 6 : if (pszNoValueName)
667 : {
668 : // Updating metadata item
669 6 : GDALPamRasterBand::SetMetadataItem(
670 : pszNoValueName,
671 : CPLSPrintf("%d", static_cast<int>(dfNoData)));
672 : }
673 : }
674 : }
675 326 : else if (nc_datatype == NC_SHORT)
676 : {
677 41 : if (bHasUnderscoreUnsignedAttr)
678 : {
679 4 : bSignedData = !bUnderscoreUnsignedAttrVal;
680 4 : if (!bSignedData)
681 4 : eDataType = GDT_UInt16;
682 : }
683 :
684 : // Fix nodata value as it was stored signed.
685 41 : if (!bSignedData && dfNoData < 0)
686 : {
687 4 : dfNoData += 65536;
688 4 : if (pszNoValueName)
689 : {
690 : // Updating metadata item
691 4 : GDALPamRasterBand::SetMetadataItem(
692 : pszNoValueName,
693 : CPLSPrintf("%d", static_cast<int>(dfNoData)));
694 : }
695 : }
696 : }
697 :
698 285 : else if (nc_datatype == NC_UBYTE || nc_datatype == NC_USHORT ||
699 267 : nc_datatype == NC_UINT || nc_datatype == NC_UINT64)
700 : {
701 28 : bSignedData = false;
702 : }
703 :
704 468 : CPLDebug("GDAL_netCDF", "netcdf type=%d gdal type=%d signedByte=%d",
705 468 : nc_datatype, eDataType, static_cast<int>(bSignedData));
706 :
707 468 : if (bGotNoData)
708 : {
709 : // Set nodata value.
710 330 : if (bGotNoDataAsInt64)
711 : {
712 8 : if (eDataType == GDT_Int64)
713 : {
714 8 : SetNoDataValueNoUpdate(nNoDataAsInt64);
715 : }
716 0 : else if (eDataType == GDT_UInt64 && nNoDataAsInt64 >= 0)
717 : {
718 0 : SetNoDataValueNoUpdate(static_cast<uint64_t>(nNoDataAsInt64));
719 : }
720 : else
721 : {
722 0 : SetNoDataValueNoUpdate(static_cast<double>(nNoDataAsInt64));
723 : }
724 : }
725 322 : else if (bGotNoDataAsUInt64)
726 : {
727 7 : if (eDataType == GDT_UInt64)
728 : {
729 7 : SetNoDataValueNoUpdate(nNoDataAsUInt64);
730 : }
731 0 : else if (eDataType == GDT_Int64 &&
732 : nNoDataAsUInt64 <=
733 0 : static_cast<uint64_t>(
734 0 : std::numeric_limits<int64_t>::max()))
735 : {
736 0 : SetNoDataValueNoUpdate(static_cast<int64_t>(nNoDataAsUInt64));
737 : }
738 : else
739 : {
740 0 : SetNoDataValueNoUpdate(static_cast<double>(nNoDataAsUInt64));
741 : }
742 : }
743 : else
744 : {
745 : #ifdef NCDF_DEBUG
746 : CPLDebug("GDAL_netCDF", "SetNoDataValue(%f) read", dfNoData);
747 : #endif
748 315 : if (eDataType == GDT_Int64 && GDALIsValueExactAs<int64_t>(dfNoData))
749 : {
750 0 : SetNoDataValueNoUpdate(static_cast<int64_t>(dfNoData));
751 : }
752 315 : else if (eDataType == GDT_UInt64 &&
753 0 : GDALIsValueExactAs<uint64_t>(dfNoData))
754 : {
755 0 : SetNoDataValueNoUpdate(static_cast<uint64_t>(dfNoData));
756 : }
757 : else
758 : {
759 315 : SetNoDataValueNoUpdate(dfNoData);
760 : }
761 : }
762 : }
763 :
764 468 : CreateMetadataFromAttributes();
765 :
766 : // Attempt to fetch the scale_factor and add_offset attributes for the
767 : // variable and set them. If these values are not available, set
768 : // offset to 0 and scale to 1.
769 468 : if (nc_inq_attid(cdfid, nZId, CF_ADD_OFFSET, nullptr) == NC_NOERR)
770 : {
771 16 : double dfOffset = 0;
772 16 : status = nc_get_att_double(cdfid, nZId, CF_ADD_OFFSET, &dfOffset);
773 16 : CPLDebug("GDAL_netCDF", "got add_offset=%.16g, status=%d", dfOffset,
774 : status);
775 16 : SetOffsetNoUpdate(dfOffset);
776 : }
777 :
778 468 : bool bHasScale = false;
779 468 : if (nc_inq_attid(cdfid, nZId, CF_SCALE_FACTOR, nullptr) == NC_NOERR)
780 : {
781 20 : bHasScale = true;
782 20 : double dfScale = 1;
783 20 : status = nc_get_att_double(cdfid, nZId, CF_SCALE_FACTOR, &dfScale);
784 20 : CPLDebug("GDAL_netCDF", "got scale_factor=%.16g, status=%d", dfScale,
785 : status);
786 20 : SetScaleNoUpdate(dfScale);
787 : }
788 :
789 12 : if (bValidRangeValid && GDALDataTypeIsInteger(eDataType) &&
790 4 : eDataType != GDT_Int64 && eDataType != GDT_UInt64 &&
791 4 : (std::fabs(std::round(adfValidRange[0]) - adfValidRange[0]) > 1e-5 ||
792 480 : std::fabs(std::round(adfValidRange[1]) - adfValidRange[1]) > 1e-5) &&
793 1 : CSLFetchNameValue(poNCDFDS->GetOpenOptions(), "HONOUR_VALID_RANGE") ==
794 : nullptr)
795 : {
796 1 : CPLError(CE_Warning, CPLE_AppDefined,
797 : "validity range = %f, %f contains floating-point values, "
798 : "whereas data type is integer. valid_range is thus likely "
799 : "wrong%s. Ignoring it.",
800 : adfValidRange[0], adfValidRange[1],
801 : bHasScale ? " (likely scaled using scale_factor/add_factor "
802 : "whereas it should be using the packed data type)"
803 : : "");
804 1 : bValidRangeValid = false;
805 1 : adfValidRange[0] = 0.0;
806 1 : adfValidRange[1] = 0.0;
807 : }
808 :
809 : // Should we check for longitude values > 360?
810 468 : bCheckLongitude =
811 936 : CPLTestBool(CPLGetConfigOption("GDAL_NETCDF_CENTERLONG_180", "YES")) &&
812 468 : NCDFIsVarLongitude(cdfid, nZId, nullptr);
813 :
814 : // Attempt to fetch the units attribute for the variable and set it.
815 468 : SetUnitTypeNoUpdate(netCDFRasterBand::GetMetadataItem(CF_UNITS));
816 :
817 468 : SetBlockSize();
818 : }
819 :
820 648 : void netCDFRasterBand::SetBlockSize()
821 : {
822 : // Check for variable chunking (netcdf-4 only).
823 : // GDAL block size should be set to hdf5 chunk size.
824 648 : int nTmpFormat = 0;
825 648 : int status = nc_inq_format(cdfid, &nTmpFormat);
826 648 : NetCDFFormatEnum eTmpFormat = static_cast<NetCDFFormatEnum>(nTmpFormat);
827 648 : if ((status == NC_NOERR) &&
828 556 : (eTmpFormat == NCDF_FORMAT_NC4 || eTmpFormat == NCDF_FORMAT_NC4C))
829 : {
830 106 : size_t chunksize[MAX_NC_DIMS] = {};
831 : // Check for chunksize and set it as the blocksize (optimizes read).
832 106 : status = nc_inq_var_chunking(cdfid, nZId, &nTmpFormat, chunksize);
833 106 : if ((status == NC_NOERR) && (nTmpFormat == NC_CHUNKED))
834 : {
835 11 : nBlockXSize = (int)chunksize[nZDim - 1];
836 11 : if (nZDim >= 2)
837 11 : nBlockYSize = (int)chunksize[nZDim - 2];
838 : else
839 0 : nBlockYSize = 1;
840 : }
841 : }
842 :
843 : // Deal with bottom-up datasets and nBlockYSize != 1.
844 648 : auto poGDS = static_cast<netCDFDataset *>(poDS);
845 648 : if (poGDS->bBottomUp && nBlockYSize != 1 && poGDS->poChunkCache == nullptr)
846 : {
847 5 : if (poGDS->eAccess == GA_ReadOnly)
848 : {
849 : // Try to cache 1 or 2 'rows' of netCDF chunks along the whole
850 : // width of the raster
851 5 : size_t nChunks =
852 5 : static_cast<size_t>(DIV_ROUND_UP(nRasterXSize, nBlockXSize));
853 5 : if ((nRasterYSize % nBlockYSize) != 0)
854 1 : nChunks *= 2;
855 : const size_t nChunkSize =
856 5 : static_cast<size_t>(GDALGetDataTypeSizeBytes(eDataType)) *
857 5 : nBlockXSize * nBlockYSize;
858 5 : constexpr size_t MAX_CACHE_SIZE = 100 * 1024 * 1024;
859 5 : nChunks = std::min(nChunks, MAX_CACHE_SIZE / nChunkSize);
860 5 : if (nChunks)
861 : {
862 5 : poGDS->poChunkCache.reset(
863 5 : new netCDFDataset::ChunkCacheType(nChunks));
864 : }
865 : }
866 : else
867 : {
868 0 : nBlockYSize = 1;
869 : }
870 : }
871 648 : }
872 :
873 : // Constructor in create mode.
874 : // If nZId and following variables are not passed, the band will have 2
875 : // dimensions.
876 : // TODO: Get metadata, missing val from band #1 if nZDim > 2.
877 180 : netCDFRasterBand::netCDFRasterBand(
878 : const netCDFRasterBand::CONSTRUCTOR_CREATE &, netCDFDataset *poNCDFDS,
879 : const GDALDataType eTypeIn, int nBandIn, bool bSigned,
880 : const char *pszBandName, const char *pszLongName, int nZIdIn, int nZDimIn,
881 : int nLevelIn, const int *panBandZLevIn, const int *panBandZPosIn,
882 180 : const int *paDimIds)
883 180 : : nc_datatype(NC_NAT), cdfid(poNCDFDS->GetCDFID()), nZId(nZIdIn),
884 : nZDim(nZDimIn), nLevel(nLevelIn), nBandXPos(1), nBandYPos(0),
885 : panBandZPos(nullptr), panBandZLev(nullptr), bSignedData(bSigned),
886 180 : bCheckLongitude(false), m_bCreateMetadataFromOtherVarsDone(true)
887 : {
888 180 : poDS = poNCDFDS;
889 180 : nBand = nBandIn;
890 :
891 180 : nRasterXSize = poDS->GetRasterXSize();
892 180 : nRasterYSize = poDS->GetRasterYSize();
893 180 : nBlockXSize = poDS->GetRasterXSize();
894 180 : nBlockYSize = 1;
895 :
896 180 : if (poDS->GetAccess() != GA_Update)
897 : {
898 0 : CPLError(CE_Failure, CPLE_NotSupported,
899 : "Dataset is not in update mode, "
900 : "wrong netCDFRasterBand constructor");
901 0 : return;
902 : }
903 :
904 : // Take care of all other dimensions.
905 180 : if (nZDim > 2 && paDimIds != nullptr)
906 : {
907 27 : nBandXPos = panBandZPosIn[0];
908 27 : nBandYPos = panBandZPosIn[1];
909 :
910 27 : panBandZPos = static_cast<int *>(CPLCalloc(nZDim - 1, sizeof(int)));
911 27 : panBandZLev = static_cast<int *>(CPLCalloc(nZDim - 1, sizeof(int)));
912 :
913 76 : for (int i = 0; i < nZDim - 2; i++)
914 : {
915 49 : panBandZPos[i] = panBandZPosIn[i + 2];
916 49 : panBandZLev[i] = panBandZLevIn[i];
917 : }
918 : }
919 :
920 : // Get the type of the "z" variable, our target raster array.
921 180 : eDataType = eTypeIn;
922 :
923 180 : switch (eDataType)
924 : {
925 75 : case GDT_Byte:
926 75 : nc_datatype = NC_BYTE;
927 : // NC_UBYTE (unsigned byte) is only available for NC4.
928 75 : if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
929 3 : nc_datatype = NC_UBYTE;
930 75 : break;
931 7 : case GDT_Int8:
932 7 : nc_datatype = NC_BYTE;
933 7 : break;
934 11 : case GDT_Int16:
935 11 : nc_datatype = NC_SHORT;
936 11 : break;
937 24 : case GDT_Int32:
938 24 : nc_datatype = NC_INT;
939 24 : break;
940 13 : case GDT_Float32:
941 13 : nc_datatype = NC_FLOAT;
942 13 : break;
943 8 : case GDT_Float64:
944 8 : nc_datatype = NC_DOUBLE;
945 8 : break;
946 7 : case GDT_Int64:
947 7 : if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
948 : {
949 7 : nc_datatype = NC_INT64;
950 : }
951 : else
952 : {
953 0 : if (nBand == 1)
954 0 : CPLError(
955 : CE_Warning, CPLE_AppDefined,
956 : "Unsupported GDAL datatype %s, treat as NC_DOUBLE.",
957 : "Int64");
958 0 : nc_datatype = NC_DOUBLE;
959 0 : eDataType = GDT_Float64;
960 : }
961 7 : break;
962 7 : case GDT_UInt64:
963 7 : if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
964 : {
965 7 : nc_datatype = NC_UINT64;
966 : }
967 : else
968 : {
969 0 : if (nBand == 1)
970 0 : CPLError(
971 : CE_Warning, CPLE_AppDefined,
972 : "Unsupported GDAL datatype %s, treat as NC_DOUBLE.",
973 : "UInt64");
974 0 : nc_datatype = NC_DOUBLE;
975 0 : eDataType = GDT_Float64;
976 : }
977 7 : break;
978 6 : case GDT_UInt16:
979 6 : if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
980 : {
981 6 : nc_datatype = NC_USHORT;
982 6 : break;
983 : }
984 : [[fallthrough]];
985 : case GDT_UInt32:
986 6 : if (poNCDFDS->eFormat == NCDF_FORMAT_NC4)
987 : {
988 6 : nc_datatype = NC_UINT;
989 6 : break;
990 : }
991 : [[fallthrough]];
992 : default:
993 16 : if (nBand == 1)
994 8 : CPLError(CE_Warning, CPLE_AppDefined,
995 : "Unsupported GDAL datatype (%d), treat as NC_FLOAT.",
996 8 : static_cast<int>(eDataType));
997 16 : nc_datatype = NC_FLOAT;
998 16 : eDataType = GDT_Float32;
999 16 : break;
1000 : }
1001 :
1002 : // Define the variable if necessary (if nZId == -1).
1003 180 : bool bDefineVar = false;
1004 :
1005 180 : if (nZId == -1)
1006 : {
1007 158 : bDefineVar = true;
1008 :
1009 : // Make sure we are in define mode.
1010 158 : static_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
1011 :
1012 : char szTempPrivate[256 + 1];
1013 158 : const char *pszTemp = nullptr;
1014 158 : if (!pszBandName || EQUAL(pszBandName, ""))
1015 : {
1016 136 : snprintf(szTempPrivate, sizeof(szTempPrivate), "Band%d", nBand);
1017 136 : pszTemp = szTempPrivate;
1018 : }
1019 : else
1020 : {
1021 22 : pszTemp = pszBandName;
1022 : }
1023 :
1024 : int status;
1025 158 : if (nZDim > 2 && paDimIds != nullptr)
1026 : {
1027 5 : status =
1028 5 : nc_def_var(cdfid, pszTemp, nc_datatype, nZDim, paDimIds, &nZId);
1029 : }
1030 : else
1031 : {
1032 153 : int anBandDims[2] = {poNCDFDS->nYDimID, poNCDFDS->nXDimID};
1033 : status =
1034 153 : nc_def_var(cdfid, pszTemp, nc_datatype, 2, anBandDims, &nZId);
1035 : }
1036 158 : NCDF_ERR(status);
1037 158 : CPLDebug("GDAL_netCDF", "nc_def_var(%d,%s,%d) id=%d", cdfid, pszTemp,
1038 : nc_datatype, nZId);
1039 :
1040 158 : if (!pszLongName || EQUAL(pszLongName, ""))
1041 : {
1042 151 : snprintf(szTempPrivate, sizeof(szTempPrivate),
1043 : "GDAL Band Number %d", nBand);
1044 151 : pszTemp = szTempPrivate;
1045 : }
1046 : else
1047 : {
1048 7 : pszTemp = pszLongName;
1049 : }
1050 : status =
1051 158 : nc_put_att_text(cdfid, nZId, CF_LNG_NAME, strlen(pszTemp), pszTemp);
1052 158 : NCDF_ERR(status);
1053 :
1054 158 : poNCDFDS->DefVarDeflate(nZId, true);
1055 : }
1056 :
1057 : // For Byte data add signed/unsigned info.
1058 180 : if (eDataType == GDT_Byte || eDataType == GDT_Int8)
1059 : {
1060 82 : if (bDefineVar)
1061 : {
1062 : // Only add attributes if creating variable.
1063 : // For unsigned NC_BYTE (except NC4 format),
1064 : // add valid_range and _Unsigned ( defined in CF-1 and NUG ).
1065 74 : if (nc_datatype == NC_BYTE && poNCDFDS->eFormat != NCDF_FORMAT_NC4)
1066 : {
1067 71 : CPLDebug("GDAL_netCDF",
1068 : "adding valid_range attributes for Byte Band");
1069 71 : short l_adfValidRange[2] = {0, 0};
1070 : int status;
1071 71 : if (bSignedData || eDataType == GDT_Int8)
1072 : {
1073 7 : l_adfValidRange[0] = -128;
1074 7 : l_adfValidRange[1] = 127;
1075 7 : status =
1076 7 : nc_put_att_text(cdfid, nZId, "_Unsigned", 5, "false");
1077 : }
1078 : else
1079 : {
1080 64 : l_adfValidRange[0] = 0;
1081 64 : l_adfValidRange[1] = 255;
1082 : status =
1083 64 : nc_put_att_text(cdfid, nZId, "_Unsigned", 4, "true");
1084 : }
1085 71 : NCDF_ERR(status);
1086 71 : status = nc_put_att_short(cdfid, nZId, "valid_range", NC_SHORT,
1087 : 2, l_adfValidRange);
1088 71 : NCDF_ERR(status);
1089 : }
1090 : }
1091 : }
1092 :
1093 180 : if (nc_datatype != NC_BYTE && nc_datatype != NC_CHAR &&
1094 101 : nc_datatype != NC_UBYTE)
1095 : {
1096 : // Set default nodata.
1097 98 : bool bIgnored = false;
1098 : double dfNoData =
1099 98 : NCDFGetDefaultNoDataValue(cdfid, nZId, nc_datatype, bIgnored);
1100 : #ifdef NCDF_DEBUG
1101 : CPLDebug("GDAL_netCDF", "SetNoDataValue(%f) default", dfNoData);
1102 : #endif
1103 98 : netCDFRasterBand::SetNoDataValue(dfNoData);
1104 : }
1105 :
1106 180 : SetBlockSize();
1107 : }
1108 :
1109 : /************************************************************************/
1110 : /* ~netCDFRasterBand() */
1111 : /************************************************************************/
1112 :
1113 1296 : netCDFRasterBand::~netCDFRasterBand()
1114 : {
1115 648 : netCDFRasterBand::FlushCache(true);
1116 648 : CPLFree(panBandZPos);
1117 648 : CPLFree(panBandZLev);
1118 1296 : }
1119 :
1120 : /************************************************************************/
1121 : /* GetMetadata() */
1122 : /************************************************************************/
1123 :
1124 47 : char **netCDFRasterBand::GetMetadata(const char *pszDomain)
1125 : {
1126 47 : if (!m_bCreateMetadataFromOtherVarsDone)
1127 47 : CreateMetadataFromOtherVars();
1128 47 : return GDALPamRasterBand::GetMetadata(pszDomain);
1129 : }
1130 :
1131 : /************************************************************************/
1132 : /* GetMetadataItem() */
1133 : /************************************************************************/
1134 :
1135 537 : const char *netCDFRasterBand::GetMetadataItem(const char *pszName,
1136 : const char *pszDomain)
1137 : {
1138 537 : if (!m_bCreateMetadataFromOtherVarsDone &&
1139 521 : STARTS_WITH(pszName, "NETCDF_DIM_") &&
1140 1 : (!pszDomain || pszDomain[0] == 0))
1141 1 : CreateMetadataFromOtherVars();
1142 537 : return GDALPamRasterBand::GetMetadataItem(pszName, pszDomain);
1143 : }
1144 :
1145 : /************************************************************************/
1146 : /* SetMetadataItem() */
1147 : /************************************************************************/
1148 :
1149 7 : CPLErr netCDFRasterBand::SetMetadataItem(const char *pszName,
1150 : const char *pszValue,
1151 : const char *pszDomain)
1152 : {
1153 9 : if (GetAccess() == GA_Update &&
1154 9 : (pszDomain == nullptr || pszDomain[0] == '\0') && pszValue != nullptr)
1155 : {
1156 : // Same logic as in CopyMetadata()
1157 :
1158 2 : const char *const papszIgnoreBand[] = {
1159 : CF_ADD_OFFSET, CF_SCALE_FACTOR, "valid_range", "_Unsigned",
1160 : NCDF_FillValue, "coordinates", nullptr};
1161 : // Do not copy varname, stats, NETCDF_DIM_*, nodata
1162 : // and items in papszIgnoreBand.
1163 6 : if (STARTS_WITH(pszName, "NETCDF_VARNAME") ||
1164 2 : STARTS_WITH(pszName, "STATISTICS_") ||
1165 2 : STARTS_WITH(pszName, "NETCDF_DIM_") ||
1166 2 : STARTS_WITH(pszName, "missing_value") ||
1167 6 : STARTS_WITH(pszName, "_FillValue") ||
1168 2 : CSLFindString(papszIgnoreBand, pszName) != -1)
1169 : {
1170 : // do nothing
1171 : }
1172 : else
1173 : {
1174 2 : cpl::down_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
1175 :
1176 2 : if (!NCDFPutAttr(cdfid, nZId, pszName, pszValue))
1177 2 : return CE_Failure;
1178 : }
1179 : }
1180 :
1181 5 : return GDALPamRasterBand::SetMetadataItem(pszName, pszValue, pszDomain);
1182 : }
1183 :
1184 : /************************************************************************/
1185 : /* SetMetadata() */
1186 : /************************************************************************/
1187 :
1188 2 : CPLErr netCDFRasterBand::SetMetadata(char **papszMD, const char *pszDomain)
1189 : {
1190 4 : if (GetAccess() == GA_Update &&
1191 2 : (pszDomain == nullptr || pszDomain[0] == '\0'))
1192 : {
1193 : // We don't handle metadata item removal for now
1194 4 : for (const char *const *papszIter = papszMD; papszIter && *papszIter;
1195 : ++papszIter)
1196 : {
1197 2 : char *pszName = nullptr;
1198 2 : const char *pszValue = CPLParseNameValue(*papszIter, &pszName);
1199 2 : if (pszName && pszValue)
1200 2 : SetMetadataItem(pszName, pszValue);
1201 2 : CPLFree(pszName);
1202 : }
1203 : }
1204 2 : return GDALPamRasterBand::SetMetadata(papszMD, pszDomain);
1205 : }
1206 :
1207 : /************************************************************************/
1208 : /* GetOffset() */
1209 : /************************************************************************/
1210 49 : double netCDFRasterBand::GetOffset(int *pbSuccess)
1211 : {
1212 49 : if (pbSuccess != nullptr)
1213 44 : *pbSuccess = static_cast<int>(m_bHaveOffset);
1214 :
1215 49 : return m_dfOffset;
1216 : }
1217 :
1218 : /************************************************************************/
1219 : /* SetOffset() */
1220 : /************************************************************************/
1221 1 : CPLErr netCDFRasterBand::SetOffset(double dfNewOffset)
1222 : {
1223 2 : CPLMutexHolderD(&hNCMutex);
1224 :
1225 : // Write value if in update mode.
1226 1 : if (poDS->GetAccess() == GA_Update)
1227 : {
1228 : // Make sure we are in define mode.
1229 1 : static_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
1230 :
1231 1 : const int status = nc_put_att_double(cdfid, nZId, CF_ADD_OFFSET,
1232 : NC_DOUBLE, 1, &dfNewOffset);
1233 :
1234 1 : NCDF_ERR(status);
1235 1 : if (status == NC_NOERR)
1236 : {
1237 1 : SetOffsetNoUpdate(dfNewOffset);
1238 1 : return CE_None;
1239 : }
1240 :
1241 0 : return CE_Failure;
1242 : }
1243 :
1244 0 : SetOffsetNoUpdate(dfNewOffset);
1245 0 : return CE_None;
1246 : }
1247 :
1248 : /************************************************************************/
1249 : /* SetOffsetNoUpdate() */
1250 : /************************************************************************/
1251 17 : void netCDFRasterBand::SetOffsetNoUpdate(double dfVal)
1252 : {
1253 17 : m_dfOffset = dfVal;
1254 17 : m_bHaveOffset = true;
1255 17 : }
1256 :
1257 : /************************************************************************/
1258 : /* GetScale() */
1259 : /************************************************************************/
1260 49 : double netCDFRasterBand::GetScale(int *pbSuccess)
1261 : {
1262 49 : if (pbSuccess != nullptr)
1263 44 : *pbSuccess = static_cast<int>(m_bHaveScale);
1264 :
1265 49 : return m_dfScale;
1266 : }
1267 :
1268 : /************************************************************************/
1269 : /* SetScale() */
1270 : /************************************************************************/
1271 1 : CPLErr netCDFRasterBand::SetScale(double dfNewScale)
1272 : {
1273 2 : CPLMutexHolderD(&hNCMutex);
1274 :
1275 : // Write value if in update mode.
1276 1 : if (poDS->GetAccess() == GA_Update)
1277 : {
1278 : // Make sure we are in define mode.
1279 1 : static_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
1280 :
1281 1 : const int status = nc_put_att_double(cdfid, nZId, CF_SCALE_FACTOR,
1282 : NC_DOUBLE, 1, &dfNewScale);
1283 :
1284 1 : NCDF_ERR(status);
1285 1 : if (status == NC_NOERR)
1286 : {
1287 1 : SetScaleNoUpdate(dfNewScale);
1288 1 : return CE_None;
1289 : }
1290 :
1291 0 : return CE_Failure;
1292 : }
1293 :
1294 0 : SetScaleNoUpdate(dfNewScale);
1295 0 : return CE_None;
1296 : }
1297 :
1298 : /************************************************************************/
1299 : /* SetScaleNoUpdate() */
1300 : /************************************************************************/
1301 21 : void netCDFRasterBand::SetScaleNoUpdate(double dfVal)
1302 : {
1303 21 : m_dfScale = dfVal;
1304 21 : m_bHaveScale = true;
1305 21 : }
1306 :
1307 : /************************************************************************/
1308 : /* GetUnitType() */
1309 : /************************************************************************/
1310 :
1311 21 : const char *netCDFRasterBand::GetUnitType()
1312 :
1313 : {
1314 21 : if (!m_osUnitType.empty())
1315 6 : return m_osUnitType;
1316 :
1317 15 : return GDALRasterBand::GetUnitType();
1318 : }
1319 :
1320 : /************************************************************************/
1321 : /* SetUnitType() */
1322 : /************************************************************************/
1323 :
1324 1 : CPLErr netCDFRasterBand::SetUnitType(const char *pszNewValue)
1325 :
1326 : {
1327 2 : CPLMutexHolderD(&hNCMutex);
1328 :
1329 2 : const std::string osUnitType = (pszNewValue != nullptr ? pszNewValue : "");
1330 :
1331 1 : if (!osUnitType.empty())
1332 : {
1333 : // Write value if in update mode.
1334 1 : if (poDS->GetAccess() == GA_Update)
1335 : {
1336 : // Make sure we are in define mode.
1337 1 : static_cast<netCDFDataset *>(poDS)->SetDefineMode(TRUE);
1338 :
1339 1 : const int status = nc_put_att_text(
1340 : cdfid, nZId, CF_UNITS, osUnitType.size(), osUnitType.c_str());
1341 :
1342 1 : NCDF_ERR(status);
1343 1 : if (status == NC_NOERR)
1344 : {
1345 1 : SetUnitTypeNoUpdate(pszNewValue);
1346 1 : return CE_None;
1347 : }
1348 :
1349 0 : return CE_Failure;
1350 : }
1351 : }
1352 :
1353 0 : SetUnitTypeNoUpdate(pszNewValue);
1354 :
1355 0 : return CE_None;
1356 : }
1357 :
1358 : /************************************************************************/
1359 : /* SetUnitTypeNoUpdate() */
1360 : /************************************************************************/
1361 :
1362 469 : void netCDFRasterBand::SetUnitTypeNoUpdate(const char *pszNewValue)
1363 : {
1364 469 : m_osUnitType = (pszNewValue != nullptr ? pszNewValue : "");
1365 469 : }
1366 :
1367 : /************************************************************************/
1368 : /* GetNoDataValue() */
1369 : /************************************************************************/
1370 :
1371 153 : double netCDFRasterBand::GetNoDataValue(int *pbSuccess)
1372 :
1373 : {
1374 153 : if (m_bNoDataSetAsInt64)
1375 : {
1376 0 : if (pbSuccess)
1377 0 : *pbSuccess = TRUE;
1378 0 : return GDALGetNoDataValueCastToDouble(m_nNodataValueInt64);
1379 : }
1380 :
1381 153 : if (m_bNoDataSetAsUInt64)
1382 : {
1383 0 : if (pbSuccess)
1384 0 : *pbSuccess = TRUE;
1385 0 : return GDALGetNoDataValueCastToDouble(m_nNodataValueUInt64);
1386 : }
1387 :
1388 153 : if (m_bNoDataSet)
1389 : {
1390 118 : if (pbSuccess)
1391 102 : *pbSuccess = TRUE;
1392 118 : return m_dfNoDataValue;
1393 : }
1394 :
1395 35 : return GDALPamRasterBand::GetNoDataValue(pbSuccess);
1396 : }
1397 :
1398 : /************************************************************************/
1399 : /* GetNoDataValueAsInt64() */
1400 : /************************************************************************/
1401 :
1402 4 : int64_t netCDFRasterBand::GetNoDataValueAsInt64(int *pbSuccess)
1403 :
1404 : {
1405 4 : if (m_bNoDataSetAsInt64)
1406 : {
1407 4 : if (pbSuccess)
1408 4 : *pbSuccess = TRUE;
1409 :
1410 4 : return m_nNodataValueInt64;
1411 : }
1412 :
1413 0 : return GDALPamRasterBand::GetNoDataValueAsInt64(pbSuccess);
1414 : }
1415 :
1416 : /************************************************************************/
1417 : /* GetNoDataValueAsUInt64() */
1418 : /************************************************************************/
1419 :
1420 4 : uint64_t netCDFRasterBand::GetNoDataValueAsUInt64(int *pbSuccess)
1421 :
1422 : {
1423 4 : if (m_bNoDataSetAsUInt64)
1424 : {
1425 4 : if (pbSuccess)
1426 4 : *pbSuccess = TRUE;
1427 :
1428 4 : return m_nNodataValueUInt64;
1429 : }
1430 :
1431 0 : return GDALPamRasterBand::GetNoDataValueAsUInt64(pbSuccess);
1432 : }
1433 :
1434 : /************************************************************************/
1435 : /* SetNoDataValue() */
1436 : /************************************************************************/
1437 :
1438 134 : CPLErr netCDFRasterBand::SetNoDataValue(double dfNoData)
1439 :
1440 : {
1441 268 : CPLMutexHolderD(&hNCMutex);
1442 :
1443 : // If already set to new value, don't do anything.
1444 134 : if (m_bNoDataSet && CPLIsEqual(dfNoData, m_dfNoDataValue))
1445 19 : return CE_None;
1446 :
1447 : // Write value if in update mode.
1448 115 : if (poDS->GetAccess() == GA_Update)
1449 : {
1450 : // netcdf-4 does not allow to set _FillValue after leaving define mode,
1451 : // but it is ok if variable has not been written to, so only print
1452 : // debug. See bug #4484.
1453 125 : if (m_bNoDataSet &&
1454 10 : !reinterpret_cast<netCDFDataset *>(poDS)->GetDefineMode())
1455 : {
1456 0 : CPLDebug("GDAL_netCDF",
1457 : "Setting NoDataValue to %.17g (previously set to %.17g) "
1458 : "but file is no longer in define mode (id #%d, band #%d)",
1459 : dfNoData, m_dfNoDataValue, cdfid, nBand);
1460 : }
1461 : #ifdef NCDF_DEBUG
1462 : else
1463 : {
1464 : CPLDebug("GDAL_netCDF",
1465 : "Setting NoDataValue to %.17g (id #%d, band #%d)",
1466 : dfNoData, cdfid, nBand);
1467 : }
1468 : #endif
1469 : // Make sure we are in define mode.
1470 115 : reinterpret_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
1471 :
1472 : int status;
1473 115 : if (eDataType == GDT_Byte)
1474 : {
1475 6 : if (bSignedData)
1476 : {
1477 0 : signed char cNoDataValue = static_cast<signed char>(dfNoData);
1478 0 : status = nc_put_att_schar(cdfid, nZId, NCDF_FillValue,
1479 : nc_datatype, 1, &cNoDataValue);
1480 : }
1481 : else
1482 : {
1483 6 : const unsigned char ucNoDataValue =
1484 6 : static_cast<unsigned char>(dfNoData);
1485 6 : status = nc_put_att_uchar(cdfid, nZId, NCDF_FillValue,
1486 : nc_datatype, 1, &ucNoDataValue);
1487 : }
1488 : }
1489 109 : else if (eDataType == GDT_Int16)
1490 : {
1491 14 : short nsNoDataValue = static_cast<short>(dfNoData);
1492 14 : status = nc_put_att_short(cdfid, nZId, NCDF_FillValue, nc_datatype,
1493 : 1, &nsNoDataValue);
1494 : }
1495 95 : else if (eDataType == GDT_Int32)
1496 : {
1497 27 : int nNoDataValue = static_cast<int>(dfNoData);
1498 27 : status = nc_put_att_int(cdfid, nZId, NCDF_FillValue, nc_datatype, 1,
1499 : &nNoDataValue);
1500 : }
1501 68 : else if (eDataType == GDT_Float32)
1502 : {
1503 31 : float fNoDataValue = static_cast<float>(dfNoData);
1504 31 : status = nc_put_att_float(cdfid, nZId, NCDF_FillValue, nc_datatype,
1505 : 1, &fNoDataValue);
1506 : }
1507 37 : else if (eDataType == GDT_UInt16 &&
1508 6 : reinterpret_cast<netCDFDataset *>(poDS)->eFormat ==
1509 : NCDF_FORMAT_NC4)
1510 : {
1511 6 : unsigned short usNoDataValue =
1512 6 : static_cast<unsigned short>(dfNoData);
1513 6 : status = nc_put_att_ushort(cdfid, nZId, NCDF_FillValue, nc_datatype,
1514 6 : 1, &usNoDataValue);
1515 : }
1516 31 : else if (eDataType == GDT_UInt32 &&
1517 7 : reinterpret_cast<netCDFDataset *>(poDS)->eFormat ==
1518 : NCDF_FORMAT_NC4)
1519 : {
1520 7 : unsigned int unNoDataValue = static_cast<unsigned int>(dfNoData);
1521 7 : status = nc_put_att_uint(cdfid, nZId, NCDF_FillValue, nc_datatype,
1522 7 : 1, &unNoDataValue);
1523 : }
1524 : else
1525 : {
1526 24 : status = nc_put_att_double(cdfid, nZId, NCDF_FillValue, nc_datatype,
1527 : 1, &dfNoData);
1528 : }
1529 :
1530 115 : NCDF_ERR(status);
1531 :
1532 : // Update status if write worked.
1533 115 : if (status == NC_NOERR)
1534 : {
1535 115 : SetNoDataValueNoUpdate(dfNoData);
1536 115 : return CE_None;
1537 : }
1538 :
1539 0 : return CE_Failure;
1540 : }
1541 :
1542 0 : SetNoDataValueNoUpdate(dfNoData);
1543 0 : return CE_None;
1544 : }
1545 :
1546 : /************************************************************************/
1547 : /* SetNoDataValueNoUpdate() */
1548 : /************************************************************************/
1549 :
1550 430 : void netCDFRasterBand::SetNoDataValueNoUpdate(double dfNoData)
1551 : {
1552 430 : m_dfNoDataValue = dfNoData;
1553 430 : m_bNoDataSet = true;
1554 430 : m_bNoDataSetAsInt64 = false;
1555 430 : m_bNoDataSetAsUInt64 = false;
1556 430 : }
1557 :
1558 : /************************************************************************/
1559 : /* SetNoDataValueAsInt64() */
1560 : /************************************************************************/
1561 :
1562 3 : CPLErr netCDFRasterBand::SetNoDataValueAsInt64(int64_t nNoData)
1563 :
1564 : {
1565 6 : CPLMutexHolderD(&hNCMutex);
1566 :
1567 : // If already set to new value, don't do anything.
1568 3 : if (m_bNoDataSetAsInt64 && nNoData == m_nNodataValueInt64)
1569 0 : return CE_None;
1570 :
1571 : // Write value if in update mode.
1572 3 : if (poDS->GetAccess() == GA_Update)
1573 : {
1574 : // netcdf-4 does not allow to set NCDF_FillValue after leaving define mode,
1575 : // but it is ok if variable has not been written to, so only print
1576 : // debug. See bug #4484.
1577 3 : if (m_bNoDataSetAsInt64 &&
1578 0 : !reinterpret_cast<netCDFDataset *>(poDS)->GetDefineMode())
1579 : {
1580 0 : CPLDebug("GDAL_netCDF",
1581 : "Setting NoDataValue to " CPL_FRMT_GIB
1582 : " (previously set to " CPL_FRMT_GIB ") "
1583 : "but file is no longer in define mode (id #%d, band #%d)",
1584 : static_cast<GIntBig>(nNoData),
1585 0 : static_cast<GIntBig>(m_nNodataValueInt64), cdfid, nBand);
1586 : }
1587 : #ifdef NCDF_DEBUG
1588 : else
1589 : {
1590 : CPLDebug("GDAL_netCDF",
1591 : "Setting NoDataValue to " CPL_FRMT_GIB
1592 : " (id #%d, band #%d)",
1593 : static_cast<GIntBig>(nNoData), cdfid, nBand);
1594 : }
1595 : #endif
1596 : // Make sure we are in define mode.
1597 3 : reinterpret_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
1598 :
1599 : int status;
1600 3 : if (eDataType == GDT_Int64 &&
1601 3 : reinterpret_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
1602 : {
1603 3 : long long tmp = static_cast<long long>(nNoData);
1604 3 : status = nc_put_att_longlong(cdfid, nZId, NCDF_FillValue,
1605 3 : nc_datatype, 1, &tmp);
1606 : }
1607 : else
1608 : {
1609 0 : double dfNoData = static_cast<double>(nNoData);
1610 0 : status = nc_put_att_double(cdfid, nZId, NCDF_FillValue, nc_datatype,
1611 : 1, &dfNoData);
1612 : }
1613 :
1614 3 : NCDF_ERR(status);
1615 :
1616 : // Update status if write worked.
1617 3 : if (status == NC_NOERR)
1618 : {
1619 3 : SetNoDataValueNoUpdate(nNoData);
1620 3 : return CE_None;
1621 : }
1622 :
1623 0 : return CE_Failure;
1624 : }
1625 :
1626 0 : SetNoDataValueNoUpdate(nNoData);
1627 0 : return CE_None;
1628 : }
1629 :
1630 : /************************************************************************/
1631 : /* SetNoDataValueNoUpdate() */
1632 : /************************************************************************/
1633 :
1634 11 : void netCDFRasterBand::SetNoDataValueNoUpdate(int64_t nNoData)
1635 : {
1636 11 : m_nNodataValueInt64 = nNoData;
1637 11 : m_bNoDataSet = false;
1638 11 : m_bNoDataSetAsInt64 = true;
1639 11 : m_bNoDataSetAsUInt64 = false;
1640 11 : }
1641 :
1642 : /************************************************************************/
1643 : /* SetNoDataValueAsUInt64() */
1644 : /************************************************************************/
1645 :
1646 3 : CPLErr netCDFRasterBand::SetNoDataValueAsUInt64(uint64_t nNoData)
1647 :
1648 : {
1649 6 : CPLMutexHolderD(&hNCMutex);
1650 :
1651 : // If already set to new value, don't do anything.
1652 3 : if (m_bNoDataSetAsUInt64 && nNoData == m_nNodataValueUInt64)
1653 0 : return CE_None;
1654 :
1655 : // Write value if in update mode.
1656 3 : if (poDS->GetAccess() == GA_Update)
1657 : {
1658 : // netcdf-4 does not allow to set _FillValue after leaving define mode,
1659 : // but it is ok if variable has not been written to, so only print
1660 : // debug. See bug #4484.
1661 3 : if (m_bNoDataSetAsUInt64 &&
1662 0 : !reinterpret_cast<netCDFDataset *>(poDS)->GetDefineMode())
1663 : {
1664 0 : CPLDebug("GDAL_netCDF",
1665 : "Setting NoDataValue to " CPL_FRMT_GUIB
1666 : " (previously set to " CPL_FRMT_GUIB ") "
1667 : "but file is no longer in define mode (id #%d, band #%d)",
1668 : static_cast<GUIntBig>(nNoData),
1669 0 : static_cast<GUIntBig>(m_nNodataValueUInt64), cdfid, nBand);
1670 : }
1671 : #ifdef NCDF_DEBUG
1672 : else
1673 : {
1674 : CPLDebug("GDAL_netCDF",
1675 : "Setting NoDataValue to " CPL_FRMT_GUIB
1676 : " (id #%d, band #%d)",
1677 : static_cast<GUIntBig>(nNoData), cdfid, nBand);
1678 : }
1679 : #endif
1680 : // Make sure we are in define mode.
1681 3 : reinterpret_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
1682 :
1683 : int status;
1684 3 : if (eDataType == GDT_UInt64 &&
1685 3 : reinterpret_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
1686 : {
1687 3 : unsigned long long tmp = static_cast<long long>(nNoData);
1688 3 : status = nc_put_att_ulonglong(cdfid, nZId, NCDF_FillValue,
1689 3 : nc_datatype, 1, &tmp);
1690 : }
1691 : else
1692 : {
1693 0 : double dfNoData = static_cast<double>(nNoData);
1694 0 : status = nc_put_att_double(cdfid, nZId, NCDF_FillValue, nc_datatype,
1695 : 1, &dfNoData);
1696 : }
1697 :
1698 3 : NCDF_ERR(status);
1699 :
1700 : // Update status if write worked.
1701 3 : if (status == NC_NOERR)
1702 : {
1703 3 : SetNoDataValueNoUpdate(nNoData);
1704 3 : return CE_None;
1705 : }
1706 :
1707 0 : return CE_Failure;
1708 : }
1709 :
1710 0 : SetNoDataValueNoUpdate(nNoData);
1711 0 : return CE_None;
1712 : }
1713 :
1714 : /************************************************************************/
1715 : /* SetNoDataValueNoUpdate() */
1716 : /************************************************************************/
1717 :
1718 10 : void netCDFRasterBand::SetNoDataValueNoUpdate(uint64_t nNoData)
1719 : {
1720 10 : m_nNodataValueUInt64 = nNoData;
1721 10 : m_bNoDataSet = false;
1722 10 : m_bNoDataSetAsInt64 = false;
1723 10 : m_bNoDataSetAsUInt64 = true;
1724 10 : }
1725 :
1726 : /************************************************************************/
1727 : /* DeleteNoDataValue() */
1728 : /************************************************************************/
1729 :
1730 : #ifdef notdef
1731 : CPLErr netCDFRasterBand::DeleteNoDataValue()
1732 :
1733 : {
1734 : CPLMutexHolderD(&hNCMutex);
1735 :
1736 : if (!bNoDataSet)
1737 : return CE_None;
1738 :
1739 : // Write value if in update mode.
1740 : if (poDS->GetAccess() == GA_Update)
1741 : {
1742 : // Make sure we are in define mode.
1743 : static_cast<netCDFDataset *>(poDS)->SetDefineMode(true);
1744 :
1745 : status = nc_del_att(cdfid, nZId, NCDF_FillValue);
1746 :
1747 : NCDF_ERR(status);
1748 :
1749 : // Update status if write worked.
1750 : if (status == NC_NOERR)
1751 : {
1752 : dfNoDataValue = 0.0;
1753 : bNoDataSet = false;
1754 : return CE_None;
1755 : }
1756 :
1757 : return CE_Failure;
1758 : }
1759 :
1760 : dfNoDataValue = 0.0;
1761 : bNoDataSet = false;
1762 : return CE_None;
1763 : }
1764 : #endif
1765 :
1766 : /************************************************************************/
1767 : /* SerializeToXML() */
1768 : /************************************************************************/
1769 :
1770 5 : CPLXMLNode *netCDFRasterBand::SerializeToXML(const char * /* pszUnused */)
1771 : {
1772 : // Overridden from GDALPamDataset to add only band histogram
1773 : // and statistics. See bug #4244.
1774 5 : if (psPam == nullptr)
1775 0 : return nullptr;
1776 :
1777 : // Setup root node and attributes.
1778 : CPLXMLNode *psTree =
1779 5 : CPLCreateXMLNode(nullptr, CXT_Element, "PAMRasterBand");
1780 :
1781 5 : if (GetBand() > 0)
1782 : {
1783 10 : CPLString oFmt;
1784 5 : CPLSetXMLValue(psTree, "#band", oFmt.Printf("%d", GetBand()));
1785 : }
1786 :
1787 : // Histograms.
1788 5 : if (psPam->psSavedHistograms != nullptr)
1789 1 : CPLAddXMLChild(psTree, CPLCloneXMLTree(psPam->psSavedHistograms));
1790 :
1791 : // Metadata (statistics only).
1792 5 : GDALMultiDomainMetadata oMDMDStats;
1793 5 : const char *papszMDStats[] = {"STATISTICS_MINIMUM", "STATISTICS_MAXIMUM",
1794 : "STATISTICS_MEAN", "STATISTICS_STDDEV",
1795 : nullptr};
1796 25 : for (int i = 0; i < CSLCount(papszMDStats); i++)
1797 : {
1798 20 : const char *pszMDI = GetMetadataItem(papszMDStats[i]);
1799 20 : if (pszMDI)
1800 4 : oMDMDStats.SetMetadataItem(papszMDStats[i], pszMDI);
1801 : }
1802 5 : CPLXMLNode *psMD = oMDMDStats.Serialize();
1803 :
1804 5 : if (psMD != nullptr)
1805 : {
1806 1 : if (psMD->psChild == nullptr)
1807 0 : CPLDestroyXMLNode(psMD);
1808 : else
1809 1 : CPLAddXMLChild(psTree, psMD);
1810 : }
1811 :
1812 : // We don't want to return anything if we had no metadata to attach.
1813 5 : if (psTree->psChild == nullptr || psTree->psChild->psNext == nullptr)
1814 : {
1815 3 : CPLDestroyXMLNode(psTree);
1816 3 : psTree = nullptr;
1817 : }
1818 :
1819 5 : return psTree;
1820 : }
1821 :
1822 : /************************************************************************/
1823 : /* Get1DVariableIndexedByDimension() */
1824 : /************************************************************************/
1825 :
1826 79 : static int Get1DVariableIndexedByDimension(int cdfid, int nDimId,
1827 : const char *pszDimName,
1828 : bool bVerboseError, int *pnGroupID)
1829 : {
1830 79 : *pnGroupID = -1;
1831 79 : int nVarID = -1;
1832 : // First try to find a variable whose name is identical to the dimension
1833 : // name, and check that it is indeed indexed by this dimension
1834 79 : if (NCDFResolveVar(cdfid, pszDimName, pnGroupID, &nVarID) == CE_None)
1835 : {
1836 65 : int nDimCountOfVariable = 0;
1837 65 : nc_inq_varndims(*pnGroupID, nVarID, &nDimCountOfVariable);
1838 65 : if (nDimCountOfVariable == 1)
1839 : {
1840 65 : int nDimIdOfVariable = -1;
1841 65 : nc_inq_vardimid(*pnGroupID, nVarID, &nDimIdOfVariable);
1842 65 : if (nDimIdOfVariable == nDimId)
1843 : {
1844 65 : return nVarID;
1845 : }
1846 : }
1847 : }
1848 :
1849 : // Otherwise iterate over the variables to find potential candidates
1850 : // TODO: should be modified to search also in other groups using the same
1851 : // logic than in NCDFResolveVar(), but maybe not needed if it's a
1852 : // very rare case? and I think this is not CF compliant.
1853 14 : int nvars = 0;
1854 14 : CPL_IGNORE_RET_VAL(nc_inq(cdfid, nullptr, &nvars, nullptr, nullptr));
1855 :
1856 14 : int nCountCandidateVars = 0;
1857 14 : int nCandidateVarID = -1;
1858 65 : for (int k = 0; k < nvars; k++)
1859 : {
1860 51 : int nDimCountOfVariable = 0;
1861 51 : nc_inq_varndims(cdfid, k, &nDimCountOfVariable);
1862 51 : if (nDimCountOfVariable == 1)
1863 : {
1864 27 : int nDimIdOfVariable = -1;
1865 27 : nc_inq_vardimid(cdfid, k, &nDimIdOfVariable);
1866 27 : if (nDimIdOfVariable == nDimId)
1867 : {
1868 7 : nCountCandidateVars++;
1869 7 : nCandidateVarID = k;
1870 : }
1871 : }
1872 : }
1873 14 : if (nCountCandidateVars > 1)
1874 : {
1875 1 : if (bVerboseError)
1876 : {
1877 1 : CPLError(CE_Warning, CPLE_AppDefined,
1878 : "Several 1D variables are indexed by dimension %s",
1879 : pszDimName);
1880 : }
1881 1 : *pnGroupID = -1;
1882 1 : return -1;
1883 : }
1884 13 : else if (nCandidateVarID < 0)
1885 : {
1886 8 : if (bVerboseError)
1887 : {
1888 8 : CPLError(CE_Warning, CPLE_AppDefined,
1889 : "No 1D variable is indexed by dimension %s", pszDimName);
1890 : }
1891 : }
1892 13 : *pnGroupID = cdfid;
1893 13 : return nCandidateVarID;
1894 : }
1895 :
1896 : /************************************************************************/
1897 : /* CreateMetadataFromAttributes() */
1898 : /************************************************************************/
1899 :
1900 468 : void netCDFRasterBand::CreateMetadataFromAttributes()
1901 : {
1902 468 : char szVarName[NC_MAX_NAME + 1] = {};
1903 468 : int status = nc_inq_varname(cdfid, nZId, szVarName);
1904 468 : NCDF_ERR(status);
1905 :
1906 468 : GDALPamRasterBand::SetMetadataItem("NETCDF_VARNAME", szVarName);
1907 :
1908 : // Get attribute metadata.
1909 468 : int nAtt = 0;
1910 468 : NCDF_ERR(nc_inq_varnatts(cdfid, nZId, &nAtt));
1911 :
1912 1972 : for (int i = 0; i < nAtt; i++)
1913 : {
1914 1504 : char szMetaName[NC_MAX_NAME + 1] = {};
1915 1504 : status = nc_inq_attname(cdfid, nZId, i, szMetaName);
1916 1504 : if (status != NC_NOERR)
1917 12 : continue;
1918 :
1919 1504 : if (GDALPamRasterBand::GetMetadataItem(szMetaName) != nullptr)
1920 : {
1921 12 : continue;
1922 : }
1923 :
1924 1492 : char *pszMetaValue = nullptr;
1925 1492 : if (NCDFGetAttr(cdfid, nZId, szMetaName, &pszMetaValue) == CE_None)
1926 : {
1927 1492 : GDALPamRasterBand::SetMetadataItem(szMetaName, pszMetaValue);
1928 : }
1929 : else
1930 : {
1931 0 : CPLDebug("GDAL_netCDF", "invalid Band metadata %s", szMetaName);
1932 : }
1933 :
1934 1492 : if (pszMetaValue)
1935 : {
1936 1492 : CPLFree(pszMetaValue);
1937 1492 : pszMetaValue = nullptr;
1938 : }
1939 : }
1940 468 : }
1941 :
1942 : /************************************************************************/
1943 : /* CreateMetadataFromOtherVars() */
1944 : /************************************************************************/
1945 :
1946 48 : void netCDFRasterBand::CreateMetadataFromOtherVars()
1947 :
1948 : {
1949 48 : CPLAssert(!m_bCreateMetadataFromOtherVarsDone);
1950 48 : m_bCreateMetadataFromOtherVarsDone = true;
1951 :
1952 48 : netCDFDataset *l_poDS = reinterpret_cast<netCDFDataset *>(poDS);
1953 48 : const int nPamFlagsBackup = l_poDS->nPamFlags;
1954 :
1955 : // Compute all dimensions from Band number and save in Metadata.
1956 48 : int nd = 0;
1957 48 : nc_inq_varndims(cdfid, nZId, &nd);
1958 : // Compute multidimention band position.
1959 : //
1960 : // BandPosition = (Total - sum(PastBandLevels) - 1)/sum(remainingLevels)
1961 : // if Data[2,3,4,x,y]
1962 : //
1963 : // BandPos0 = (nBand) / (3*4)
1964 : // BandPos1 = (nBand - BandPos0*(3*4)) / (4)
1965 : // BandPos2 = (nBand - BandPos0*(3*4)) % (4)
1966 :
1967 48 : int Sum = 1;
1968 48 : if (nd == 3)
1969 : {
1970 5 : Sum *= panBandZLev[0];
1971 : }
1972 :
1973 : // Loop over non-spatial dimensions.
1974 48 : int Taken = 0;
1975 :
1976 88 : for (int i = 0; i < nd - 2; i++)
1977 : {
1978 : int result;
1979 40 : if (i != nd - 2 - 1)
1980 : {
1981 18 : Sum = 1;
1982 37 : for (int j = i + 1; j < nd - 2; j++)
1983 : {
1984 19 : Sum *= panBandZLev[j];
1985 : }
1986 18 : result = static_cast<int>((nLevel - Taken) / Sum);
1987 : }
1988 : else
1989 : {
1990 22 : result = static_cast<int>((nLevel - Taken) % Sum);
1991 : }
1992 :
1993 40 : char szName[NC_MAX_NAME + 1] = {};
1994 40 : snprintf(szName, sizeof(szName), "%s",
1995 40 : l_poDS->papszDimName[l_poDS->m_anDimIds[panBandZPos[i]]]);
1996 :
1997 : char szMetaName[NC_MAX_NAME + 1 + 32];
1998 40 : snprintf(szMetaName, sizeof(szMetaName), "NETCDF_DIM_%s", szName);
1999 :
2000 40 : const int nGroupID = l_poDS->m_anExtraDimGroupIds[i];
2001 40 : const int nVarID = l_poDS->m_anExtraDimVarIds[i];
2002 40 : if (nVarID < 0)
2003 : {
2004 2 : GDALPamRasterBand::SetMetadataItem(szMetaName,
2005 : CPLSPrintf("%d", result + 1));
2006 : }
2007 : else
2008 : {
2009 : // TODO: Make sure all the status checks make sense.
2010 :
2011 38 : nc_type nVarType = NC_NAT;
2012 38 : /* status = */ nc_inq_vartype(nGroupID, nVarID, &nVarType);
2013 :
2014 38 : int nDims = 0;
2015 38 : /* status = */ nc_inq_varndims(nGroupID, nVarID, &nDims);
2016 :
2017 38 : char szMetaTemp[256] = {};
2018 38 : if (nDims == 1)
2019 : {
2020 38 : size_t count[1] = {1};
2021 38 : size_t start[1] = {static_cast<size_t>(result)};
2022 :
2023 38 : switch (nVarType)
2024 : {
2025 0 : case NC_BYTE:
2026 : // TODO: Check for signed/unsigned byte.
2027 : signed char cData;
2028 0 : /* status = */ nc_get_vara_schar(nGroupID, nVarID,
2029 : start, count, &cData);
2030 0 : snprintf(szMetaTemp, sizeof(szMetaTemp), "%d", cData);
2031 0 : break;
2032 0 : case NC_SHORT:
2033 : short sData;
2034 0 : /* status = */ nc_get_vara_short(nGroupID, nVarID,
2035 : start, count, &sData);
2036 0 : snprintf(szMetaTemp, sizeof(szMetaTemp), "%d", sData);
2037 0 : break;
2038 19 : case NC_INT:
2039 : {
2040 : int nData;
2041 19 : /* status = */ nc_get_vara_int(nGroupID, nVarID, start,
2042 : count, &nData);
2043 19 : snprintf(szMetaTemp, sizeof(szMetaTemp), "%d", nData);
2044 19 : break;
2045 : }
2046 0 : case NC_FLOAT:
2047 : float fData;
2048 0 : /* status = */ nc_get_vara_float(nGroupID, nVarID,
2049 : start, count, &fData);
2050 0 : CPLsnprintf(szMetaTemp, sizeof(szMetaTemp), "%.8g",
2051 : fData);
2052 0 : break;
2053 18 : case NC_DOUBLE:
2054 : double dfData;
2055 18 : /* status = */ nc_get_vara_double(
2056 : nGroupID, nVarID, start, count, &dfData);
2057 18 : CPLsnprintf(szMetaTemp, sizeof(szMetaTemp), "%.16g",
2058 : dfData);
2059 18 : break;
2060 0 : case NC_UBYTE:
2061 : unsigned char ucData;
2062 0 : /* status = */ nc_get_vara_uchar(nGroupID, nVarID,
2063 : start, count, &ucData);
2064 0 : snprintf(szMetaTemp, sizeof(szMetaTemp), "%u", ucData);
2065 0 : break;
2066 0 : case NC_USHORT:
2067 : unsigned short usData;
2068 0 : /* status = */ nc_get_vara_ushort(
2069 : nGroupID, nVarID, start, count, &usData);
2070 0 : snprintf(szMetaTemp, sizeof(szMetaTemp), "%u", usData);
2071 0 : break;
2072 0 : case NC_UINT:
2073 : {
2074 : unsigned int unData;
2075 0 : /* status = */ nc_get_vara_uint(nGroupID, nVarID, start,
2076 : count, &unData);
2077 0 : snprintf(szMetaTemp, sizeof(szMetaTemp), "%u", unData);
2078 0 : break;
2079 : }
2080 1 : case NC_INT64:
2081 : {
2082 : long long nData;
2083 1 : /* status = */ nc_get_vara_longlong(
2084 : nGroupID, nVarID, start, count, &nData);
2085 1 : snprintf(szMetaTemp, sizeof(szMetaTemp), CPL_FRMT_GIB,
2086 : nData);
2087 1 : break;
2088 : }
2089 0 : case NC_UINT64:
2090 : {
2091 : unsigned long long unData;
2092 0 : /* status = */ nc_get_vara_ulonglong(
2093 : nGroupID, nVarID, start, count, &unData);
2094 0 : snprintf(szMetaTemp, sizeof(szMetaTemp), CPL_FRMT_GUIB,
2095 : unData);
2096 0 : break;
2097 : }
2098 0 : default:
2099 0 : CPLDebug("GDAL_netCDF", "invalid dim %s, type=%d",
2100 : szMetaTemp, nVarType);
2101 0 : break;
2102 : }
2103 : }
2104 : else
2105 : {
2106 0 : snprintf(szMetaTemp, sizeof(szMetaTemp), "%d", result + 1);
2107 : }
2108 :
2109 : // Save dimension value.
2110 : // NOTE: removed #original_units as not part of CF-1.
2111 :
2112 38 : GDALPamRasterBand::SetMetadataItem(szMetaName, szMetaTemp);
2113 : }
2114 :
2115 : // Avoid int32 overflow. Perhaps something more sensible to do here ?
2116 40 : if (result > 0 && Sum > INT_MAX / result)
2117 0 : break;
2118 40 : if (Taken > INT_MAX - result * Sum)
2119 0 : break;
2120 :
2121 40 : Taken += result * Sum;
2122 : } // End loop non-spatial dimensions.
2123 :
2124 48 : l_poDS->nPamFlags = nPamFlagsBackup;
2125 48 : }
2126 :
2127 : /************************************************************************/
2128 : /* CheckData() */
2129 : /************************************************************************/
2130 : template <class T>
2131 5731 : void netCDFRasterBand::CheckData(void *pImage, void *pImageNC,
2132 : size_t nTmpBlockXSize, size_t nTmpBlockYSize,
2133 : bool bCheckIsNan)
2134 : {
2135 5731 : CPLAssert(pImage != nullptr && pImageNC != nullptr);
2136 :
2137 : // If this block is not a full block (in the x axis), we need to re-arrange
2138 : // the data this is because partial blocks are not arranged the same way in
2139 : // netcdf and gdal.
2140 5731 : if (nTmpBlockXSize != static_cast<size_t>(nBlockXSize))
2141 : {
2142 6 : T *ptrWrite = static_cast<T *>(pImage);
2143 6 : T *ptrRead = static_cast<T *>(pImageNC);
2144 29 : for (size_t j = 0; j < nTmpBlockYSize;
2145 23 : j++, ptrWrite += nBlockXSize, ptrRead += nTmpBlockXSize)
2146 : {
2147 23 : memmove(ptrWrite, ptrRead, nTmpBlockXSize * sizeof(T));
2148 : }
2149 : }
2150 :
2151 : // Is valid data checking needed or requested?
2152 5731 : if (bValidRangeValid || bCheckIsNan)
2153 : {
2154 1265 : T *ptrImage = static_cast<T *>(pImage);
2155 2584 : for (size_t j = 0; j < nTmpBlockYSize; j++)
2156 : {
2157 : // k moves along the gdal block, skipping the out-of-range pixels.
2158 1319 : size_t k = j * nBlockXSize;
2159 96938 : for (size_t i = 0; i < nTmpBlockXSize; i++, k++)
2160 : {
2161 : // Check for nodata and nan.
2162 95619 : if (CPLIsEqual((double)ptrImage[k], m_dfNoDataValue))
2163 6301 : continue;
2164 89318 : if (bCheckIsNan && std::isnan((double)ptrImage[k]))
2165 : {
2166 5737 : ptrImage[k] = (T)m_dfNoDataValue;
2167 5737 : continue;
2168 : }
2169 : // Check for valid_range.
2170 83581 : if (bValidRangeValid)
2171 : {
2172 40986 : if (((adfValidRange[0] != m_dfNoDataValue) &&
2173 40986 : (ptrImage[k] < (T)adfValidRange[0])) ||
2174 40983 : ((adfValidRange[1] != m_dfNoDataValue) &&
2175 40983 : (ptrImage[k] > (T)adfValidRange[1])))
2176 : {
2177 4 : ptrImage[k] = (T)m_dfNoDataValue;
2178 : }
2179 : }
2180 : }
2181 : }
2182 : }
2183 :
2184 : // If minimum longitude is > 180, subtract 360 from all.
2185 : // If not, disable checking for further calls (check just once).
2186 : // Only check first and last block elements since lon must be monotonic.
2187 5731 : const bool bIsSigned = std::numeric_limits<T>::is_signed;
2188 5419 : if (bCheckLongitude && bIsSigned &&
2189 9 : !CPLIsEqual((double)((T *)pImage)[0], m_dfNoDataValue) &&
2190 8 : !CPLIsEqual((double)((T *)pImage)[nTmpBlockXSize - 1],
2191 2714 : m_dfNoDataValue) &&
2192 8 : std::min(((T *)pImage)[0], ((T *)pImage)[nTmpBlockXSize - 1]) > 180.0)
2193 : {
2194 0 : T *ptrImage = static_cast<T *>(pImage);
2195 0 : for (size_t j = 0; j < nTmpBlockYSize; j++)
2196 : {
2197 0 : size_t k = j * nBlockXSize;
2198 0 : for (size_t i = 0; i < nTmpBlockXSize; i++, k++)
2199 : {
2200 0 : if (!CPLIsEqual((double)ptrImage[k], m_dfNoDataValue))
2201 0 : ptrImage[k] = static_cast<T>(ptrImage[k] - 360);
2202 : }
2203 : }
2204 : }
2205 : else
2206 : {
2207 5731 : bCheckLongitude = false;
2208 : }
2209 5731 : }
2210 :
2211 : /************************************************************************/
2212 : /* CheckDataCpx() */
2213 : /************************************************************************/
2214 : template <class T>
2215 25 : void netCDFRasterBand::CheckDataCpx(void *pImage, void *pImageNC,
2216 : size_t nTmpBlockXSize,
2217 : size_t nTmpBlockYSize, bool bCheckIsNan)
2218 : {
2219 25 : CPLAssert(pImage != nullptr && pImageNC != nullptr);
2220 :
2221 : // If this block is not a full block (in the x axis), we need to re-arrange
2222 : // the data this is because partial blocks are not arranged the same way in
2223 : // netcdf and gdal.
2224 25 : if (nTmpBlockXSize != static_cast<size_t>(nBlockXSize))
2225 : {
2226 0 : T *ptrWrite = static_cast<T *>(pImage);
2227 0 : T *ptrRead = static_cast<T *>(pImageNC);
2228 0 : for (size_t j = 0; j < nTmpBlockYSize; j++,
2229 0 : ptrWrite += (2 * nBlockXSize),
2230 0 : ptrRead += (2 * nTmpBlockXSize))
2231 : {
2232 0 : memmove(ptrWrite, ptrRead, nTmpBlockXSize * sizeof(T) * 2);
2233 : }
2234 : }
2235 :
2236 : // Is valid data checking needed or requested?
2237 25 : if (bValidRangeValid || bCheckIsNan)
2238 : {
2239 0 : T *ptrImage = static_cast<T *>(pImage);
2240 0 : for (size_t j = 0; j < nTmpBlockYSize; j++)
2241 : {
2242 : // k moves along the gdal block, skipping the out-of-range pixels.
2243 0 : size_t k = 2 * j * nBlockXSize;
2244 0 : for (size_t i = 0; i < (2 * nTmpBlockXSize); i++, k++)
2245 : {
2246 : // Check for nodata and nan.
2247 0 : if (CPLIsEqual((double)ptrImage[k], m_dfNoDataValue))
2248 0 : continue;
2249 0 : if (bCheckIsNan && std::isnan((double)ptrImage[k]))
2250 : {
2251 0 : ptrImage[k] = (T)m_dfNoDataValue;
2252 0 : continue;
2253 : }
2254 : // Check for valid_range.
2255 0 : if (bValidRangeValid)
2256 : {
2257 0 : if (((adfValidRange[0] != m_dfNoDataValue) &&
2258 0 : (ptrImage[k] < (T)adfValidRange[0])) ||
2259 0 : ((adfValidRange[1] != m_dfNoDataValue) &&
2260 0 : (ptrImage[k] > (T)adfValidRange[1])))
2261 : {
2262 0 : ptrImage[k] = (T)m_dfNoDataValue;
2263 : }
2264 : }
2265 : }
2266 : }
2267 : }
2268 25 : }
2269 :
2270 : /************************************************************************/
2271 : /* FetchNetcdfChunk() */
2272 : /************************************************************************/
2273 :
2274 5756 : bool netCDFRasterBand::FetchNetcdfChunk(size_t xstart, size_t ystart,
2275 : void *pImage)
2276 : {
2277 5756 : size_t start[MAX_NC_DIMS] = {};
2278 5756 : size_t edge[MAX_NC_DIMS] = {};
2279 :
2280 5756 : start[nBandXPos] = xstart;
2281 5756 : edge[nBandXPos] = nBlockXSize;
2282 5756 : if ((start[nBandXPos] + edge[nBandXPos]) > (size_t)nRasterXSize)
2283 6 : edge[nBandXPos] = nRasterXSize - start[nBandXPos];
2284 5756 : if (nBandYPos >= 0)
2285 : {
2286 5752 : start[nBandYPos] = ystart;
2287 5752 : edge[nBandYPos] = nBlockYSize;
2288 5752 : if ((start[nBandYPos] + edge[nBandYPos]) > (size_t)nRasterYSize)
2289 4 : edge[nBandYPos] = nRasterYSize - start[nBandYPos];
2290 : }
2291 5756 : const size_t nYChunkSize = nBandYPos < 0 ? 1 : edge[nBandYPos];
2292 :
2293 : #ifdef NCDF_DEBUG
2294 : CPLDebug("GDAL_netCDF", "start={%ld,%ld} edge={%ld,%ld} bBottomUp=%d",
2295 : start[nBandXPos], nBandYPos < 0 ? 0 : start[nBandYPos],
2296 : edge[nBandXPos], nYChunkSize, ((netCDFDataset *)poDS)->bBottomUp);
2297 : #endif
2298 :
2299 5756 : int nd = 0;
2300 5756 : nc_inq_varndims(cdfid, nZId, &nd);
2301 5756 : if (nd == 3)
2302 : {
2303 1078 : start[panBandZPos[0]] = nLevel; // z
2304 1078 : edge[panBandZPos[0]] = 1;
2305 : }
2306 :
2307 : // Compute multidimention band position.
2308 : //
2309 : // BandPosition = (Total - sum(PastBandLevels) - 1)/sum(remainingLevels)
2310 : // if Data[2,3,4,x,y]
2311 : //
2312 : // BandPos0 = (nBand) / (3*4)
2313 : // BandPos1 = (nBand - (3*4)) / (4)
2314 : // BandPos2 = (nBand - (3*4)) % (4)
2315 5756 : if (nd > 3)
2316 : {
2317 160 : int Sum = -1;
2318 160 : int Taken = 0;
2319 480 : for (int i = 0; i < nd - 2; i++)
2320 : {
2321 320 : if (i != nd - 2 - 1)
2322 : {
2323 160 : Sum = 1;
2324 320 : for (int j = i + 1; j < nd - 2; j++)
2325 : {
2326 160 : Sum *= panBandZLev[j];
2327 : }
2328 160 : start[panBandZPos[i]] = (int)((nLevel - Taken) / Sum);
2329 160 : edge[panBandZPos[i]] = 1;
2330 : }
2331 : else
2332 : {
2333 160 : start[panBandZPos[i]] = (int)((nLevel - Taken) % Sum);
2334 160 : edge[panBandZPos[i]] = 1;
2335 : }
2336 320 : Taken += static_cast<int>(start[panBandZPos[i]]) * Sum;
2337 : }
2338 : }
2339 :
2340 : // Make sure we are in data mode.
2341 5756 : static_cast<netCDFDataset *>(poDS)->SetDefineMode(false);
2342 :
2343 : // If this block is not a full block in the x axis, we need to
2344 : // re-arrange the data because partial blocks are not arranged the
2345 : // same way in netcdf and gdal, so we first we read the netcdf data at
2346 : // the end of the gdal block buffer then re-arrange rows in CheckData().
2347 5756 : void *pImageNC = pImage;
2348 5756 : if (edge[nBandXPos] != static_cast<size_t>(nBlockXSize))
2349 : {
2350 6 : pImageNC = static_cast<GByte *>(pImage) +
2351 6 : ((static_cast<size_t>(nBlockXSize) * nBlockYSize -
2352 12 : edge[nBandXPos] * nYChunkSize) *
2353 6 : (GDALGetDataTypeSize(eDataType) / 8));
2354 : }
2355 :
2356 : // Read data according to type.
2357 : int status;
2358 5756 : if (eDataType == GDT_Byte)
2359 : {
2360 3004 : if (bSignedData)
2361 : {
2362 0 : status = nc_get_vara_schar(cdfid, nZId, start, edge,
2363 : static_cast<signed char *>(pImageNC));
2364 0 : if (status == NC_NOERR)
2365 0 : CheckData<signed char>(pImage, pImageNC, edge[nBandXPos],
2366 : nYChunkSize, false);
2367 : }
2368 : else
2369 : {
2370 3004 : status = nc_get_vara_uchar(cdfid, nZId, start, edge,
2371 : static_cast<unsigned char *>(pImageNC));
2372 3004 : if (status == NC_NOERR)
2373 3004 : CheckData<unsigned char>(pImage, pImageNC, edge[nBandXPos],
2374 : nYChunkSize, false);
2375 : }
2376 : }
2377 2752 : else if (eDataType == GDT_Int8)
2378 : {
2379 60 : status = nc_get_vara_schar(cdfid, nZId, start, edge,
2380 : static_cast<signed char *>(pImageNC));
2381 60 : if (status == NC_NOERR)
2382 60 : CheckData<signed char>(pImage, pImageNC, edge[nBandXPos],
2383 : nYChunkSize, false);
2384 : }
2385 2692 : else if (nc_datatype == NC_SHORT)
2386 : {
2387 465 : status = nc_get_vara_short(cdfid, nZId, start, edge,
2388 : static_cast<short *>(pImageNC));
2389 465 : if (status == NC_NOERR)
2390 : {
2391 465 : if (eDataType == GDT_Int16)
2392 : {
2393 462 : CheckData<GInt16>(pImage, pImageNC, edge[nBandXPos],
2394 : nYChunkSize, false);
2395 : }
2396 : else
2397 : {
2398 3 : CheckData<GUInt16>(pImage, pImageNC, edge[nBandXPos],
2399 : nYChunkSize, false);
2400 : }
2401 : }
2402 : }
2403 2227 : else if (eDataType == GDT_Int32)
2404 : {
2405 : #if SIZEOF_UNSIGNED_LONG == 4
2406 : status = nc_get_vara_long(cdfid, nZId, start, edge,
2407 : static_cast<long *>(pImageNC));
2408 : if (status == NC_NOERR)
2409 : CheckData<long>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
2410 : false);
2411 : #else
2412 912 : status = nc_get_vara_int(cdfid, nZId, start, edge,
2413 : static_cast<int *>(pImageNC));
2414 912 : if (status == NC_NOERR)
2415 912 : CheckData<int>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
2416 : false);
2417 : #endif
2418 : }
2419 1315 : else if (eDataType == GDT_Float32)
2420 : {
2421 1178 : status = nc_get_vara_float(cdfid, nZId, start, edge,
2422 : static_cast<float *>(pImageNC));
2423 1178 : if (status == NC_NOERR)
2424 1178 : CheckData<float>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
2425 : true);
2426 : }
2427 137 : else if (eDataType == GDT_Float64)
2428 : {
2429 86 : status = nc_get_vara_double(cdfid, nZId, start, edge,
2430 : static_cast<double *>(pImageNC));
2431 86 : if (status == NC_NOERR)
2432 86 : CheckData<double>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
2433 : true);
2434 : }
2435 51 : else if (eDataType == GDT_UInt16)
2436 : {
2437 6 : status = nc_get_vara_ushort(cdfid, nZId, start, edge,
2438 : static_cast<unsigned short *>(pImageNC));
2439 6 : if (status == NC_NOERR)
2440 6 : CheckData<unsigned short>(pImage, pImageNC, edge[nBandXPos],
2441 : nYChunkSize, false);
2442 : }
2443 45 : else if (eDataType == GDT_UInt32)
2444 : {
2445 6 : status = nc_get_vara_uint(cdfid, nZId, start, edge,
2446 : static_cast<unsigned int *>(pImageNC));
2447 6 : if (status == NC_NOERR)
2448 6 : CheckData<unsigned int>(pImage, pImageNC, edge[nBandXPos],
2449 : nYChunkSize, false);
2450 : }
2451 39 : else if (eDataType == GDT_Int64)
2452 : {
2453 7 : status = nc_get_vara_longlong(cdfid, nZId, start, edge,
2454 : static_cast<long long *>(pImageNC));
2455 7 : if (status == NC_NOERR)
2456 7 : CheckData<std::int64_t>(pImage, pImageNC, edge[nBandXPos],
2457 : nYChunkSize, false);
2458 : }
2459 32 : else if (eDataType == GDT_UInt64)
2460 : {
2461 : status =
2462 7 : nc_get_vara_ulonglong(cdfid, nZId, start, edge,
2463 : static_cast<unsigned long long *>(pImageNC));
2464 7 : if (status == NC_NOERR)
2465 7 : CheckData<std::uint64_t>(pImage, pImageNC, edge[nBandXPos],
2466 : nYChunkSize, false);
2467 : }
2468 25 : else if (eDataType == GDT_CInt16)
2469 : {
2470 0 : status = nc_get_vara(cdfid, nZId, start, edge, pImageNC);
2471 0 : if (status == NC_NOERR)
2472 0 : CheckDataCpx<short>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
2473 : false);
2474 : }
2475 25 : else if (eDataType == GDT_CInt32)
2476 : {
2477 0 : status = nc_get_vara(cdfid, nZId, start, edge, pImageNC);
2478 0 : if (status == NC_NOERR)
2479 0 : CheckDataCpx<int>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
2480 : false);
2481 : }
2482 25 : else if (eDataType == GDT_CFloat32)
2483 : {
2484 20 : status = nc_get_vara(cdfid, nZId, start, edge, pImageNC);
2485 20 : if (status == NC_NOERR)
2486 20 : CheckDataCpx<float>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
2487 : false);
2488 : }
2489 5 : else if (eDataType == GDT_CFloat64)
2490 : {
2491 5 : status = nc_get_vara(cdfid, nZId, start, edge, pImageNC);
2492 5 : if (status == NC_NOERR)
2493 5 : CheckDataCpx<double>(pImage, pImageNC, edge[nBandXPos], nYChunkSize,
2494 : false);
2495 : }
2496 :
2497 : else
2498 0 : status = NC_EBADTYPE;
2499 :
2500 5756 : if (status != NC_NOERR)
2501 : {
2502 0 : CPLError(CE_Failure, CPLE_AppDefined,
2503 : "netCDF chunk fetch failed: #%d (%s)", status,
2504 : nc_strerror(status));
2505 0 : return false;
2506 : }
2507 5756 : return true;
2508 : }
2509 :
2510 : /************************************************************************/
2511 : /* IReadBlock() */
2512 : /************************************************************************/
2513 :
2514 5756 : CPLErr netCDFRasterBand::IReadBlock(int nBlockXOff, int nBlockYOff,
2515 : void *pImage)
2516 :
2517 : {
2518 11512 : CPLMutexHolderD(&hNCMutex);
2519 :
2520 : // Locate X, Y and Z position in the array.
2521 :
2522 5756 : size_t xstart = static_cast<size_t>(nBlockXOff) * nBlockXSize;
2523 5756 : size_t ystart = 0;
2524 :
2525 : // Check y order.
2526 5756 : if (nBandYPos >= 0)
2527 : {
2528 5752 : auto poGDS = static_cast<netCDFDataset *>(poDS);
2529 5752 : if (poGDS->bBottomUp)
2530 : {
2531 4837 : if (nBlockYSize == 1)
2532 : {
2533 4824 : ystart = nRasterYSize - 1 - nBlockYOff;
2534 : }
2535 : else
2536 : {
2537 : // in GDAL space
2538 13 : ystart = static_cast<size_t>(nBlockYOff) * nBlockYSize;
2539 : const size_t yend =
2540 26 : std::min(ystart + nBlockYSize - 1,
2541 13 : static_cast<size_t>(nRasterYSize - 1));
2542 : // in netCDF space
2543 13 : const size_t nFirstChunkLine = nRasterYSize - 1 - yend;
2544 13 : const size_t nLastChunkLine = nRasterYSize - 1 - ystart;
2545 13 : const size_t nFirstChunkBlock = nFirstChunkLine / nBlockYSize;
2546 13 : const size_t nLastChunkBlock = nLastChunkLine / nBlockYSize;
2547 :
2548 : const auto firstKey = netCDFDataset::ChunkKey(
2549 13 : nBlockXOff, nFirstChunkBlock, nBand);
2550 : const auto secondKey =
2551 13 : netCDFDataset::ChunkKey(nBlockXOff, nLastChunkBlock, nBand);
2552 :
2553 : // Retrieve data from the one or 2 needed netCDF chunks
2554 13 : std::shared_ptr<std::vector<GByte>> firstChunk;
2555 13 : std::shared_ptr<std::vector<GByte>> secondChunk;
2556 13 : if (poGDS->poChunkCache)
2557 : {
2558 13 : poGDS->poChunkCache->tryGet(firstKey, firstChunk);
2559 13 : if (firstKey != secondKey)
2560 6 : poGDS->poChunkCache->tryGet(secondKey, secondChunk);
2561 : }
2562 : const size_t nChunkLineSize =
2563 13 : static_cast<size_t>(GDALGetDataTypeSizeBytes(eDataType)) *
2564 13 : nBlockXSize;
2565 13 : const size_t nChunkSize = nChunkLineSize * nBlockYSize;
2566 13 : if (!firstChunk)
2567 : {
2568 11 : firstChunk.reset(new std::vector<GByte>(nChunkSize));
2569 11 : if (!FetchNetcdfChunk(xstart,
2570 11 : nFirstChunkBlock * nBlockYSize,
2571 11 : firstChunk.get()->data()))
2572 0 : return CE_Failure;
2573 11 : if (poGDS->poChunkCache)
2574 11 : poGDS->poChunkCache->insert(firstKey, firstChunk);
2575 : }
2576 13 : if (!secondChunk && firstKey != secondKey)
2577 : {
2578 2 : secondChunk.reset(new std::vector<GByte>(nChunkSize));
2579 2 : if (!FetchNetcdfChunk(xstart, nLastChunkBlock * nBlockYSize,
2580 2 : secondChunk.get()->data()))
2581 0 : return CE_Failure;
2582 2 : if (poGDS->poChunkCache)
2583 2 : poGDS->poChunkCache->insert(secondKey, secondChunk);
2584 : }
2585 :
2586 : // Assemble netCDF chunks into GDAL block
2587 13 : GByte *pabyImage = static_cast<GByte *>(pImage);
2588 13 : const size_t nFirstChunkBlockLine =
2589 13 : nFirstChunkBlock * nBlockYSize;
2590 13 : const size_t nLastChunkBlockLine =
2591 13 : nLastChunkBlock * nBlockYSize;
2592 146 : for (size_t iLine = ystart; iLine <= yend; iLine++)
2593 : {
2594 133 : const size_t nLineFromBottom = nRasterYSize - 1 - iLine;
2595 133 : const size_t nChunkY = nLineFromBottom / nBlockYSize;
2596 133 : if (nChunkY == nFirstChunkBlock)
2597 : {
2598 121 : memcpy(pabyImage + nChunkLineSize * (iLine - ystart),
2599 121 : firstChunk.get()->data() +
2600 121 : (nLineFromBottom - nFirstChunkBlockLine) *
2601 : nChunkLineSize,
2602 : nChunkLineSize);
2603 : }
2604 : else
2605 : {
2606 12 : CPLAssert(nChunkY == nLastChunkBlock);
2607 12 : assert(secondChunk);
2608 12 : memcpy(pabyImage + nChunkLineSize * (iLine - ystart),
2609 12 : secondChunk.get()->data() +
2610 12 : (nLineFromBottom - nLastChunkBlockLine) *
2611 : nChunkLineSize,
2612 : nChunkLineSize);
2613 : }
2614 : }
2615 13 : return CE_None;
2616 : }
2617 : }
2618 : else
2619 : {
2620 915 : ystart = static_cast<size_t>(nBlockYOff) * nBlockYSize;
2621 : }
2622 : }
2623 :
2624 5743 : return FetchNetcdfChunk(xstart, ystart, pImage) ? CE_None : CE_Failure;
2625 : }
2626 :
2627 : /************************************************************************/
2628 : /* IWriteBlock() */
2629 : /************************************************************************/
2630 :
2631 2781 : CPLErr netCDFRasterBand::IWriteBlock(CPL_UNUSED int nBlockXOff, int nBlockYOff,
2632 : void *pImage)
2633 : {
2634 5562 : CPLMutexHolderD(&hNCMutex);
2635 :
2636 : #ifdef NCDF_DEBUG
2637 : if (nBlockYOff == 0 || (nBlockYOff == nRasterYSize - 1))
2638 : CPLDebug("GDAL_netCDF",
2639 : "netCDFRasterBand::IWriteBlock( %d, %d, ...) nBand=%d",
2640 : nBlockXOff, nBlockYOff, nBand);
2641 : #endif
2642 :
2643 2781 : int nd = 0;
2644 2781 : nc_inq_varndims(cdfid, nZId, &nd);
2645 :
2646 : // Locate X, Y and Z position in the array.
2647 :
2648 : size_t start[MAX_NC_DIMS];
2649 2781 : memset(start, 0, sizeof(start));
2650 2781 : start[nBandXPos] = static_cast<size_t>(nBlockXOff) * nBlockXSize;
2651 :
2652 : // check y order.
2653 2781 : if (static_cast<netCDFDataset *>(poDS)->bBottomUp)
2654 : {
2655 2757 : if (nBlockYSize == 1)
2656 : {
2657 2757 : start[nBandYPos] = nRasterYSize - 1 - nBlockYOff;
2658 : }
2659 : else
2660 : {
2661 0 : CPLError(CE_Failure, CPLE_AppDefined,
2662 : "nBlockYSize = %d, only 1 supported when "
2663 : "writing bottom-up dataset",
2664 : nBlockYSize);
2665 0 : return CE_Failure;
2666 : }
2667 : }
2668 : else
2669 : {
2670 24 : start[nBandYPos] = static_cast<size_t>(nBlockYOff) * nBlockYSize; // y
2671 : }
2672 :
2673 2781 : size_t edge[MAX_NC_DIMS] = {};
2674 :
2675 2781 : edge[nBandXPos] = nBlockXSize;
2676 2781 : if ((start[nBandXPos] + edge[nBandXPos]) > (size_t)nRasterXSize)
2677 0 : edge[nBandXPos] = nRasterXSize - start[nBandXPos];
2678 2781 : edge[nBandYPos] = nBlockYSize;
2679 2781 : if ((start[nBandYPos] + edge[nBandYPos]) > (size_t)nRasterYSize)
2680 0 : edge[nBandYPos] = nRasterYSize - start[nBandYPos];
2681 :
2682 2781 : if (nd == 3)
2683 : {
2684 610 : start[panBandZPos[0]] = nLevel; // z
2685 610 : edge[panBandZPos[0]] = 1;
2686 : }
2687 :
2688 : // Compute multidimention band position.
2689 : //
2690 : // BandPosition = (Total - sum(PastBandLevels) - 1)/sum(remainingLevels)
2691 : // if Data[2,3,4,x,y]
2692 : //
2693 : // BandPos0 = (nBand) / (3*4)
2694 : // BandPos1 = (nBand - (3*4)) / (4)
2695 : // BandPos2 = (nBand - (3*4)) % (4)
2696 2781 : if (nd > 3)
2697 : {
2698 178 : int Sum = -1;
2699 178 : int Taken = 0;
2700 534 : for (int i = 0; i < nd - 2; i++)
2701 : {
2702 356 : if (i != nd - 2 - 1)
2703 : {
2704 178 : Sum = 1;
2705 356 : for (int j = i + 1; j < nd - 2; j++)
2706 : {
2707 178 : Sum *= panBandZLev[j];
2708 : }
2709 178 : start[panBandZPos[i]] = (int)((nLevel - Taken) / Sum);
2710 178 : edge[panBandZPos[i]] = 1;
2711 : }
2712 : else
2713 : {
2714 178 : start[panBandZPos[i]] = (int)((nLevel - Taken) % Sum);
2715 178 : edge[panBandZPos[i]] = 1;
2716 : }
2717 356 : Taken += static_cast<int>(start[panBandZPos[i]]) * Sum;
2718 : }
2719 : }
2720 :
2721 : // Make sure we are in data mode.
2722 2781 : static_cast<netCDFDataset *>(poDS)->SetDefineMode(false);
2723 :
2724 : // Copy data according to type.
2725 2781 : int status = 0;
2726 2781 : if (eDataType == GDT_Byte)
2727 : {
2728 2222 : if (bSignedData)
2729 0 : status = nc_put_vara_schar(cdfid, nZId, start, edge,
2730 : static_cast<signed char *>(pImage));
2731 : else
2732 2222 : status = nc_put_vara_uchar(cdfid, nZId, start, edge,
2733 : static_cast<unsigned char *>(pImage));
2734 : }
2735 559 : else if (eDataType == GDT_Int8)
2736 : {
2737 40 : status = nc_put_vara_schar(cdfid, nZId, start, edge,
2738 : static_cast<signed char *>(pImage));
2739 : }
2740 519 : else if (nc_datatype == NC_SHORT)
2741 : {
2742 101 : status = nc_put_vara_short(cdfid, nZId, start, edge,
2743 : static_cast<short *>(pImage));
2744 : }
2745 418 : else if (eDataType == GDT_Int32)
2746 : {
2747 210 : status = nc_put_vara_int(cdfid, nZId, start, edge,
2748 : static_cast<int *>(pImage));
2749 : }
2750 208 : else if (eDataType == GDT_Float32)
2751 : {
2752 128 : status = nc_put_vara_float(cdfid, nZId, start, edge,
2753 : static_cast<float *>(pImage));
2754 : }
2755 80 : else if (eDataType == GDT_Float64)
2756 : {
2757 50 : status = nc_put_vara_double(cdfid, nZId, start, edge,
2758 : static_cast<double *>(pImage));
2759 : }
2760 30 : else if (eDataType == GDT_UInt16 &&
2761 12 : static_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
2762 : {
2763 12 : status = nc_put_vara_ushort(cdfid, nZId, start, edge,
2764 : static_cast<unsigned short *>(pImage));
2765 : }
2766 18 : else if (eDataType == GDT_UInt32 &&
2767 12 : static_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
2768 : {
2769 12 : status = nc_put_vara_uint(cdfid, nZId, start, edge,
2770 : static_cast<unsigned int *>(pImage));
2771 : }
2772 6 : else if (eDataType == GDT_UInt64 &&
2773 3 : static_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
2774 : {
2775 3 : status =
2776 3 : nc_put_vara_ulonglong(cdfid, nZId, start, edge,
2777 : static_cast<unsigned long long *>(pImage));
2778 : }
2779 3 : else if (eDataType == GDT_Int64 &&
2780 3 : static_cast<netCDFDataset *>(poDS)->eFormat == NCDF_FORMAT_NC4)
2781 : {
2782 3 : status = nc_put_vara_longlong(cdfid, nZId, start, edge,
2783 : static_cast<long long *>(pImage));
2784 : }
2785 : else
2786 : {
2787 0 : CPLError(CE_Failure, CPLE_NotSupported,
2788 : "The NetCDF driver does not support GDAL data type %d",
2789 0 : eDataType);
2790 0 : status = NC_EBADTYPE;
2791 : }
2792 2781 : NCDF_ERR(status);
2793 :
2794 2781 : if (status != NC_NOERR)
2795 : {
2796 0 : CPLError(CE_Failure, CPLE_AppDefined,
2797 : "netCDF scanline write failed: %s", nc_strerror(status));
2798 0 : return CE_Failure;
2799 : }
2800 :
2801 2781 : return CE_None;
2802 : }
2803 :
2804 : /************************************************************************/
2805 : /* ==================================================================== */
2806 : /* netCDFDataset */
2807 : /* ==================================================================== */
2808 : /************************************************************************/
2809 :
2810 : /************************************************************************/
2811 : /* netCDFDataset() */
2812 : /************************************************************************/
2813 :
2814 974 : netCDFDataset::netCDFDataset()
2815 : :
2816 : // Basic dataset vars.
2817 : #ifdef ENABLE_NCDUMP
2818 : bFileToDestroyAtClosing(false),
2819 : #endif
2820 : cdfid(-1), nSubDatasets(0), papszSubDatasets(nullptr),
2821 : papszMetadata(nullptr), bBottomUp(true), eFormat(NCDF_FORMAT_NONE),
2822 : bIsGdalFile(false), bIsGdalCfFile(false), pszCFProjection(nullptr),
2823 : pszCFCoordinates(nullptr), nCFVersion(1.6), bSGSupport(false),
2824 974 : eMultipleLayerBehavior(SINGLE_LAYER), logCount(0), vcdf(this, cdfid),
2825 974 : GeometryScribe(vcdf, this->generateLogName()),
2826 974 : FieldScribe(vcdf, this->generateLogName()),
2827 1948 : bufManager(CPLGetUsablePhysicalRAM() / 5),
2828 :
2829 : // projection/GT.
2830 : nXDimID(-1), nYDimID(-1), bIsProjected(false),
2831 : bIsGeographic(false), // Can be not projected, and also not geographic
2832 : // State vars.
2833 : bDefineMode(true), bAddedGridMappingRef(false),
2834 :
2835 : // Create vars.
2836 : papszCreationOptions(nullptr), eCompress(NCDF_COMPRESS_NONE),
2837 : nZLevel(NCDF_DEFLATE_LEVEL), bChunking(false), nCreateMode(NC_CLOBBER),
2838 2922 : bSignedData(true)
2839 : {
2840 974 : m_oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
2841 :
2842 : // Projection/GT.
2843 974 : m_adfGeoTransform[0] = 0.0;
2844 974 : m_adfGeoTransform[1] = 1.0;
2845 974 : m_adfGeoTransform[2] = 0.0;
2846 974 : m_adfGeoTransform[3] = 0.0;
2847 974 : m_adfGeoTransform[4] = 0.0;
2848 974 : m_adfGeoTransform[5] = 1.0;
2849 :
2850 : // Set buffers
2851 974 : bufManager.addBuffer(&(GeometryScribe.getMemBuffer()));
2852 974 : bufManager.addBuffer(&(FieldScribe.getMemBuffer()));
2853 974 : }
2854 :
2855 : /************************************************************************/
2856 : /* ~netCDFDataset() */
2857 : /************************************************************************/
2858 :
2859 1887 : netCDFDataset::~netCDFDataset()
2860 :
2861 : {
2862 974 : netCDFDataset::Close();
2863 1887 : }
2864 :
2865 : /************************************************************************/
2866 : /* Close() */
2867 : /************************************************************************/
2868 :
2869 1709 : CPLErr netCDFDataset::Close()
2870 : {
2871 1709 : CPLErr eErr = CE_None;
2872 1709 : if (nOpenFlags != OPEN_FLAGS_CLOSED)
2873 : {
2874 1948 : CPLMutexHolderD(&hNCMutex);
2875 :
2876 : #ifdef NCDF_DEBUG
2877 : CPLDebug("GDAL_netCDF",
2878 : "netCDFDataset::~netCDFDataset(), cdfid=%d filename=%s", cdfid,
2879 : osFilename.c_str());
2880 : #endif
2881 :
2882 : // Write data related to geotransform
2883 1205 : if (GetAccess() == GA_Update && !m_bAddedProjectionVarsData &&
2884 231 : (m_bHasProjection || m_bHasGeoTransform))
2885 : {
2886 : // Ensure projection is written if GeoTransform OR Projection are
2887 : // missing.
2888 37 : if (!m_bAddedProjectionVarsDefs)
2889 : {
2890 2 : AddProjectionVars(true, nullptr, nullptr);
2891 : }
2892 37 : AddProjectionVars(false, nullptr, nullptr);
2893 : }
2894 :
2895 974 : if (netCDFDataset::FlushCache(true) != CE_None)
2896 0 : eErr = CE_Failure;
2897 :
2898 974 : if (GetAccess() == GA_Update && !SGCommitPendingTransaction())
2899 0 : eErr = CE_Failure;
2900 :
2901 976 : for (size_t i = 0; i < apoVectorDatasets.size(); i++)
2902 2 : delete apoVectorDatasets[i];
2903 :
2904 : // Make sure projection variable is written to band variable.
2905 974 : if (GetAccess() == GA_Update && !bAddedGridMappingRef)
2906 : {
2907 246 : if (!AddGridMappingRef())
2908 0 : eErr = CE_Failure;
2909 : }
2910 :
2911 974 : CSLDestroy(papszMetadata);
2912 974 : CSLDestroy(papszSubDatasets);
2913 974 : CSLDestroy(papszCreationOptions);
2914 :
2915 974 : CPLFree(pszCFProjection);
2916 :
2917 974 : if (cdfid > 0)
2918 : {
2919 : #ifdef NCDF_DEBUG
2920 : CPLDebug("GDAL_netCDF", "calling nc_close( %d)", cdfid);
2921 : #endif
2922 651 : int status = GDAL_nc_close(cdfid);
2923 : #ifdef ENABLE_UFFD
2924 651 : NETCDF_UFFD_UNMAP(pCtx);
2925 : #endif
2926 651 : NCDF_ERR(status);
2927 651 : if (status != NC_NOERR)
2928 0 : eErr = CE_Failure;
2929 : }
2930 :
2931 974 : if (fpVSIMEM)
2932 15 : VSIFCloseL(fpVSIMEM);
2933 :
2934 : #ifdef ENABLE_NCDUMP
2935 974 : if (bFileToDestroyAtClosing)
2936 0 : VSIUnlink(osFilename);
2937 : #endif
2938 :
2939 974 : if (GDALPamDataset::Close() != CE_None)
2940 0 : eErr = CE_Failure;
2941 : }
2942 1709 : return eErr;
2943 : }
2944 :
2945 : /************************************************************************/
2946 : /* SetDefineMode() */
2947 : /************************************************************************/
2948 10591 : bool netCDFDataset::SetDefineMode(bool bNewDefineMode)
2949 : {
2950 : // Do nothing if already in new define mode
2951 : // or if dataset is in read-only mode or if dataset is true NC4 dataset.
2952 11144 : if (bDefineMode == bNewDefineMode || GetAccess() == GA_ReadOnly ||
2953 553 : eFormat == NCDF_FORMAT_NC4)
2954 10185 : return true;
2955 :
2956 406 : CPLDebug("GDAL_netCDF", "SetDefineMode(%d) old=%d",
2957 406 : static_cast<int>(bNewDefineMode), static_cast<int>(bDefineMode));
2958 :
2959 406 : bDefineMode = bNewDefineMode;
2960 :
2961 : int status;
2962 406 : if (bDefineMode)
2963 141 : status = nc_redef(cdfid);
2964 : else
2965 265 : status = nc_enddef(cdfid);
2966 :
2967 406 : NCDF_ERR(status);
2968 406 : return status == NC_NOERR;
2969 : }
2970 :
2971 : /************************************************************************/
2972 : /* GetMetadataDomainList() */
2973 : /************************************************************************/
2974 :
2975 27 : char **netCDFDataset::GetMetadataDomainList()
2976 : {
2977 27 : char **papszDomains = BuildMetadataDomainList(
2978 : GDALDataset::GetMetadataDomainList(), TRUE, "SUBDATASETS", nullptr);
2979 28 : for (const auto &kv : m_oMapDomainToJSon)
2980 1 : papszDomains = CSLAddString(papszDomains, ("json:" + kv.first).c_str());
2981 27 : return papszDomains;
2982 : }
2983 :
2984 : /************************************************************************/
2985 : /* GetMetadata() */
2986 : /************************************************************************/
2987 356 : char **netCDFDataset::GetMetadata(const char *pszDomain)
2988 : {
2989 356 : if (pszDomain != nullptr && STARTS_WITH_CI(pszDomain, "SUBDATASETS"))
2990 36 : return papszSubDatasets;
2991 :
2992 320 : if (pszDomain != nullptr && STARTS_WITH(pszDomain, "json:"))
2993 : {
2994 1 : auto iter = m_oMapDomainToJSon.find(pszDomain + strlen("json:"));
2995 1 : if (iter != m_oMapDomainToJSon.end())
2996 1 : return iter->second.List();
2997 : }
2998 :
2999 319 : return GDALDataset::GetMetadata(pszDomain);
3000 : }
3001 :
3002 : /************************************************************************/
3003 : /* SetMetadataItem() */
3004 : /************************************************************************/
3005 :
3006 43 : CPLErr netCDFDataset::SetMetadataItem(const char *pszName, const char *pszValue,
3007 : const char *pszDomain)
3008 : {
3009 85 : if (GetAccess() == GA_Update &&
3010 85 : (pszDomain == nullptr || pszDomain[0] == '\0') && pszValue != nullptr)
3011 : {
3012 42 : std::string osName(pszName);
3013 :
3014 : // Same logic as in CopyMetadata()
3015 42 : if (STARTS_WITH(osName.c_str(), "NC_GLOBAL#"))
3016 8 : osName = osName.substr(strlen("NC_GLOBAL#"));
3017 34 : else if (strchr(osName.c_str(), '#') == nullptr)
3018 5 : osName = "GDAL_" + osName;
3019 :
3020 84 : if (STARTS_WITH(osName.c_str(), "NETCDF_DIM_") ||
3021 42 : strchr(osName.c_str(), '#') != nullptr)
3022 : {
3023 : // do nothing
3024 29 : return CE_None;
3025 : }
3026 : else
3027 : {
3028 13 : SetDefineMode(true);
3029 :
3030 13 : if (!NCDFPutAttr(cdfid, NC_GLOBAL, osName.c_str(), pszValue))
3031 13 : return CE_Failure;
3032 : }
3033 : }
3034 :
3035 1 : return GDALPamDataset::SetMetadataItem(pszName, pszValue, pszDomain);
3036 : }
3037 :
3038 : /************************************************************************/
3039 : /* SetMetadata() */
3040 : /************************************************************************/
3041 :
3042 8 : CPLErr netCDFDataset::SetMetadata(char **papszMD, const char *pszDomain)
3043 : {
3044 13 : if (GetAccess() == GA_Update &&
3045 5 : (pszDomain == nullptr || pszDomain[0] == '\0'))
3046 : {
3047 : // We don't handle metadata item removal for now
3048 50 : for (const char *const *papszIter = papszMD; papszIter && *papszIter;
3049 : ++papszIter)
3050 : {
3051 42 : char *pszName = nullptr;
3052 42 : const char *pszValue = CPLParseNameValue(*papszIter, &pszName);
3053 42 : if (pszName && pszValue)
3054 42 : SetMetadataItem(pszName, pszValue);
3055 42 : CPLFree(pszName);
3056 : }
3057 8 : return CE_None;
3058 : }
3059 0 : return GDALPamDataset::SetMetadata(papszMD, pszDomain);
3060 : }
3061 :
3062 : /************************************************************************/
3063 : /* GetSpatialRef() */
3064 : /************************************************************************/
3065 :
3066 168 : const OGRSpatialReference *netCDFDataset::GetSpatialRef() const
3067 : {
3068 168 : if (m_bHasProjection)
3069 69 : return m_oSRS.IsEmpty() ? nullptr : &m_oSRS;
3070 :
3071 99 : return GDALPamDataset::GetSpatialRef();
3072 : }
3073 :
3074 : /************************************************************************/
3075 : /* FetchCopyParam() */
3076 : /************************************************************************/
3077 :
3078 312 : double netCDFDataset::FetchCopyParam(const char *pszGridMappingValue,
3079 : const char *pszParam, double dfDefault,
3080 : bool *pbFound)
3081 :
3082 : {
3083 : char *pszTemp =
3084 312 : CPLStrdup(CPLSPrintf("%s#%s", pszGridMappingValue, pszParam));
3085 312 : const char *pszValue = CSLFetchNameValue(papszMetadata, pszTemp);
3086 312 : CPLFree(pszTemp);
3087 :
3088 312 : if (pbFound)
3089 : {
3090 312 : *pbFound = (pszValue != nullptr);
3091 : }
3092 :
3093 312 : if (pszValue)
3094 : {
3095 0 : return CPLAtofM(pszValue);
3096 : }
3097 :
3098 312 : return dfDefault;
3099 : }
3100 :
3101 : /************************************************************************/
3102 : /* FetchStandardParallels() */
3103 : /************************************************************************/
3104 :
3105 : std::vector<std::string>
3106 0 : netCDFDataset::FetchStandardParallels(const char *pszGridMappingValue)
3107 : {
3108 : // cf-1.0 tags
3109 0 : const char *pszValue = FetchAttr(pszGridMappingValue, CF_PP_STD_PARALLEL);
3110 :
3111 0 : std::vector<std::string> ret;
3112 0 : if (pszValue != nullptr)
3113 : {
3114 0 : CPLStringList aosValues;
3115 0 : if (pszValue[0] != '{' &&
3116 0 : CPLString(pszValue).Trim().find(' ') != std::string::npos)
3117 : {
3118 : // Some files like
3119 : // ftp://data.knmi.nl/download/KNW-NetCDF-3D/1.0/noversion/2013/11/14/KNW-1.0_H37-ERA_NL_20131114.nc
3120 : // do not use standard formatting for arrays, but just space
3121 : // separated syntax
3122 0 : aosValues = CSLTokenizeString2(pszValue, " ", 0);
3123 : }
3124 : else
3125 : {
3126 0 : aosValues = NCDFTokenizeArray(pszValue);
3127 : }
3128 0 : for (int i = 0; i < aosValues.size(); i++)
3129 : {
3130 0 : ret.push_back(aosValues[i]);
3131 : }
3132 : }
3133 : // Try gdal tags.
3134 : else
3135 : {
3136 0 : pszValue = FetchAttr(pszGridMappingValue, CF_PP_STD_PARALLEL_1);
3137 :
3138 0 : if (pszValue != nullptr)
3139 0 : ret.push_back(pszValue);
3140 :
3141 0 : pszValue = FetchAttr(pszGridMappingValue, CF_PP_STD_PARALLEL_2);
3142 :
3143 0 : if (pszValue != nullptr)
3144 0 : ret.push_back(pszValue);
3145 : }
3146 :
3147 0 : return ret;
3148 : }
3149 :
3150 : /************************************************************************/
3151 : /* FetchAttr() */
3152 : /************************************************************************/
3153 :
3154 3612 : const char *netCDFDataset::FetchAttr(const char *pszVarFullName,
3155 : const char *pszAttr)
3156 :
3157 : {
3158 3612 : char *pszKey = CPLStrdup(CPLSPrintf("%s#%s", pszVarFullName, pszAttr));
3159 3612 : const char *pszValue = CSLFetchNameValue(papszMetadata, pszKey);
3160 3612 : CPLFree(pszKey);
3161 3612 : return pszValue;
3162 : }
3163 :
3164 2403 : const char *netCDFDataset::FetchAttr(int nGroupId, int nVarId,
3165 : const char *pszAttr)
3166 :
3167 : {
3168 2403 : char *pszVarFullName = nullptr;
3169 2403 : NCDFGetVarFullName(nGroupId, nVarId, &pszVarFullName);
3170 2403 : const char *pszValue = FetchAttr(pszVarFullName, pszAttr);
3171 2403 : CPLFree(pszVarFullName);
3172 2403 : return pszValue;
3173 : }
3174 :
3175 : /************************************************************************/
3176 : /* IsDifferenceBelow() */
3177 : /************************************************************************/
3178 :
3179 1067 : static bool IsDifferenceBelow(double dfA, double dfB, double dfError)
3180 : {
3181 1067 : const double dfAbsDiff = fabs(dfA - dfB);
3182 1067 : return dfAbsDiff <= dfError;
3183 : }
3184 :
3185 : /************************************************************************/
3186 : /* SetProjectionFromVar() */
3187 : /************************************************************************/
3188 497 : void netCDFDataset::SetProjectionFromVar(
3189 : int nGroupId, int nVarId, bool bReadSRSOnly, const char *pszGivenGM,
3190 : std::string *returnProjStr, nccfdriver::SGeometry_Reader *sg,
3191 : std::vector<std::string> *paosRemovedMDItems)
3192 : {
3193 497 : bool bGotGeogCS = false;
3194 497 : bool bGotCfSRS = false;
3195 497 : bool bGotCfWktSRS = false;
3196 497 : bool bGotGdalSRS = false;
3197 497 : bool bGotCfGT = false;
3198 497 : bool bGotGdalGT = false;
3199 :
3200 : // These values from CF metadata.
3201 497 : OGRSpatialReference oSRS;
3202 497 : oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
3203 497 : size_t xdim = nRasterXSize;
3204 497 : size_t ydim = nRasterYSize;
3205 :
3206 : // These values from GDAL metadata.
3207 497 : const char *pszWKT = nullptr;
3208 497 : const char *pszGeoTransform = nullptr;
3209 :
3210 497 : netCDFDataset *poDS = this; // Perhaps this should be removed for clarity.
3211 :
3212 497 : CPLDebug("GDAL_netCDF", "\n=====\nSetProjectionFromVar( %d, %d)", nGroupId,
3213 : nVarId);
3214 :
3215 : // Get x/y range information.
3216 :
3217 : // Temp variables to use in SetGeoTransform() and SetProjection().
3218 497 : double adfTempGeoTransform[6] = {0.0, 1.0, 0.0, 0.0, 0.0, 1.0};
3219 :
3220 : // Look for grid_mapping metadata.
3221 497 : const char *pszValue = pszGivenGM;
3222 497 : CPLString osTmpGridMapping; // let is in this outer scope as pszValue may
3223 : // point to it
3224 497 : if (pszValue == nullptr)
3225 : {
3226 454 : pszValue = FetchAttr(nGroupId, nVarId, CF_GRD_MAPPING);
3227 454 : if (pszValue && strchr(pszValue, ':') && strchr(pszValue, ' '))
3228 : {
3229 : // Expanded form of grid_mapping
3230 : // e.g. "crsOSGB: x y crsWGS84: lat lon"
3231 : // Pickup the grid_mapping whose coordinates are dimensions of the
3232 : // variable
3233 6 : CPLStringList aosTokens(CSLTokenizeString2(pszValue, " ", 0));
3234 3 : if ((aosTokens.size() % 3) == 0)
3235 : {
3236 3 : for (int i = 0; i < aosTokens.size() / 3; i++)
3237 : {
3238 3 : if (CSLFindString(poDS->papszDimName,
3239 9 : aosTokens[3 * i + 1]) >= 0 &&
3240 3 : CSLFindString(poDS->papszDimName,
3241 3 : aosTokens[3 * i + 2]) >= 0)
3242 : {
3243 3 : osTmpGridMapping = aosTokens[3 * i];
3244 6 : if (!osTmpGridMapping.empty() &&
3245 3 : osTmpGridMapping.back() == ':')
3246 : {
3247 3 : osTmpGridMapping.resize(osTmpGridMapping.size() -
3248 : 1);
3249 : }
3250 3 : pszValue = osTmpGridMapping.c_str();
3251 3 : break;
3252 : }
3253 : }
3254 : }
3255 : }
3256 : }
3257 497 : char *pszGridMappingValue = CPLStrdup(pszValue ? pszValue : "");
3258 :
3259 497 : if (!EQUAL(pszGridMappingValue, ""))
3260 : {
3261 : // Read grid_mapping metadata.
3262 213 : int nProjGroupID = -1;
3263 213 : int nProjVarID = -1;
3264 213 : if (NCDFResolveVar(nGroupId, pszGridMappingValue, &nProjGroupID,
3265 213 : &nProjVarID) == CE_None)
3266 : {
3267 212 : poDS->ReadAttributes(nProjGroupID, nProjVarID);
3268 :
3269 : // Look for GDAL spatial_ref and GeoTransform within grid_mapping.
3270 212 : CPLFree(pszGridMappingValue);
3271 212 : pszGridMappingValue = nullptr;
3272 212 : NCDFGetVarFullName(nProjGroupID, nProjVarID, &pszGridMappingValue);
3273 212 : if (pszGridMappingValue)
3274 : {
3275 212 : CPLDebug("GDAL_netCDF", "got grid_mapping %s",
3276 : pszGridMappingValue);
3277 212 : pszWKT = FetchAttr(pszGridMappingValue, NCDF_SPATIAL_REF);
3278 212 : if (!pszWKT)
3279 : {
3280 34 : pszWKT = FetchAttr(pszGridMappingValue, NCDF_CRS_WKT);
3281 : }
3282 : else
3283 : {
3284 178 : bGotGdalSRS = true;
3285 178 : CPLDebug("GDAL_netCDF", "setting WKT from GDAL");
3286 : }
3287 212 : if (pszWKT)
3288 : {
3289 182 : if (!bGotGdalSRS)
3290 : {
3291 4 : bGotCfWktSRS = true;
3292 4 : CPLDebug("GDAL_netCDF", "setting WKT from CF");
3293 : }
3294 182 : if (returnProjStr != nullptr)
3295 : {
3296 41 : (*returnProjStr) = std::string(pszWKT);
3297 : }
3298 : else
3299 : {
3300 141 : m_bAddedProjectionVarsDefs = true;
3301 141 : m_bAddedProjectionVarsData = true;
3302 282 : OGRSpatialReference oSRSTmp;
3303 141 : oSRSTmp.SetAxisMappingStrategy(
3304 : OAMS_TRADITIONAL_GIS_ORDER);
3305 141 : oSRSTmp.importFromWkt(pszWKT);
3306 141 : SetSpatialRefNoUpdate(&oSRSTmp);
3307 : }
3308 : pszGeoTransform =
3309 182 : FetchAttr(pszGridMappingValue, NCDF_GEOTRANSFORM);
3310 : }
3311 : }
3312 : else
3313 : {
3314 0 : pszGridMappingValue = CPLStrdup("");
3315 : }
3316 : }
3317 : }
3318 :
3319 : // Get information about the file.
3320 : //
3321 : // Was this file created by the GDAL netcdf driver?
3322 : // Was this file created by the newer (CF-conformant) driver?
3323 : //
3324 : // 1) If GDAL netcdf metadata is set, and version >= 1.9,
3325 : // it was created with the new driver
3326 : // 2) Else, if spatial_ref and GeoTransform are present in the
3327 : // grid_mapping variable, it was created by the old driver
3328 497 : pszValue = FetchAttr("NC_GLOBAL", "GDAL");
3329 :
3330 497 : if (pszValue && NCDFIsGDALVersionGTE(pszValue, 1900))
3331 : {
3332 238 : bIsGdalFile = true;
3333 238 : bIsGdalCfFile = true;
3334 : }
3335 259 : else if (pszWKT != nullptr && pszGeoTransform != nullptr)
3336 : {
3337 14 : bIsGdalFile = true;
3338 14 : bIsGdalCfFile = false;
3339 : }
3340 :
3341 : // Set default bottom-up default value.
3342 : // Y axis dimension and absence of GT can modify this value.
3343 : // Override with Config option GDAL_NETCDF_BOTTOMUP.
3344 :
3345 : // New driver is bottom-up by default.
3346 497 : if ((bIsGdalFile && !bIsGdalCfFile) || bSwitchedXY)
3347 16 : poDS->bBottomUp = false;
3348 : else
3349 481 : poDS->bBottomUp = true;
3350 :
3351 497 : CPLDebug("GDAL_netCDF",
3352 : "bIsGdalFile=%d bIsGdalCfFile=%d bSwitchedXY=%d bBottomUp=%d",
3353 497 : static_cast<int>(bIsGdalFile), static_cast<int>(bIsGdalCfFile),
3354 497 : static_cast<int>(bSwitchedXY), static_cast<int>(bBottomUp));
3355 :
3356 : // Read projection coordinates.
3357 :
3358 497 : int nGroupDimXID = -1;
3359 497 : int nVarDimXID = -1;
3360 497 : int nGroupDimYID = -1;
3361 497 : int nVarDimYID = -1;
3362 497 : if (sg != nullptr)
3363 : {
3364 43 : nGroupDimXID = sg->get_ncID();
3365 43 : nGroupDimYID = sg->get_ncID();
3366 43 : nVarDimXID = sg->getNodeCoordVars()[0];
3367 43 : nVarDimYID = sg->getNodeCoordVars()[1];
3368 : }
3369 :
3370 497 : if (!bReadSRSOnly)
3371 : {
3372 344 : NCDFResolveVar(nGroupId, poDS->papszDimName[nXDimID], &nGroupDimXID,
3373 : &nVarDimXID);
3374 344 : NCDFResolveVar(nGroupId, poDS->papszDimName[nYDimID], &nGroupDimYID,
3375 : &nVarDimYID);
3376 : // TODO: if above resolving fails we should also search for coordinate
3377 : // variables without same name than dimension using the same resolving
3378 : // logic. This should handle for example NASA Ocean Color L2 products.
3379 :
3380 : const bool bIgnoreXYAxisNameChecks =
3381 688 : CPLTestBool(CSLFetchNameValueDef(
3382 344 : papszOpenOptions, "IGNORE_XY_AXIS_NAME_CHECKS",
3383 : CPLGetConfigOption("GDAL_NETCDF_IGNORE_XY_AXIS_NAME_CHECKS",
3384 344 : "NO"))) ||
3385 : // Dataset from https://github.com/OSGeo/gdal/issues/4075 has a res
3386 : // and transform attributes
3387 344 : (FetchAttr(nGroupId, nVarId, "res") != nullptr &&
3388 688 : FetchAttr(nGroupId, nVarId, "transform") != nullptr) ||
3389 343 : FetchAttr(nGroupId, NC_GLOBAL, "GMT_version") != nullptr;
3390 :
3391 : // Check that they are 1D or 2D variables
3392 344 : if (nVarDimXID >= 0)
3393 : {
3394 250 : int ndims = -1;
3395 250 : nc_inq_varndims(nGroupId, nVarDimXID, &ndims);
3396 250 : if (ndims == 0 || ndims > 2)
3397 0 : nVarDimXID = -1;
3398 250 : else if (!bIgnoreXYAxisNameChecks)
3399 : {
3400 248 : if (!NCDFIsVarLongitude(nGroupId, nVarDimXID, nullptr) &&
3401 159 : !NCDFIsVarProjectionX(nGroupId, nVarDimXID, nullptr) &&
3402 : // In case of inversion of X/Y
3403 438 : !NCDFIsVarLatitude(nGroupId, nVarDimXID, nullptr) &&
3404 31 : !NCDFIsVarProjectionY(nGroupId, nVarDimXID, nullptr))
3405 : {
3406 : char szVarNameX[NC_MAX_NAME + 1];
3407 31 : CPL_IGNORE_RET_VAL(
3408 31 : nc_inq_varname(nGroupId, nVarDimXID, szVarNameX));
3409 31 : if (!(ndims == 1 &&
3410 30 : (EQUAL(szVarNameX, CF_LONGITUDE_STD_NAME) ||
3411 29 : EQUAL(szVarNameX, CF_LONGITUDE_VAR_NAME))))
3412 : {
3413 30 : CPLDebug(
3414 : "netCDF",
3415 : "Georeferencing ignored due to non-specific "
3416 : "enough X axis name. "
3417 : "Set GDAL_NETCDF_IGNORE_XY_AXIS_NAME_CHECKS=YES "
3418 : "as configuration option to bypass this check");
3419 30 : nVarDimXID = -1;
3420 : }
3421 : }
3422 : }
3423 : }
3424 :
3425 344 : if (nVarDimYID >= 0)
3426 : {
3427 252 : int ndims = -1;
3428 252 : nc_inq_varndims(nGroupId, nVarDimYID, &ndims);
3429 252 : if (ndims == 0 || ndims > 2)
3430 1 : nVarDimYID = -1;
3431 251 : else if (!bIgnoreXYAxisNameChecks)
3432 : {
3433 249 : if (!NCDFIsVarLatitude(nGroupId, nVarDimYID, nullptr) &&
3434 160 : !NCDFIsVarProjectionY(nGroupId, nVarDimYID, nullptr) &&
3435 : // In case of inversion of X/Y
3436 441 : !NCDFIsVarLongitude(nGroupId, nVarDimYID, nullptr) &&
3437 32 : !NCDFIsVarProjectionX(nGroupId, nVarDimYID, nullptr))
3438 : {
3439 : char szVarNameY[NC_MAX_NAME + 1];
3440 32 : CPL_IGNORE_RET_VAL(
3441 32 : nc_inq_varname(nGroupId, nVarDimYID, szVarNameY));
3442 32 : if (!(ndims == 1 &&
3443 32 : (EQUAL(szVarNameY, CF_LATITUDE_STD_NAME) ||
3444 31 : EQUAL(szVarNameY, CF_LATITUDE_VAR_NAME))))
3445 : {
3446 31 : CPLDebug(
3447 : "netCDF",
3448 : "Georeferencing ignored due to non-specific "
3449 : "enough Y axis name. "
3450 : "Set GDAL_NETCDF_IGNORE_XY_AXIS_NAME_CHECKS=YES "
3451 : "as configuration option to bypass this check");
3452 31 : nVarDimYID = -1;
3453 : }
3454 : }
3455 : }
3456 : }
3457 :
3458 344 : if ((nVarDimXID >= 0 && xdim == 1) || (nVarDimXID >= 0 && ydim == 1))
3459 : {
3460 0 : CPLError(CE_Warning, CPLE_AppDefined,
3461 : "1-pixel width/height files not supported, "
3462 : "xdim: %ld ydim: %ld",
3463 : static_cast<long>(xdim), static_cast<long>(ydim));
3464 0 : nVarDimXID = -1;
3465 0 : nVarDimYID = -1;
3466 : }
3467 : }
3468 :
3469 497 : const char *pszUnits = nullptr;
3470 497 : if ((nVarDimXID != -1) && (nVarDimYID != -1) && xdim > 0 && ydim > 0)
3471 : {
3472 263 : const char *pszUnitsX = FetchAttr(nGroupDimXID, nVarDimXID, "units");
3473 263 : const char *pszUnitsY = FetchAttr(nGroupDimYID, nVarDimYID, "units");
3474 : // Normalize degrees_east/degrees_north to degrees
3475 : // Cf https://github.com/OSGeo/gdal/issues/11009
3476 263 : if (pszUnitsX && EQUAL(pszUnitsX, "degrees_east"))
3477 78 : pszUnitsX = "degrees";
3478 263 : if (pszUnitsY && EQUAL(pszUnitsY, "degrees_north"))
3479 78 : pszUnitsY = "degrees";
3480 :
3481 263 : if (pszUnitsX && pszUnitsY)
3482 : {
3483 216 : if (EQUAL(pszUnitsX, pszUnitsY))
3484 213 : pszUnits = pszUnitsX;
3485 3 : else if (!pszWKT && !EQUAL(pszGridMappingValue, ""))
3486 : {
3487 0 : CPLError(CE_Failure, CPLE_AppDefined,
3488 : "X axis unit (%s) is different from Y axis "
3489 : "unit (%s). SRS will ignore axis unit and be "
3490 : "likely wrong.",
3491 : pszUnitsX, pszUnitsY);
3492 : }
3493 : }
3494 47 : else if (pszUnitsX && !pszWKT && !EQUAL(pszGridMappingValue, ""))
3495 : {
3496 0 : CPLError(CE_Failure, CPLE_AppDefined,
3497 : "X axis unit is defined, but not Y one ."
3498 : "SRS will ignore axis unit and be likely wrong.");
3499 : }
3500 47 : else if (pszUnitsY && !pszWKT && !EQUAL(pszGridMappingValue, ""))
3501 : {
3502 0 : CPLError(CE_Failure, CPLE_AppDefined,
3503 : "Y axis unit is defined, but not X one ."
3504 : "SRS will ignore axis unit and be likely wrong.");
3505 : }
3506 : }
3507 :
3508 497 : if (!pszWKT && !EQUAL(pszGridMappingValue, ""))
3509 : {
3510 31 : CPLStringList aosGridMappingKeyValues;
3511 31 : const size_t nLenGridMappingValue = strlen(pszGridMappingValue);
3512 789 : for (const char *const *papszIter = papszMetadata;
3513 789 : papszIter && *papszIter; ++papszIter)
3514 : {
3515 758 : if (STARTS_WITH(*papszIter, pszGridMappingValue) &&
3516 236 : (*papszIter)[nLenGridMappingValue] == '#')
3517 : {
3518 236 : char *pszKey = nullptr;
3519 472 : pszValue = CPLParseNameValue(
3520 236 : *papszIter + nLenGridMappingValue + 1, &pszKey);
3521 236 : if (pszKey && pszValue)
3522 236 : aosGridMappingKeyValues.SetNameValue(pszKey, pszValue);
3523 236 : CPLFree(pszKey);
3524 : }
3525 : }
3526 :
3527 31 : bGotGeogCS = aosGridMappingKeyValues.FetchNameValue(
3528 : CF_PP_SEMI_MAJOR_AXIS) != nullptr;
3529 :
3530 31 : oSRS.importFromCF1(aosGridMappingKeyValues.List(), pszUnits);
3531 31 : bGotCfSRS = oSRS.IsGeographic() || oSRS.IsProjected();
3532 : }
3533 : else
3534 : {
3535 : // Dataset from https://github.com/OSGeo/gdal/issues/4075 has a "crs"
3536 : // attribute hold on the variable of interest that contains a PROJ.4
3537 : // string
3538 466 : pszValue = FetchAttr(nGroupId, nVarId, "crs");
3539 467 : if (pszValue &&
3540 1 : (strstr(pszValue, "+proj=") != nullptr ||
3541 0 : strstr(pszValue, "GEOGCS") != nullptr ||
3542 0 : strstr(pszValue, "PROJCS") != nullptr ||
3543 467 : strstr(pszValue, "EPSG:") != nullptr) &&
3544 1 : oSRS.SetFromUserInput(pszValue) == OGRERR_NONE)
3545 : {
3546 1 : bGotCfSRS = true;
3547 : }
3548 : }
3549 :
3550 : // Set Projection from CF.
3551 497 : double dfLinearUnitsConvFactor = 1.0;
3552 497 : if ((bGotGeogCS || bGotCfSRS))
3553 : {
3554 31 : if ((nVarDimXID != -1) && (nVarDimYID != -1) && xdim > 0 && ydim > 0)
3555 : {
3556 : // Set SRS Units.
3557 :
3558 : // Check units for x and y.
3559 28 : if (oSRS.IsProjected())
3560 : {
3561 25 : dfLinearUnitsConvFactor = oSRS.GetLinearUnits(nullptr);
3562 :
3563 : // If the user doesn't ask to preserve the axis unit,
3564 : // then normalize to metre
3565 31 : if (dfLinearUnitsConvFactor != 1.0 &&
3566 6 : !CPLFetchBool(GetOpenOptions(), "PRESERVE_AXIS_UNIT_IN_CRS",
3567 : false))
3568 : {
3569 5 : oSRS.SetLinearUnits("metre", 1.0);
3570 5 : oSRS.SetAuthority("PROJCS|UNIT", "EPSG", 9001);
3571 : }
3572 : else
3573 : {
3574 20 : dfLinearUnitsConvFactor = 1.0;
3575 : }
3576 : }
3577 : }
3578 :
3579 : // Set projection.
3580 31 : char *pszTempProjection = nullptr;
3581 31 : oSRS.exportToWkt(&pszTempProjection);
3582 31 : if (pszTempProjection)
3583 : {
3584 31 : CPLDebug("GDAL_netCDF", "setting WKT from CF");
3585 31 : if (returnProjStr != nullptr)
3586 : {
3587 2 : (*returnProjStr) = std::string(pszTempProjection);
3588 : }
3589 : else
3590 : {
3591 29 : m_bAddedProjectionVarsDefs = true;
3592 29 : m_bAddedProjectionVarsData = true;
3593 29 : SetSpatialRefNoUpdate(&oSRS);
3594 : }
3595 : }
3596 31 : CPLFree(pszTempProjection);
3597 : }
3598 :
3599 497 : if (!bReadSRSOnly && (nVarDimXID != -1) && (nVarDimYID != -1) && xdim > 0 &&
3600 : ydim > 0)
3601 : {
3602 : double *pdfXCoord =
3603 220 : static_cast<double *>(CPLCalloc(xdim, sizeof(double)));
3604 : double *pdfYCoord =
3605 220 : static_cast<double *>(CPLCalloc(ydim, sizeof(double)));
3606 :
3607 220 : size_t start[2] = {0, 0};
3608 220 : size_t edge[2] = {xdim, 0};
3609 220 : int status = nc_get_vara_double(nGroupDimXID, nVarDimXID, start, edge,
3610 : pdfXCoord);
3611 220 : NCDF_ERR(status);
3612 :
3613 220 : edge[0] = ydim;
3614 220 : status = nc_get_vara_double(nGroupDimYID, nVarDimYID, start, edge,
3615 : pdfYCoord);
3616 220 : NCDF_ERR(status);
3617 :
3618 220 : nc_type nc_var_dimx_datatype = NC_NAT;
3619 : status =
3620 220 : nc_inq_vartype(nGroupDimXID, nVarDimXID, &nc_var_dimx_datatype);
3621 220 : NCDF_ERR(status);
3622 :
3623 220 : nc_type nc_var_dimy_datatype = NC_NAT;
3624 : status =
3625 220 : nc_inq_vartype(nGroupDimYID, nVarDimYID, &nc_var_dimy_datatype);
3626 220 : NCDF_ERR(status);
3627 :
3628 220 : if (!poDS->bSwitchedXY)
3629 : {
3630 : // Convert ]180,540] longitude values to ]-180,0].
3631 307 : if (NCDFIsVarLongitude(nGroupDimXID, nVarDimXID, nullptr) &&
3632 89 : CPLTestBool(
3633 : CPLGetConfigOption("GDAL_NETCDF_CENTERLONG_180", "YES")))
3634 : {
3635 : // If minimum longitude is > 180, subtract 360 from all.
3636 : // Add a check on the maximum X value too, since
3637 : // NCDFIsVarLongitude() is not very specific by default (see
3638 : // https://github.com/OSGeo/gdal/issues/1440)
3639 96 : if (std::min(pdfXCoord[0], pdfXCoord[xdim - 1]) > 180.0 &&
3640 7 : std::max(pdfXCoord[0], pdfXCoord[xdim - 1]) <= 540)
3641 : {
3642 0 : CPLDebug(
3643 : "GDAL_netCDF",
3644 : "Offsetting longitudes from ]180,540] to ]-180,180]. "
3645 : "Can be disabled with GDAL_NETCDF_CENTERLONG_180=NO");
3646 0 : for (size_t i = 0; i < xdim; i++)
3647 0 : pdfXCoord[i] -= 360;
3648 : }
3649 : }
3650 : }
3651 :
3652 : // Is pixel spacing uniform across the map?
3653 :
3654 : // Check Longitude.
3655 :
3656 220 : bool bLonSpacingOK = false;
3657 220 : if (xdim == 2)
3658 : {
3659 28 : bLonSpacingOK = true;
3660 : }
3661 : else
3662 : {
3663 192 : bool bWestIsLeft = (pdfXCoord[0] < pdfXCoord[xdim - 1]);
3664 :
3665 : // fix longitudes if longitudes should increase from
3666 : // west to east, but west > east
3667 271 : if (NCDFIsVarLongitude(nGroupDimXID, nVarDimXID, nullptr) &&
3668 79 : !bWestIsLeft)
3669 : {
3670 2 : size_t ndecreases = 0;
3671 :
3672 : // there is lon wrap if longitudes increase
3673 : // with one single decrease
3674 107 : for (size_t i = 1; i < xdim; i++)
3675 : {
3676 105 : if (pdfXCoord[i] < pdfXCoord[i - 1])
3677 1 : ndecreases++;
3678 : }
3679 :
3680 2 : if (ndecreases == 1)
3681 : {
3682 1 : CPLDebug("GDAL_netCDF", "longitude wrap detected");
3683 4 : for (size_t i = 0; i < xdim; i++)
3684 : {
3685 3 : if (pdfXCoord[i] > pdfXCoord[xdim - 1])
3686 1 : pdfXCoord[i] -= 360;
3687 : }
3688 : }
3689 : }
3690 :
3691 192 : const double dfSpacingBegin = pdfXCoord[1] - pdfXCoord[0];
3692 192 : const double dfSpacingMiddle =
3693 192 : pdfXCoord[xdim / 2 + 1] - pdfXCoord[xdim / 2];
3694 192 : const double dfSpacingLast =
3695 192 : pdfXCoord[xdim - 1] - pdfXCoord[xdim - 2];
3696 :
3697 192 : CPLDebug("GDAL_netCDF",
3698 : "xdim: %ld dfSpacingBegin: %f dfSpacingMiddle: %f "
3699 : "dfSpacingLast: %f",
3700 : static_cast<long>(xdim), dfSpacingBegin, dfSpacingMiddle,
3701 : dfSpacingLast);
3702 : #ifdef NCDF_DEBUG
3703 : CPLDebug("GDAL_netCDF", "xcoords: %f %f %f %f %f %f", pdfXCoord[0],
3704 : pdfXCoord[1], pdfXCoord[xdim / 2],
3705 : pdfXCoord[(xdim / 2) + 1], pdfXCoord[xdim - 2],
3706 : pdfXCoord[xdim - 1]);
3707 : #endif
3708 :
3709 : // ftp://ftp.cdc.noaa.gov/Datasets/NARR/Dailies/monolevel/vwnd.10m.2015.nc
3710 : // requires a 0.02% tolerance, so let's settle for 0.05%
3711 :
3712 : // For float variables, increase to 0.2% (as seen in
3713 : // https://github.com/OSGeo/gdal/issues/3663)
3714 192 : const double dfEpsRel =
3715 192 : nc_var_dimx_datatype == NC_FLOAT ? 0.002 : 0.0005;
3716 :
3717 : const double dfEps =
3718 : dfEpsRel *
3719 384 : std::max(fabs(dfSpacingBegin),
3720 192 : std::max(fabs(dfSpacingMiddle), fabs(dfSpacingLast)));
3721 378 : if (IsDifferenceBelow(dfSpacingBegin, dfSpacingLast, dfEps) &&
3722 378 : IsDifferenceBelow(dfSpacingBegin, dfSpacingMiddle, dfEps) &&
3723 186 : IsDifferenceBelow(dfSpacingMiddle, dfSpacingLast, dfEps))
3724 : {
3725 186 : bLonSpacingOK = true;
3726 : }
3727 6 : else if (CPLTestBool(CPLGetConfigOption(
3728 : "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK", "NO")))
3729 : {
3730 0 : bLonSpacingOK = true;
3731 0 : CPLDebug(
3732 : "GDAL_netCDF",
3733 : "Longitude/X is not equally spaced, but will be considered "
3734 : "as such because of "
3735 : "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK");
3736 : }
3737 : }
3738 :
3739 220 : if (bLonSpacingOK == false)
3740 : {
3741 6 : CPLDebug(
3742 : "GDAL_netCDF", "%s",
3743 : "Longitude/X is not equally spaced (with a 0.05% tolerance). "
3744 : "You may set the "
3745 : "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK configuration "
3746 : "option to YES to ignore this check");
3747 : }
3748 :
3749 : // Check Latitude.
3750 220 : bool bLatSpacingOK = false;
3751 :
3752 220 : if (ydim == 2)
3753 : {
3754 48 : bLatSpacingOK = true;
3755 : }
3756 : else
3757 : {
3758 172 : const double dfSpacingBegin = pdfYCoord[1] - pdfYCoord[0];
3759 172 : const double dfSpacingMiddle =
3760 172 : pdfYCoord[ydim / 2 + 1] - pdfYCoord[ydim / 2];
3761 :
3762 172 : const double dfSpacingLast =
3763 172 : pdfYCoord[ydim - 1] - pdfYCoord[ydim - 2];
3764 :
3765 172 : CPLDebug("GDAL_netCDF",
3766 : "ydim: %ld dfSpacingBegin: %f dfSpacingMiddle: %f "
3767 : "dfSpacingLast: %f",
3768 : (long)ydim, dfSpacingBegin, dfSpacingMiddle,
3769 : dfSpacingLast);
3770 : #ifdef NCDF_DEBUG
3771 : CPLDebug("GDAL_netCDF", "ycoords: %f %f %f %f %f %f", pdfYCoord[0],
3772 : pdfYCoord[1], pdfYCoord[ydim / 2],
3773 : pdfYCoord[(ydim / 2) + 1], pdfYCoord[ydim - 2],
3774 : pdfYCoord[ydim - 1]);
3775 : #endif
3776 :
3777 172 : const double dfEpsRel =
3778 172 : nc_var_dimy_datatype == NC_FLOAT ? 0.002 : 0.0005;
3779 :
3780 : const double dfEps =
3781 : dfEpsRel *
3782 344 : std::max(fabs(dfSpacingBegin),
3783 172 : std::max(fabs(dfSpacingMiddle), fabs(dfSpacingLast)));
3784 342 : if (IsDifferenceBelow(dfSpacingBegin, dfSpacingLast, dfEps) &&
3785 342 : IsDifferenceBelow(dfSpacingBegin, dfSpacingMiddle, dfEps) &&
3786 161 : IsDifferenceBelow(dfSpacingMiddle, dfSpacingLast, dfEps))
3787 : {
3788 161 : bLatSpacingOK = true;
3789 : }
3790 11 : else if (CPLTestBool(CPLGetConfigOption(
3791 : "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK", "NO")))
3792 : {
3793 0 : bLatSpacingOK = true;
3794 0 : CPLDebug(
3795 : "GDAL_netCDF",
3796 : "Latitude/Y is not equally spaced, but will be considered "
3797 : "as such because of "
3798 : "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK");
3799 : }
3800 11 : else if (!oSRS.IsProjected() &&
3801 11 : fabs(dfSpacingBegin - dfSpacingLast) <= 0.1 &&
3802 30 : fabs(dfSpacingBegin - dfSpacingMiddle) <= 0.1 &&
3803 8 : fabs(dfSpacingMiddle - dfSpacingLast) <= 0.1)
3804 : {
3805 8 : bLatSpacingOK = true;
3806 8 : CPLError(CE_Warning, CPLE_AppDefined,
3807 : "Latitude grid not spaced evenly. "
3808 : "Setting projection for grid spacing is "
3809 : "within 0.1 degrees threshold.");
3810 :
3811 8 : CPLDebug("GDAL_netCDF",
3812 : "Latitude grid not spaced evenly, but within 0.1 "
3813 : "degree threshold (probably a Gaussian grid). "
3814 : "Saving original latitude values in Y_VALUES "
3815 : "geolocation metadata");
3816 8 : Set1DGeolocation(nGroupDimYID, nVarDimYID, "Y");
3817 : }
3818 :
3819 172 : if (bLatSpacingOK == false)
3820 : {
3821 3 : CPLDebug(
3822 : "GDAL_netCDF", "%s",
3823 : "Latitude/Y is not equally spaced (with a 0.05% "
3824 : "tolerance). "
3825 : "You may set the "
3826 : "GDAL_NETCDF_IGNORE_EQUALLY_SPACED_XY_CHECK configuration "
3827 : "option to YES to ignore this check");
3828 : }
3829 : }
3830 :
3831 220 : if (bLonSpacingOK && bLatSpacingOK)
3832 : {
3833 : // We have gridded data so we can set the Georeferencing info.
3834 :
3835 : // Enable GeoTransform.
3836 :
3837 : // In the following "actual_range" and "node_offset"
3838 : // are attributes used by netCDF files created by GMT.
3839 : // If we find them we know how to proceed. Else, use
3840 : // the original algorithm.
3841 213 : bGotCfGT = true;
3842 :
3843 213 : int node_offset = 0;
3844 213 : NCDFResolveAttInt(nGroupId, NC_GLOBAL, "node_offset", &node_offset);
3845 :
3846 213 : double adfActualRange[2] = {0.0, 0.0};
3847 213 : double xMinMax[2] = {0.0, 0.0};
3848 213 : double yMinMax[2] = {0.0, 0.0};
3849 :
3850 : const auto RoundMinMaxForFloatVals =
3851 58 : [](double &dfMin, double &dfMax, int nIntervals)
3852 : {
3853 : // Helps for a case where longitudes range from
3854 : // -179.99 to 180.0 with a 0.01 degree spacing.
3855 : // However as this is encoded in a float array,
3856 : // -179.99 is actually read as -179.99000549316406 as
3857 : // a double. Try to detect that and correct the rounding
3858 :
3859 87 : const auto IsAlmostInteger = [](double dfVal)
3860 : {
3861 87 : constexpr double THRESHOLD_INTEGER = 1e-3;
3862 87 : return std::fabs(dfVal - std::round(dfVal)) <=
3863 87 : THRESHOLD_INTEGER;
3864 : };
3865 :
3866 58 : const double dfSpacing = (dfMax - dfMin) / nIntervals;
3867 58 : if (dfSpacing > 0)
3868 : {
3869 47 : const double dfInvSpacing = 1.0 / dfSpacing;
3870 47 : if (IsAlmostInteger(dfInvSpacing))
3871 : {
3872 20 : const double dfRoundedSpacing =
3873 20 : 1.0 / std::round(dfInvSpacing);
3874 20 : const double dfMinDivRoundedSpacing =
3875 20 : dfMin / dfRoundedSpacing;
3876 20 : const double dfMaxDivRoundedSpacing =
3877 20 : dfMax / dfRoundedSpacing;
3878 40 : if (IsAlmostInteger(dfMinDivRoundedSpacing) &&
3879 20 : IsAlmostInteger(dfMaxDivRoundedSpacing))
3880 : {
3881 20 : const double dfRoundedMin =
3882 20 : std::round(dfMinDivRoundedSpacing) *
3883 : dfRoundedSpacing;
3884 20 : const double dfRoundedMax =
3885 20 : std::round(dfMaxDivRoundedSpacing) *
3886 : dfRoundedSpacing;
3887 20 : if (static_cast<float>(dfMin) ==
3888 20 : static_cast<float>(dfRoundedMin) &&
3889 8 : static_cast<float>(dfMax) ==
3890 8 : static_cast<float>(dfRoundedMax))
3891 : {
3892 7 : dfMin = dfRoundedMin;
3893 7 : dfMax = dfRoundedMax;
3894 : }
3895 : }
3896 : }
3897 : }
3898 58 : };
3899 :
3900 213 : if (!nc_get_att_double(nGroupDimXID, nVarDimXID, "actual_range",
3901 : adfActualRange))
3902 : {
3903 3 : xMinMax[0] = adfActualRange[0];
3904 3 : xMinMax[1] = adfActualRange[1];
3905 :
3906 : // Present xMinMax[] in the same order as padfXCoord
3907 3 : if ((xMinMax[0] - xMinMax[1]) *
3908 3 : (pdfXCoord[0] - pdfXCoord[xdim - 1]) <
3909 : 0)
3910 : {
3911 0 : std::swap(xMinMax[0], xMinMax[1]);
3912 : }
3913 : }
3914 : else
3915 : {
3916 210 : xMinMax[0] = pdfXCoord[0];
3917 210 : xMinMax[1] = pdfXCoord[xdim - 1];
3918 210 : node_offset = 0;
3919 :
3920 210 : if (nc_var_dimx_datatype == NC_FLOAT)
3921 : {
3922 29 : RoundMinMaxForFloatVals(xMinMax[0], xMinMax[1],
3923 29 : poDS->nRasterXSize - 1);
3924 : }
3925 : }
3926 :
3927 213 : if (!nc_get_att_double(nGroupDimYID, nVarDimYID, "actual_range",
3928 : adfActualRange))
3929 : {
3930 3 : yMinMax[0] = adfActualRange[0];
3931 3 : yMinMax[1] = adfActualRange[1];
3932 :
3933 : // Present yMinMax[] in the same order as pdfYCoord
3934 3 : if ((yMinMax[0] - yMinMax[1]) *
3935 3 : (pdfYCoord[0] - pdfYCoord[ydim - 1]) <
3936 : 0)
3937 : {
3938 1 : std::swap(yMinMax[0], yMinMax[1]);
3939 : }
3940 : }
3941 : else
3942 : {
3943 210 : yMinMax[0] = pdfYCoord[0];
3944 210 : yMinMax[1] = pdfYCoord[ydim - 1];
3945 210 : node_offset = 0;
3946 :
3947 210 : if (nc_var_dimy_datatype == NC_FLOAT)
3948 : {
3949 29 : RoundMinMaxForFloatVals(yMinMax[0], yMinMax[1],
3950 29 : poDS->nRasterYSize - 1);
3951 : }
3952 : }
3953 :
3954 213 : double dfCoordOffset = 0.0;
3955 213 : double dfCoordScale = 1.0;
3956 213 : if (!nc_get_att_double(nGroupId, nVarDimXID, CF_ADD_OFFSET,
3957 217 : &dfCoordOffset) &&
3958 4 : !nc_get_att_double(nGroupId, nVarDimXID, CF_SCALE_FACTOR,
3959 : &dfCoordScale))
3960 : {
3961 4 : xMinMax[0] = dfCoordOffset + xMinMax[0] * dfCoordScale;
3962 4 : xMinMax[1] = dfCoordOffset + xMinMax[1] * dfCoordScale;
3963 : }
3964 :
3965 213 : if (!nc_get_att_double(nGroupId, nVarDimYID, CF_ADD_OFFSET,
3966 217 : &dfCoordOffset) &&
3967 4 : !nc_get_att_double(nGroupId, nVarDimYID, CF_SCALE_FACTOR,
3968 : &dfCoordScale))
3969 : {
3970 4 : yMinMax[0] = dfCoordOffset + yMinMax[0] * dfCoordScale;
3971 4 : yMinMax[1] = dfCoordOffset + yMinMax[1] * dfCoordScale;
3972 : }
3973 :
3974 : // Check for reverse order of y-coordinate.
3975 213 : if (!bSwitchedXY)
3976 : {
3977 211 : poDS->bBottomUp = (yMinMax[0] <= yMinMax[1]);
3978 211 : CPLDebug("GDAL_netCDF", "set bBottomUp = %d from Y axis",
3979 211 : static_cast<int>(poDS->bBottomUp));
3980 211 : if (!poDS->bBottomUp)
3981 : {
3982 32 : std::swap(yMinMax[0], yMinMax[1]);
3983 : }
3984 : }
3985 :
3986 : // Geostationary satellites can specify units in (micro)radians
3987 : // So we check if they do, and if so convert to linear units
3988 : // (meters)
3989 213 : const char *pszProjName = oSRS.GetAttrValue("PROJECTION");
3990 213 : if (pszProjName != nullptr)
3991 : {
3992 24 : if (EQUAL(pszProjName, SRS_PT_GEOSTATIONARY_SATELLITE))
3993 : {
3994 : double satelliteHeight =
3995 3 : oSRS.GetProjParm(SRS_PP_SATELLITE_HEIGHT, 1.0);
3996 3 : size_t nAttlen = 0;
3997 : char szUnits[NC_MAX_NAME + 1];
3998 3 : szUnits[0] = '\0';
3999 3 : nc_type nAttype = NC_NAT;
4000 3 : nc_inq_att(nGroupId, nVarDimXID, "units", &nAttype,
4001 : &nAttlen);
4002 6 : if (nAttlen < sizeof(szUnits) &&
4003 3 : nc_get_att_text(nGroupId, nVarDimXID, "units",
4004 : szUnits) == NC_NOERR)
4005 : {
4006 3 : szUnits[nAttlen] = '\0';
4007 3 : if (EQUAL(szUnits, "microradian"))
4008 : {
4009 1 : xMinMax[0] =
4010 1 : xMinMax[0] * satelliteHeight * 0.000001;
4011 1 : xMinMax[1] =
4012 1 : xMinMax[1] * satelliteHeight * 0.000001;
4013 : }
4014 2 : else if (EQUAL(szUnits, "rad") ||
4015 1 : EQUAL(szUnits, "radian"))
4016 : {
4017 2 : xMinMax[0] = xMinMax[0] * satelliteHeight;
4018 2 : xMinMax[1] = xMinMax[1] * satelliteHeight;
4019 : }
4020 : }
4021 3 : szUnits[0] = '\0';
4022 3 : nc_inq_att(nGroupId, nVarDimYID, "units", &nAttype,
4023 : &nAttlen);
4024 6 : if (nAttlen < sizeof(szUnits) &&
4025 3 : nc_get_att_text(nGroupId, nVarDimYID, "units",
4026 : szUnits) == NC_NOERR)
4027 : {
4028 3 : szUnits[nAttlen] = '\0';
4029 3 : if (EQUAL(szUnits, "microradian"))
4030 : {
4031 1 : yMinMax[0] =
4032 1 : yMinMax[0] * satelliteHeight * 0.000001;
4033 1 : yMinMax[1] =
4034 1 : yMinMax[1] * satelliteHeight * 0.000001;
4035 : }
4036 2 : else if (EQUAL(szUnits, "rad") ||
4037 1 : EQUAL(szUnits, "radian"))
4038 : {
4039 2 : yMinMax[0] = yMinMax[0] * satelliteHeight;
4040 2 : yMinMax[1] = yMinMax[1] * satelliteHeight;
4041 : }
4042 : }
4043 : }
4044 : }
4045 :
4046 213 : adfTempGeoTransform[0] = xMinMax[0];
4047 213 : adfTempGeoTransform[1] = (xMinMax[1] - xMinMax[0]) /
4048 213 : (poDS->nRasterXSize + (node_offset - 1));
4049 213 : adfTempGeoTransform[2] = 0;
4050 213 : if (bSwitchedXY)
4051 : {
4052 2 : adfTempGeoTransform[3] = yMinMax[0];
4053 2 : adfTempGeoTransform[4] = 0;
4054 2 : adfTempGeoTransform[5] =
4055 2 : (yMinMax[1] - yMinMax[0]) /
4056 2 : (poDS->nRasterYSize + (node_offset - 1));
4057 : }
4058 : else
4059 : {
4060 211 : adfTempGeoTransform[3] = yMinMax[1];
4061 211 : adfTempGeoTransform[4] = 0;
4062 211 : adfTempGeoTransform[5] =
4063 211 : (yMinMax[0] - yMinMax[1]) /
4064 211 : (poDS->nRasterYSize + (node_offset - 1));
4065 : }
4066 :
4067 : // Compute the center of the pixel.
4068 213 : if (!node_offset)
4069 : {
4070 : // Otherwise its already the pixel center.
4071 213 : adfTempGeoTransform[0] -= (adfTempGeoTransform[1] / 2);
4072 213 : adfTempGeoTransform[3] -= (adfTempGeoTransform[5] / 2);
4073 : }
4074 : }
4075 :
4076 : const auto AreSRSEqualThroughProj4String =
4077 2 : [](const OGRSpatialReference &oSRS1,
4078 : const OGRSpatialReference &oSRS2)
4079 : {
4080 2 : char *pszProj4Str1 = nullptr;
4081 2 : oSRS1.exportToProj4(&pszProj4Str1);
4082 :
4083 2 : char *pszProj4Str2 = nullptr;
4084 2 : oSRS2.exportToProj4(&pszProj4Str2);
4085 :
4086 : {
4087 2 : char *pszTmp = strstr(pszProj4Str1, "+datum=");
4088 2 : if (pszTmp)
4089 0 : memcpy(pszTmp, "+ellps=", strlen("+ellps="));
4090 : }
4091 :
4092 : {
4093 2 : char *pszTmp = strstr(pszProj4Str2, "+datum=");
4094 2 : if (pszTmp)
4095 2 : memcpy(pszTmp, "+ellps=", strlen("+ellps="));
4096 : }
4097 :
4098 2 : bool bRet = false;
4099 2 : if (pszProj4Str1 && pszProj4Str2 &&
4100 2 : EQUAL(pszProj4Str1, pszProj4Str2))
4101 : {
4102 1 : bRet = true;
4103 : }
4104 :
4105 2 : CPLFree(pszProj4Str1);
4106 2 : CPLFree(pszProj4Str2);
4107 2 : return bRet;
4108 : };
4109 :
4110 220 : if (dfLinearUnitsConvFactor != 1.0)
4111 : {
4112 35 : for (int i = 0; i < 6; ++i)
4113 30 : adfTempGeoTransform[i] *= dfLinearUnitsConvFactor;
4114 :
4115 5 : if (paosRemovedMDItems)
4116 : {
4117 : char szVarNameX[NC_MAX_NAME + 1];
4118 5 : CPL_IGNORE_RET_VAL(
4119 5 : nc_inq_varname(nGroupId, nVarDimXID, szVarNameX));
4120 :
4121 : char szVarNameY[NC_MAX_NAME + 1];
4122 5 : CPL_IGNORE_RET_VAL(
4123 5 : nc_inq_varname(nGroupId, nVarDimYID, szVarNameY));
4124 :
4125 5 : paosRemovedMDItems->push_back(
4126 : CPLSPrintf("%s#units", szVarNameX));
4127 5 : paosRemovedMDItems->push_back(
4128 : CPLSPrintf("%s#units", szVarNameY));
4129 : }
4130 : }
4131 :
4132 : // If there is a global "geospatial_bounds_crs" attribute, check that it
4133 : // is consistent with the SRS, and if so, use it as the SRS
4134 : const char *pszGBCRS =
4135 220 : FetchAttr(nGroupId, NC_GLOBAL, "geospatial_bounds_crs");
4136 220 : if (pszGBCRS && STARTS_WITH(pszGBCRS, "EPSG:"))
4137 : {
4138 4 : OGRSpatialReference oSRSFromGBCRS;
4139 2 : oSRSFromGBCRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
4140 2 : if (oSRSFromGBCRS.SetFromUserInput(
4141 : pszGBCRS,
4142 : OGRSpatialReference::
4143 4 : SET_FROM_USER_INPUT_LIMITATIONS_get()) == OGRERR_NONE &&
4144 2 : AreSRSEqualThroughProj4String(oSRS, oSRSFromGBCRS))
4145 : {
4146 1 : oSRS = std::move(oSRSFromGBCRS);
4147 1 : SetSpatialRefNoUpdate(&oSRS);
4148 : }
4149 : }
4150 :
4151 220 : CPLFree(pdfXCoord);
4152 220 : CPLFree(pdfYCoord);
4153 : } // end if(has dims)
4154 :
4155 : // Process custom GeoTransform GDAL value.
4156 497 : if (!EQUAL(pszGridMappingValue, "") && !bGotCfGT)
4157 : {
4158 : // TODO: Read the GT values and detect for conflict with CF.
4159 : // This could resolve the GT precision loss issue.
4160 :
4161 91 : if (pszGeoTransform != nullptr)
4162 : {
4163 : char **papszGeoTransform =
4164 13 : CSLTokenizeString2(pszGeoTransform, " ", CSLT_HONOURSTRINGS);
4165 13 : if (CSLCount(papszGeoTransform) == 6)
4166 : {
4167 13 : bGotGdalGT = true;
4168 91 : for (int i = 0; i < 6; i++)
4169 78 : adfTempGeoTransform[i] = CPLAtof(papszGeoTransform[i]);
4170 : }
4171 13 : CSLDestroy(papszGeoTransform);
4172 : }
4173 : else
4174 : {
4175 : // Look for corner array values.
4176 : // CPLDebug("GDAL_netCDF",
4177 : // "looking for geotransform corners");
4178 78 : bool bGotNN = false;
4179 78 : double dfNN = FetchCopyParam(pszGridMappingValue,
4180 : "Northernmost_Northing", 0, &bGotNN);
4181 :
4182 78 : bool bGotSN = false;
4183 78 : double dfSN = FetchCopyParam(pszGridMappingValue,
4184 : "Southernmost_Northing", 0, &bGotSN);
4185 :
4186 78 : bool bGotEE = false;
4187 78 : double dfEE = FetchCopyParam(pszGridMappingValue,
4188 : "Easternmost_Easting", 0, &bGotEE);
4189 :
4190 78 : bool bGotWE = false;
4191 78 : double dfWE = FetchCopyParam(pszGridMappingValue,
4192 : "Westernmost_Easting", 0, &bGotWE);
4193 :
4194 : // Only set the GeoTransform if we got all the values.
4195 78 : if (bGotNN && bGotSN && bGotEE && bGotWE)
4196 : {
4197 0 : bGotGdalGT = true;
4198 :
4199 0 : adfTempGeoTransform[0] = dfWE;
4200 0 : adfTempGeoTransform[1] =
4201 0 : (dfEE - dfWE) / (poDS->GetRasterXSize() - 1);
4202 0 : adfTempGeoTransform[2] = 0.0;
4203 0 : adfTempGeoTransform[3] = dfNN;
4204 0 : adfTempGeoTransform[4] = 0.0;
4205 0 : adfTempGeoTransform[5] =
4206 0 : (dfSN - dfNN) / (poDS->GetRasterYSize() - 1);
4207 : // Compute the center of the pixel.
4208 0 : adfTempGeoTransform[0] = dfWE - (adfTempGeoTransform[1] / 2);
4209 0 : adfTempGeoTransform[3] = dfNN - (adfTempGeoTransform[5] / 2);
4210 : }
4211 : } // (pszGeoTransform != NULL)
4212 :
4213 91 : if (bGotGdalSRS && !bGotGdalGT)
4214 72 : CPLDebug("GDAL_netCDF", "Got SRS but no geotransform from GDAL!");
4215 : }
4216 :
4217 497 : if (!pszWKT && !bGotCfSRS)
4218 : {
4219 : // Some netCDF files have a srid attribute (#6613) like
4220 : // urn:ogc:def:crs:EPSG::6931
4221 284 : const char *pszSRID = FetchAttr(pszGridMappingValue, "srid");
4222 284 : if (pszSRID != nullptr)
4223 : {
4224 0 : oSRS.Clear();
4225 0 : if (oSRS.SetFromUserInput(
4226 : pszSRID,
4227 : OGRSpatialReference::
4228 0 : SET_FROM_USER_INPUT_LIMITATIONS_get()) == OGRERR_NONE)
4229 : {
4230 0 : char *pszWKTExport = nullptr;
4231 0 : CPLDebug("GDAL_netCDF", "Got SRS from %s", pszSRID);
4232 0 : oSRS.exportToWkt(&pszWKTExport);
4233 0 : if (returnProjStr != nullptr)
4234 : {
4235 0 : (*returnProjStr) = std::string(pszWKTExport);
4236 : }
4237 : else
4238 : {
4239 0 : m_bAddedProjectionVarsDefs = true;
4240 0 : m_bAddedProjectionVarsData = true;
4241 0 : SetSpatialRefNoUpdate(&oSRS);
4242 : }
4243 0 : CPLFree(pszWKTExport);
4244 : }
4245 : }
4246 : }
4247 :
4248 497 : CPLFree(pszGridMappingValue);
4249 :
4250 497 : if (bReadSRSOnly)
4251 153 : return;
4252 :
4253 : // Determines the SRS to be used by the geolocation array, if any
4254 688 : std::string osGeolocWKT = SRS_WKT_WGS84_LAT_LONG;
4255 344 : if (!m_oSRS.IsEmpty())
4256 : {
4257 256 : OGRSpatialReference oGeogCRS;
4258 128 : oGeogCRS.CopyGeogCSFrom(&m_oSRS);
4259 128 : char *pszWKTTmp = nullptr;
4260 128 : const char *const apszOptions[] = {"FORMAT=WKT2_2019", nullptr};
4261 128 : if (oGeogCRS.exportToWkt(&pszWKTTmp, apszOptions) == OGRERR_NONE)
4262 : {
4263 128 : osGeolocWKT = pszWKTTmp;
4264 : }
4265 128 : CPLFree(pszWKTTmp);
4266 : }
4267 :
4268 : // Process geolocation arrays from CF "coordinates" attribute.
4269 688 : std::string osGeolocXName, osGeolocYName;
4270 344 : if (ProcessCFGeolocation(nGroupId, nVarId, osGeolocWKT, osGeolocXName,
4271 344 : osGeolocYName))
4272 : {
4273 52 : bool bCanCancelGT = true;
4274 52 : if ((nVarDimXID != -1) && (nVarDimYID != -1))
4275 : {
4276 : char szVarNameX[NC_MAX_NAME + 1];
4277 44 : CPL_IGNORE_RET_VAL(
4278 44 : nc_inq_varname(nGroupId, nVarDimXID, szVarNameX));
4279 : char szVarNameY[NC_MAX_NAME + 1];
4280 44 : CPL_IGNORE_RET_VAL(
4281 44 : nc_inq_varname(nGroupId, nVarDimYID, szVarNameY));
4282 44 : bCanCancelGT =
4283 44 : !(osGeolocXName == szVarNameX && osGeolocYName == szVarNameY);
4284 : }
4285 86 : if (bCanCancelGT && !m_oSRS.IsGeographic() && !m_oSRS.IsProjected() &&
4286 34 : !bSwitchedXY)
4287 : {
4288 32 : bGotCfGT = false;
4289 : }
4290 : }
4291 119 : else if (!bGotCfGT && !bReadSRSOnly && (nVarDimXID != -1) &&
4292 414 : (nVarDimYID != -1) && xdim > 0 && ydim > 0 &&
4293 3 : ((!bSwitchedXY &&
4294 3 : NCDFIsVarLongitude(nGroupId, nVarDimXID, nullptr) &&
4295 1 : NCDFIsVarLatitude(nGroupId, nVarDimYID, nullptr)) ||
4296 2 : (bSwitchedXY &&
4297 0 : NCDFIsVarLongitude(nGroupId, nVarDimYID, nullptr) &&
4298 0 : NCDFIsVarLatitude(nGroupId, nVarDimXID, nullptr))))
4299 : {
4300 : // Case of autotest/gdrivers/data/netcdf/GLMELT_4X5.OCN.nc
4301 : // which is indexed by lat, lon variables, but lat has irregular
4302 : // spacing.
4303 1 : const char *pszGeolocXFullName = poDS->papszDimName[poDS->nXDimID];
4304 1 : const char *pszGeolocYFullName = poDS->papszDimName[poDS->nYDimID];
4305 1 : if (bSwitchedXY)
4306 : {
4307 0 : std::swap(pszGeolocXFullName, pszGeolocYFullName);
4308 0 : GDALPamDataset::SetMetadataItem("SWAP_XY", "YES", "GEOLOCATION");
4309 : }
4310 :
4311 1 : CPLDebug("GDAL_netCDF", "using variables %s and %s for GEOLOCATION",
4312 : pszGeolocXFullName, pszGeolocYFullName);
4313 :
4314 1 : GDALPamDataset::SetMetadataItem("SRS", osGeolocWKT.c_str(),
4315 : "GEOLOCATION");
4316 :
4317 2 : CPLString osTMP;
4318 1 : osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(),
4319 1 : pszGeolocXFullName);
4320 :
4321 1 : GDALPamDataset::SetMetadataItem("X_DATASET", osTMP, "GEOLOCATION");
4322 1 : GDALPamDataset::SetMetadataItem("X_BAND", "1", "GEOLOCATION");
4323 1 : osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(),
4324 1 : pszGeolocYFullName);
4325 :
4326 1 : GDALPamDataset::SetMetadataItem("Y_DATASET", osTMP, "GEOLOCATION");
4327 1 : GDALPamDataset::SetMetadataItem("Y_BAND", "1", "GEOLOCATION");
4328 :
4329 1 : GDALPamDataset::SetMetadataItem("PIXEL_OFFSET", "0", "GEOLOCATION");
4330 1 : GDALPamDataset::SetMetadataItem("PIXEL_STEP", "1", "GEOLOCATION");
4331 :
4332 1 : GDALPamDataset::SetMetadataItem("LINE_OFFSET", "0", "GEOLOCATION");
4333 1 : GDALPamDataset::SetMetadataItem("LINE_STEP", "1", "GEOLOCATION");
4334 :
4335 1 : GDALPamDataset::SetMetadataItem("GEOREFERENCING_CONVENTION",
4336 : "PIXEL_CENTER", "GEOLOCATION");
4337 : }
4338 :
4339 : // Set GeoTransform if we got a complete one - after projection has been set
4340 344 : if (bGotCfGT || bGotGdalGT)
4341 : {
4342 195 : m_bAddedProjectionVarsDefs = true;
4343 195 : m_bAddedProjectionVarsData = true;
4344 195 : SetGeoTransformNoUpdate(adfTempGeoTransform);
4345 : }
4346 :
4347 : // Debugging reports.
4348 344 : CPLDebug("GDAL_netCDF",
4349 : "bGotGeogCS=%d bGotCfSRS=%d bGotCfGT=%d bGotCfWktSRS=%d "
4350 : "bGotGdalSRS=%d bGotGdalGT=%d",
4351 : static_cast<int>(bGotGeogCS), static_cast<int>(bGotCfSRS),
4352 : static_cast<int>(bGotCfGT), static_cast<int>(bGotCfWktSRS),
4353 : static_cast<int>(bGotGdalSRS), static_cast<int>(bGotGdalGT));
4354 :
4355 344 : if (!bGotCfGT && !bGotGdalGT)
4356 149 : CPLDebug("GDAL_netCDF", "did not get geotransform from CF nor GDAL!");
4357 :
4358 344 : if (!bGotGeogCS && !bGotCfSRS && !bGotGdalSRS && !bGotCfGT && !bGotCfWktSRS)
4359 149 : CPLDebug("GDAL_netCDF", "did not get projection from CF nor GDAL!");
4360 :
4361 : // wish of 6195
4362 : // we don't have CS/SRS, but we do have GT, and we live in -180,360 -90,90
4363 344 : if (!bGotGeogCS && !bGotCfSRS && !bGotGdalSRS && !bGotCfWktSRS)
4364 : {
4365 216 : if (bGotCfGT || bGotGdalGT)
4366 : {
4367 134 : bool bAssumedLongLat = CPLTestBool(CSLFetchNameValueDef(
4368 67 : papszOpenOptions, "ASSUME_LONGLAT",
4369 : CPLGetConfigOption("GDAL_NETCDF_ASSUME_LONGLAT", "NO")));
4370 :
4371 2 : if (bAssumedLongLat && adfTempGeoTransform[0] >= -180 &&
4372 2 : adfTempGeoTransform[0] < 360 &&
4373 4 : (adfTempGeoTransform[0] +
4374 2 : adfTempGeoTransform[1] * poDS->GetRasterXSize()) <= 360 &&
4375 71 : adfTempGeoTransform[3] <= 90 && adfTempGeoTransform[3] > -90 &&
4376 4 : (adfTempGeoTransform[3] +
4377 2 : adfTempGeoTransform[5] * poDS->GetRasterYSize()) >= -90)
4378 : {
4379 :
4380 2 : poDS->bIsGeographic = true;
4381 2 : char *pszTempProjection = nullptr;
4382 : // seems odd to use 4326 so OGC:CRS84
4383 2 : oSRS.SetFromUserInput("OGC:CRS84");
4384 2 : oSRS.exportToWkt(&pszTempProjection);
4385 2 : if (returnProjStr != nullptr)
4386 : {
4387 0 : (*returnProjStr) = std::string(pszTempProjection);
4388 : }
4389 : else
4390 : {
4391 2 : m_bAddedProjectionVarsDefs = true;
4392 2 : m_bAddedProjectionVarsData = true;
4393 2 : SetSpatialRefNoUpdate(&oSRS);
4394 : }
4395 2 : CPLFree(pszTempProjection);
4396 :
4397 2 : CPLDebug("netCDF",
4398 : "Assumed Longitude Latitude CRS 'OGC:CRS84' because "
4399 : "none otherwise available and geotransform within "
4400 : "suitable bounds. "
4401 : "Set GDAL_NETCDF_ASSUME_LONGLAT=NO as configuration "
4402 : "option or "
4403 : " ASSUME_LONGLAT=NO as open option to bypass this "
4404 : "assumption.");
4405 : }
4406 : }
4407 : }
4408 :
4409 : // Search for Well-known GeogCS if got only CF WKT
4410 : // Disabled for now, as a named datum also include control points
4411 : // (see mailing list and bug#4281
4412 : // For example, WGS84 vs. GDA94 (EPSG:3577) - AEA in netcdf_cf.py
4413 :
4414 : // Disabled for now, but could be set in a config option.
4415 : #if 0
4416 : bool bLookForWellKnownGCS = false; // This could be a Config Option.
4417 :
4418 : if( bLookForWellKnownGCS && bGotCfSRS && !bGotGdalSRS )
4419 : {
4420 : // ET - Could use a more exhaustive method by scanning all EPSG codes in
4421 : // data/gcs.csv as proposed by Even in the gdal-dev mailing list "help
4422 : // for comparing two WKT".
4423 : // This code could be contributed to a new function.
4424 : // OGRSpatialReference * OGRSpatialReference::FindMatchingGeogCS(
4425 : // const OGRSpatialReference *poOther) */
4426 : CPLDebug("GDAL_netCDF", "Searching for Well-known GeogCS");
4427 : const char *pszWKGCSList[] = { "WGS84", "WGS72", "NAD27", "NAD83" };
4428 : char *pszWKGCS = NULL;
4429 : oSRS.exportToPrettyWkt(&pszWKGCS);
4430 : for( size_t i = 0; i < sizeof(pszWKGCSList) / 8; i++ )
4431 : {
4432 : pszWKGCS = CPLStrdup(pszWKGCSList[i]);
4433 : OGRSpatialReference oSRSTmp;
4434 : oSRSTmp.SetWellKnownGeogCS(pszWKGCSList[i]);
4435 : // Set datum to unknown, bug #4281.
4436 : if( oSRSTmp.GetAttrNode("DATUM" ) )
4437 : oSRSTmp.GetAttrNode("DATUM")->GetChild(0)->SetValue("unknown");
4438 : // Could use OGRSpatialReference::StripCTParms(), but let's keep
4439 : // TOWGS84.
4440 : oSRSTmp.GetRoot()->StripNodes("AXIS");
4441 : oSRSTmp.GetRoot()->StripNodes("AUTHORITY");
4442 : oSRSTmp.GetRoot()->StripNodes("EXTENSION");
4443 :
4444 : oSRSTmp.exportToPrettyWkt(&pszWKGCS);
4445 : if( oSRS.IsSameGeogCS(&oSRSTmp) )
4446 : {
4447 : oSRS.SetWellKnownGeogCS(pszWKGCSList[i]);
4448 : oSRS.exportToWkt(&(pszTempProjection));
4449 : SetProjection(pszTempProjection);
4450 : CPLFree(pszTempProjection);
4451 : }
4452 : }
4453 : }
4454 : #endif
4455 : }
4456 :
4457 110 : void netCDFDataset::SetProjectionFromVar(int nGroupId, int nVarId,
4458 : bool bReadSRSOnly)
4459 : {
4460 110 : SetProjectionFromVar(nGroupId, nVarId, bReadSRSOnly, nullptr, nullptr,
4461 : nullptr, nullptr);
4462 110 : }
4463 :
4464 281 : bool netCDFDataset::ProcessNASAL2OceanGeoLocation(int nGroupId, int nVarId)
4465 : {
4466 : // Cf https://oceancolor.gsfc.nasa.gov/docs/format/l2nc/
4467 : // and https://github.com/OSGeo/gdal/issues/7605
4468 :
4469 : // Check for a structure like:
4470 : /* netcdf SNPP_VIIRS.20230406T024200.L2.OC.NRT {
4471 : dimensions:
4472 : number_of_lines = 3248 ;
4473 : pixels_per_line = 3200 ;
4474 : [...]
4475 : pixel_control_points = 3200 ;
4476 : [...]
4477 : group: geophysical_data {
4478 : variables:
4479 : short aot_862(number_of_lines, pixels_per_line) ; <-- nVarId
4480 : [...]
4481 : }
4482 : group: navigation_data {
4483 : variables:
4484 : float longitude(number_of_lines, pixel_control_points) ;
4485 : [...]
4486 : float latitude(number_of_lines, pixel_control_points) ;
4487 : [...]
4488 : }
4489 : }
4490 : */
4491 : // Note that the longitude and latitude arrays are not indexed by the
4492 : // same dimensions. Handle only the case where
4493 : // pixel_control_points == pixels_per_line
4494 : // If there was a subsampling of the geolocation arrays, we'd need to
4495 : // add more logic.
4496 :
4497 562 : std::string osGroupName;
4498 281 : osGroupName.resize(NC_MAX_NAME);
4499 281 : NCDF_ERR(nc_inq_grpname(nGroupId, &osGroupName[0]));
4500 281 : osGroupName.resize(strlen(osGroupName.data()));
4501 281 : if (osGroupName != "geophysical_data")
4502 280 : return false;
4503 :
4504 1 : int nVarDims = 0;
4505 1 : NCDF_ERR(nc_inq_varndims(nGroupId, nVarId, &nVarDims));
4506 1 : if (nVarDims != 2)
4507 0 : return false;
4508 :
4509 1 : int nNavigationDataGrpId = 0;
4510 1 : if (nc_inq_grp_ncid(cdfid, "navigation_data", &nNavigationDataGrpId) !=
4511 : NC_NOERR)
4512 0 : return false;
4513 :
4514 : std::array<int, 2> anVarDimIds;
4515 1 : NCDF_ERR(nc_inq_vardimid(nGroupId, nVarId, anVarDimIds.data()));
4516 :
4517 1 : int nLongitudeId = 0;
4518 1 : int nLatitudeId = 0;
4519 1 : if (nc_inq_varid(nNavigationDataGrpId, "longitude", &nLongitudeId) !=
4520 2 : NC_NOERR ||
4521 1 : nc_inq_varid(nNavigationDataGrpId, "latitude", &nLatitudeId) !=
4522 : NC_NOERR)
4523 : {
4524 0 : return false;
4525 : }
4526 :
4527 1 : int nDimsLongitude = 0;
4528 1 : NCDF_ERR(
4529 : nc_inq_varndims(nNavigationDataGrpId, nLongitudeId, &nDimsLongitude));
4530 1 : int nDimsLatitude = 0;
4531 1 : NCDF_ERR(
4532 : nc_inq_varndims(nNavigationDataGrpId, nLatitudeId, &nDimsLatitude));
4533 1 : if (!(nDimsLongitude == 2 && nDimsLatitude == 2))
4534 : {
4535 0 : return false;
4536 : }
4537 :
4538 : std::array<int, 2> anDimLongitudeIds;
4539 1 : NCDF_ERR(nc_inq_vardimid(nNavigationDataGrpId, nLongitudeId,
4540 : anDimLongitudeIds.data()));
4541 : std::array<int, 2> anDimLatitudeIds;
4542 1 : NCDF_ERR(nc_inq_vardimid(nNavigationDataGrpId, nLatitudeId,
4543 : anDimLatitudeIds.data()));
4544 1 : if (anDimLongitudeIds != anDimLatitudeIds)
4545 : {
4546 0 : return false;
4547 : }
4548 :
4549 : std::array<size_t, 2> anSizeVarDimIds;
4550 : std::array<size_t, 2> anSizeLongLatIds;
4551 2 : if (!(nc_inq_dimlen(cdfid, anVarDimIds[0], &anSizeVarDimIds[0]) ==
4552 1 : NC_NOERR &&
4553 1 : nc_inq_dimlen(cdfid, anVarDimIds[1], &anSizeVarDimIds[1]) ==
4554 1 : NC_NOERR &&
4555 1 : nc_inq_dimlen(cdfid, anDimLongitudeIds[0], &anSizeLongLatIds[0]) ==
4556 1 : NC_NOERR &&
4557 1 : nc_inq_dimlen(cdfid, anDimLongitudeIds[1], &anSizeLongLatIds[1]) ==
4558 : NC_NOERR &&
4559 1 : anSizeVarDimIds == anSizeLongLatIds))
4560 : {
4561 0 : return false;
4562 : }
4563 :
4564 1 : const char *pszGeolocXFullName = "/navigation_data/longitude";
4565 1 : const char *pszGeolocYFullName = "/navigation_data/latitude";
4566 :
4567 1 : if (bSwitchedXY)
4568 : {
4569 0 : std::swap(pszGeolocXFullName, pszGeolocYFullName);
4570 0 : GDALPamDataset::SetMetadataItem("SWAP_XY", "YES", "GEOLOCATION");
4571 : }
4572 :
4573 1 : CPLDebug("GDAL_netCDF", "using variables %s and %s for GEOLOCATION",
4574 : pszGeolocXFullName, pszGeolocYFullName);
4575 :
4576 1 : GDALPamDataset::SetMetadataItem("SRS", SRS_WKT_WGS84_LAT_LONG,
4577 : "GEOLOCATION");
4578 :
4579 1 : CPLString osTMP;
4580 1 : osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(), pszGeolocXFullName);
4581 :
4582 1 : GDALPamDataset::SetMetadataItem("X_DATASET", osTMP, "GEOLOCATION");
4583 1 : GDALPamDataset::SetMetadataItem("X_BAND", "1", "GEOLOCATION");
4584 1 : osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(), pszGeolocYFullName);
4585 :
4586 1 : GDALPamDataset::SetMetadataItem("Y_DATASET", osTMP, "GEOLOCATION");
4587 1 : GDALPamDataset::SetMetadataItem("Y_BAND", "1", "GEOLOCATION");
4588 :
4589 1 : GDALPamDataset::SetMetadataItem("PIXEL_OFFSET", "0", "GEOLOCATION");
4590 1 : GDALPamDataset::SetMetadataItem("PIXEL_STEP", "1", "GEOLOCATION");
4591 :
4592 1 : GDALPamDataset::SetMetadataItem("LINE_OFFSET", "0", "GEOLOCATION");
4593 1 : GDALPamDataset::SetMetadataItem("LINE_STEP", "1", "GEOLOCATION");
4594 :
4595 1 : GDALPamDataset::SetMetadataItem("GEOREFERENCING_CONVENTION", "PIXEL_CENTER",
4596 : "GEOLOCATION");
4597 1 : return true;
4598 : }
4599 :
4600 280 : bool netCDFDataset::ProcessNASAEMITGeoLocation(int nGroupId, int nVarId)
4601 : {
4602 : // Cf https://earth.jpl.nasa.gov/emit/data/data-portal/coverage-and-forecasts/
4603 :
4604 : // Check for a structure like:
4605 : /* netcdf EMIT_L2A_RFL_001_20220903T163129_2224611_012 {
4606 : dimensions:
4607 : downtrack = 1280 ;
4608 : crosstrack = 1242 ;
4609 : bands = 285 ;
4610 : [...]
4611 :
4612 : variables:
4613 : float reflectance(downtrack, crosstrack, bands) ;
4614 :
4615 : group: location {
4616 : variables:
4617 : double lon(downtrack, crosstrack) ;
4618 : lon:_FillValue = -9999. ;
4619 : lon:long_name = "Longitude (WGS-84)" ;
4620 : lon:units = "degrees east" ;
4621 : double lat(downtrack, crosstrack) ;
4622 : lat:_FillValue = -9999. ;
4623 : lat:long_name = "Latitude (WGS-84)" ;
4624 : lat:units = "degrees north" ;
4625 : } // group location
4626 :
4627 : }
4628 : or
4629 : netcdf EMIT_L2B_MIN_001_20231024T055538_2329704_040 {
4630 : dimensions:
4631 : downtrack = 1664 ;
4632 : crosstrack = 1242 ;
4633 : [...]
4634 : variables:
4635 : float group_1_band_depth(downtrack, crosstrack) ;
4636 : group_1_band_depth:_FillValue = -9999.f ;
4637 : group_1_band_depth:long_name = "Group 1 Band Depth" ;
4638 : group_1_band_depth:units = "unitless" ;
4639 : [...]
4640 : group: location {
4641 : variables:
4642 : double lon(downtrack, crosstrack) ;
4643 : lon:_FillValue = -9999. ;
4644 : lon:long_name = "Longitude (WGS-84)" ;
4645 : lon:units = "degrees east" ;
4646 : double lat(downtrack, crosstrack) ;
4647 : lat:_FillValue = -9999. ;
4648 : lat:long_name = "Latitude (WGS-84)" ;
4649 : lat:units = "degrees north" ;
4650 : }
4651 : */
4652 :
4653 280 : int nVarDims = 0;
4654 280 : NCDF_ERR(nc_inq_varndims(nGroupId, nVarId, &nVarDims));
4655 280 : if (nVarDims != 2 && nVarDims != 3)
4656 14 : return false;
4657 :
4658 266 : int nLocationGrpId = 0;
4659 266 : if (nc_inq_grp_ncid(cdfid, "location", &nLocationGrpId) != NC_NOERR)
4660 56 : return false;
4661 :
4662 : std::array<int, 3> anVarDimIds;
4663 210 : NCDF_ERR(nc_inq_vardimid(nGroupId, nVarId, anVarDimIds.data()));
4664 210 : if (nYDimID != anVarDimIds[0] || nXDimID != anVarDimIds[1])
4665 21 : return false;
4666 :
4667 189 : int nLongitudeId = 0;
4668 189 : int nLatitudeId = 0;
4669 226 : if (nc_inq_varid(nLocationGrpId, "lon", &nLongitudeId) != NC_NOERR ||
4670 37 : nc_inq_varid(nLocationGrpId, "lat", &nLatitudeId) != NC_NOERR)
4671 : {
4672 152 : return false;
4673 : }
4674 :
4675 37 : int nDimsLongitude = 0;
4676 37 : NCDF_ERR(nc_inq_varndims(nLocationGrpId, nLongitudeId, &nDimsLongitude));
4677 37 : int nDimsLatitude = 0;
4678 37 : NCDF_ERR(nc_inq_varndims(nLocationGrpId, nLatitudeId, &nDimsLatitude));
4679 37 : if (!(nDimsLongitude == 2 && nDimsLatitude == 2))
4680 : {
4681 33 : return false;
4682 : }
4683 :
4684 : std::array<int, 2> anDimLongitudeIds;
4685 4 : NCDF_ERR(nc_inq_vardimid(nLocationGrpId, nLongitudeId,
4686 : anDimLongitudeIds.data()));
4687 : std::array<int, 2> anDimLatitudeIds;
4688 4 : NCDF_ERR(
4689 : nc_inq_vardimid(nLocationGrpId, nLatitudeId, anDimLatitudeIds.data()));
4690 4 : if (anDimLongitudeIds != anDimLatitudeIds)
4691 : {
4692 0 : return false;
4693 : }
4694 :
4695 8 : if (anDimLongitudeIds[0] != anVarDimIds[0] ||
4696 4 : anDimLongitudeIds[1] != anVarDimIds[1])
4697 : {
4698 0 : return false;
4699 : }
4700 :
4701 4 : const char *pszGeolocXFullName = "/location/lon";
4702 4 : const char *pszGeolocYFullName = "/location/lat";
4703 :
4704 4 : CPLDebug("GDAL_netCDF", "using variables %s and %s for GEOLOCATION",
4705 : pszGeolocXFullName, pszGeolocYFullName);
4706 :
4707 4 : GDALPamDataset::SetMetadataItem("SRS", SRS_WKT_WGS84_LAT_LONG,
4708 : "GEOLOCATION");
4709 :
4710 4 : CPLString osTMP;
4711 4 : osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(), pszGeolocXFullName);
4712 :
4713 4 : GDALPamDataset::SetMetadataItem("X_DATASET", osTMP, "GEOLOCATION");
4714 4 : GDALPamDataset::SetMetadataItem("X_BAND", "1", "GEOLOCATION");
4715 4 : osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(), pszGeolocYFullName);
4716 :
4717 4 : GDALPamDataset::SetMetadataItem("Y_DATASET", osTMP, "GEOLOCATION");
4718 4 : GDALPamDataset::SetMetadataItem("Y_BAND", "1", "GEOLOCATION");
4719 :
4720 4 : GDALPamDataset::SetMetadataItem("PIXEL_OFFSET", "0", "GEOLOCATION");
4721 4 : GDALPamDataset::SetMetadataItem("PIXEL_STEP", "1", "GEOLOCATION");
4722 :
4723 4 : GDALPamDataset::SetMetadataItem("LINE_OFFSET", "0", "GEOLOCATION");
4724 4 : GDALPamDataset::SetMetadataItem("LINE_STEP", "1", "GEOLOCATION");
4725 :
4726 4 : GDALPamDataset::SetMetadataItem("GEOREFERENCING_CONVENTION", "PIXEL_CENTER",
4727 : "GEOLOCATION");
4728 4 : return true;
4729 : }
4730 :
4731 344 : int netCDFDataset::ProcessCFGeolocation(int nGroupId, int nVarId,
4732 : const std::string &osGeolocWKT,
4733 : std::string &osGeolocXNameOut,
4734 : std::string &osGeolocYNameOut)
4735 : {
4736 344 : bool bAddGeoloc = false;
4737 344 : char *pszCoordinates = nullptr;
4738 :
4739 : // If there is no explicit "coordinates" attribute, check if there are
4740 : // "lon" and "lat" 2D variables whose dimensions are the last
4741 : // 2 ones of the variable of interest.
4742 344 : if (NCDFGetAttr(nGroupId, nVarId, "coordinates", &pszCoordinates) !=
4743 : CE_None)
4744 : {
4745 298 : CPLFree(pszCoordinates);
4746 298 : pszCoordinates = nullptr;
4747 :
4748 298 : int nVarDims = 0;
4749 298 : NCDF_ERR(nc_inq_varndims(nGroupId, nVarId, &nVarDims));
4750 298 : if (nVarDims >= 2)
4751 : {
4752 596 : std::vector<int> anVarDimIds(nVarDims);
4753 298 : NCDF_ERR(nc_inq_vardimid(nGroupId, nVarId, anVarDimIds.data()));
4754 :
4755 298 : int nLongitudeId = 0;
4756 298 : int nLatitudeId = 0;
4757 365 : if (nc_inq_varid(nGroupId, "lon", &nLongitudeId) == NC_NOERR &&
4758 67 : nc_inq_varid(nGroupId, "lat", &nLatitudeId) == NC_NOERR)
4759 : {
4760 67 : int nDimsLongitude = 0;
4761 67 : NCDF_ERR(
4762 : nc_inq_varndims(nGroupId, nLongitudeId, &nDimsLongitude));
4763 67 : int nDimsLatitude = 0;
4764 67 : NCDF_ERR(
4765 : nc_inq_varndims(nGroupId, nLatitudeId, &nDimsLatitude));
4766 67 : if (nDimsLongitude == 2 && nDimsLatitude == 2)
4767 : {
4768 34 : std::vector<int> anDimLongitudeIds(2);
4769 17 : NCDF_ERR(nc_inq_vardimid(nGroupId, nLongitudeId,
4770 : anDimLongitudeIds.data()));
4771 34 : std::vector<int> anDimLatitudeIds(2);
4772 17 : NCDF_ERR(nc_inq_vardimid(nGroupId, nLatitudeId,
4773 : anDimLatitudeIds.data()));
4774 17 : if (anDimLongitudeIds == anDimLatitudeIds &&
4775 34 : anVarDimIds[anVarDimIds.size() - 2] ==
4776 51 : anDimLongitudeIds[0] &&
4777 34 : anVarDimIds[anVarDimIds.size() - 1] ==
4778 17 : anDimLongitudeIds[1])
4779 : {
4780 17 : pszCoordinates = CPLStrdup("lon lat");
4781 : }
4782 : }
4783 : }
4784 : }
4785 : }
4786 :
4787 344 : if (pszCoordinates)
4788 : {
4789 : // Get X and Y geolocation names from coordinates attribute.
4790 : const CPLStringList aosCoordinates(
4791 126 : NCDFTokenizeCoordinatesAttribute(pszCoordinates));
4792 63 : if (aosCoordinates.size() >= 2)
4793 : {
4794 : char szGeolocXName[NC_MAX_NAME + 1];
4795 : char szGeolocYName[NC_MAX_NAME + 1];
4796 60 : szGeolocXName[0] = '\0';
4797 60 : szGeolocYName[0] = '\0';
4798 :
4799 : // Test that each variable is longitude/latitude.
4800 193 : for (int i = 0; i < aosCoordinates.size(); i++)
4801 : {
4802 133 : if (NCDFIsVarLongitude(nGroupId, -1, aosCoordinates[i]))
4803 : {
4804 49 : int nOtherGroupId = -1;
4805 49 : int nOtherVarId = -1;
4806 : // Check that the variable actually exists
4807 : // Needed on Sentinel-3 products
4808 49 : if (NCDFResolveVar(nGroupId, aosCoordinates[i],
4809 49 : &nOtherGroupId, &nOtherVarId) == CE_None)
4810 : {
4811 47 : snprintf(szGeolocXName, sizeof(szGeolocXName), "%s",
4812 : aosCoordinates[i]);
4813 : }
4814 : }
4815 84 : else if (NCDFIsVarLatitude(nGroupId, -1, aosCoordinates[i]))
4816 : {
4817 49 : int nOtherGroupId = -1;
4818 49 : int nOtherVarId = -1;
4819 : // Check that the variable actually exists
4820 : // Needed on Sentinel-3 products
4821 49 : if (NCDFResolveVar(nGroupId, aosCoordinates[i],
4822 49 : &nOtherGroupId, &nOtherVarId) == CE_None)
4823 : {
4824 47 : snprintf(szGeolocYName, sizeof(szGeolocYName), "%s",
4825 : aosCoordinates[i]);
4826 : }
4827 : }
4828 : }
4829 : // Add GEOLOCATION metadata.
4830 60 : if (!EQUAL(szGeolocXName, "") && !EQUAL(szGeolocYName, ""))
4831 : {
4832 47 : osGeolocXNameOut = szGeolocXName;
4833 47 : osGeolocYNameOut = szGeolocYName;
4834 :
4835 47 : char *pszGeolocXFullName = nullptr;
4836 47 : char *pszGeolocYFullName = nullptr;
4837 47 : if (NCDFResolveVarFullName(nGroupId, szGeolocXName,
4838 94 : &pszGeolocXFullName) == CE_None &&
4839 47 : NCDFResolveVarFullName(nGroupId, szGeolocYName,
4840 : &pszGeolocYFullName) == CE_None)
4841 : {
4842 47 : if (bSwitchedXY)
4843 : {
4844 2 : std::swap(pszGeolocXFullName, pszGeolocYFullName);
4845 2 : GDALPamDataset::SetMetadataItem("SWAP_XY", "YES",
4846 : "GEOLOCATION");
4847 : }
4848 :
4849 47 : bAddGeoloc = true;
4850 47 : CPLDebug("GDAL_netCDF",
4851 : "using variables %s and %s for GEOLOCATION",
4852 : pszGeolocXFullName, pszGeolocYFullName);
4853 :
4854 47 : GDALPamDataset::SetMetadataItem("SRS", osGeolocWKT.c_str(),
4855 : "GEOLOCATION");
4856 :
4857 94 : CPLString osTMP;
4858 47 : osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(),
4859 47 : pszGeolocXFullName);
4860 :
4861 47 : GDALPamDataset::SetMetadataItem("X_DATASET", osTMP,
4862 : "GEOLOCATION");
4863 47 : GDALPamDataset::SetMetadataItem("X_BAND", "1",
4864 : "GEOLOCATION");
4865 47 : osTMP.Printf("NETCDF:\"%s\":%s", osFilename.c_str(),
4866 47 : pszGeolocYFullName);
4867 :
4868 47 : GDALPamDataset::SetMetadataItem("Y_DATASET", osTMP,
4869 : "GEOLOCATION");
4870 47 : GDALPamDataset::SetMetadataItem("Y_BAND", "1",
4871 : "GEOLOCATION");
4872 :
4873 47 : GDALPamDataset::SetMetadataItem("PIXEL_OFFSET", "0",
4874 : "GEOLOCATION");
4875 47 : GDALPamDataset::SetMetadataItem("PIXEL_STEP", "1",
4876 : "GEOLOCATION");
4877 :
4878 47 : GDALPamDataset::SetMetadataItem("LINE_OFFSET", "0",
4879 : "GEOLOCATION");
4880 47 : GDALPamDataset::SetMetadataItem("LINE_STEP", "1",
4881 : "GEOLOCATION");
4882 :
4883 47 : GDALPamDataset::SetMetadataItem("GEOREFERENCING_CONVENTION",
4884 : "PIXEL_CENTER",
4885 : "GEOLOCATION");
4886 : }
4887 : else
4888 : {
4889 0 : CPLDebug("GDAL_netCDF",
4890 : "cannot resolve location of "
4891 : "lat/lon variables specified by the coordinates "
4892 : "attribute [%s]",
4893 : pszCoordinates);
4894 : }
4895 47 : CPLFree(pszGeolocXFullName);
4896 47 : CPLFree(pszGeolocYFullName);
4897 : }
4898 : else
4899 : {
4900 13 : CPLDebug("GDAL_netCDF",
4901 : "coordinates attribute [%s] is unsupported",
4902 : pszCoordinates);
4903 : }
4904 : }
4905 : else
4906 : {
4907 3 : CPLDebug("GDAL_netCDF",
4908 : "coordinates attribute [%s] with %d element(s) is "
4909 : "unsupported",
4910 : pszCoordinates, aosCoordinates.size());
4911 : }
4912 : }
4913 :
4914 : else
4915 : {
4916 281 : bAddGeoloc = ProcessNASAL2OceanGeoLocation(nGroupId, nVarId);
4917 :
4918 281 : if (!bAddGeoloc)
4919 280 : bAddGeoloc = ProcessNASAEMITGeoLocation(nGroupId, nVarId);
4920 : }
4921 :
4922 344 : CPLFree(pszCoordinates);
4923 :
4924 344 : return bAddGeoloc;
4925 : }
4926 :
4927 8 : CPLErr netCDFDataset::Set1DGeolocation(int nGroupId, int nVarId,
4928 : const char *szDimName)
4929 : {
4930 : // Get values.
4931 8 : char *pszVarValues = nullptr;
4932 8 : CPLErr eErr = NCDFGet1DVar(nGroupId, nVarId, &pszVarValues);
4933 8 : if (eErr != CE_None)
4934 0 : return eErr;
4935 :
4936 : // Write metadata.
4937 8 : char szTemp[NC_MAX_NAME + 1 + 32] = {};
4938 8 : snprintf(szTemp, sizeof(szTemp), "%s_VALUES", szDimName);
4939 8 : GDALPamDataset::SetMetadataItem(szTemp, pszVarValues, "GEOLOCATION2");
4940 :
4941 8 : CPLFree(pszVarValues);
4942 :
4943 8 : return CE_None;
4944 : }
4945 :
4946 0 : double *netCDFDataset::Get1DGeolocation(CPL_UNUSED const char *szDimName,
4947 : int &nVarLen)
4948 : {
4949 0 : nVarLen = 0;
4950 :
4951 : // Get Y_VALUES as tokens.
4952 : char **papszValues =
4953 0 : NCDFTokenizeArray(GetMetadataItem("Y_VALUES", "GEOLOCATION2"));
4954 0 : if (papszValues == nullptr)
4955 0 : return nullptr;
4956 :
4957 : // Initialize and fill array.
4958 0 : nVarLen = CSLCount(papszValues);
4959 : double *pdfVarValues =
4960 0 : static_cast<double *>(CPLCalloc(nVarLen, sizeof(double)));
4961 :
4962 0 : for (int i = 0, j = 0; i < nVarLen; i++)
4963 : {
4964 0 : if (!bBottomUp)
4965 0 : j = nVarLen - 1 - i;
4966 : else
4967 0 : j = i; // Invert latitude values.
4968 0 : char *pszTemp = nullptr;
4969 0 : pdfVarValues[j] = CPLStrtod(papszValues[i], &pszTemp);
4970 : }
4971 0 : CSLDestroy(papszValues);
4972 :
4973 0 : return pdfVarValues;
4974 : }
4975 :
4976 : /************************************************************************/
4977 : /* SetSpatialRefNoUpdate() */
4978 : /************************************************************************/
4979 :
4980 247 : void netCDFDataset::SetSpatialRefNoUpdate(const OGRSpatialReference *poSRS)
4981 : {
4982 247 : m_oSRS.Clear();
4983 247 : if (poSRS)
4984 240 : m_oSRS = *poSRS;
4985 247 : m_bHasProjection = true;
4986 247 : }
4987 :
4988 : /************************************************************************/
4989 : /* SetSpatialRef() */
4990 : /************************************************************************/
4991 :
4992 74 : CPLErr netCDFDataset::SetSpatialRef(const OGRSpatialReference *poSRS)
4993 : {
4994 148 : CPLMutexHolderD(&hNCMutex);
4995 :
4996 74 : if (GetAccess() != GA_Update || m_bHasProjection)
4997 : {
4998 0 : CPLError(CE_Failure, CPLE_AppDefined,
4999 : "netCDFDataset::_SetProjection() should only be called once "
5000 : "in update mode!");
5001 0 : return CE_Failure;
5002 : }
5003 :
5004 74 : if (m_bHasGeoTransform)
5005 : {
5006 32 : SetSpatialRefNoUpdate(poSRS);
5007 :
5008 : // For NC4/NC4C, writing both projection variables and data,
5009 : // followed by redefining nodata value, cancels the projection
5010 : // info from the Band variable, so for now only write the
5011 : // variable definitions, and write data at the end.
5012 : // See https://trac.osgeo.org/gdal/ticket/7245
5013 32 : return AddProjectionVars(true, nullptr, nullptr);
5014 : }
5015 :
5016 42 : SetSpatialRefNoUpdate(poSRS);
5017 :
5018 42 : return CE_None;
5019 : }
5020 :
5021 : /************************************************************************/
5022 : /* SetGeoTransformNoUpdate() */
5023 : /************************************************************************/
5024 :
5025 270 : void netCDFDataset::SetGeoTransformNoUpdate(double *padfTransform)
5026 : {
5027 270 : memcpy(m_adfGeoTransform, padfTransform, sizeof(double) * 6);
5028 270 : m_bHasGeoTransform = true;
5029 270 : }
5030 :
5031 : /************************************************************************/
5032 : /* SetGeoTransform() */
5033 : /************************************************************************/
5034 :
5035 75 : CPLErr netCDFDataset::SetGeoTransform(double *padfTransform)
5036 : {
5037 150 : CPLMutexHolderD(&hNCMutex);
5038 :
5039 75 : if (GetAccess() != GA_Update || m_bHasGeoTransform)
5040 : {
5041 0 : CPLError(CE_Failure, CPLE_AppDefined,
5042 : "netCDFDataset::SetGeoTransform() should only be called once "
5043 : "in update mode!");
5044 0 : return CE_Failure;
5045 : }
5046 :
5047 75 : CPLDebug("GDAL_netCDF", "SetGeoTransform(%f,%f,%f,%f,%f,%f)",
5048 75 : padfTransform[0], padfTransform[1], padfTransform[2],
5049 75 : padfTransform[3], padfTransform[4], padfTransform[5]);
5050 :
5051 75 : if (m_bHasProjection)
5052 : {
5053 3 : SetGeoTransformNoUpdate(padfTransform);
5054 :
5055 : // For NC4/NC4C, writing both projection variables and data,
5056 : // followed by redefining nodata value, cancels the projection
5057 : // info from the Band variable, so for now only write the
5058 : // variable definitions, and write data at the end.
5059 : // See https://trac.osgeo.org/gdal/ticket/7245
5060 3 : return AddProjectionVars(true, nullptr, nullptr);
5061 : }
5062 :
5063 72 : SetGeoTransformNoUpdate(padfTransform);
5064 72 : return CE_None;
5065 : }
5066 :
5067 : /************************************************************************/
5068 : /* NCDFWriteSRSVariable() */
5069 : /************************************************************************/
5070 :
5071 126 : int NCDFWriteSRSVariable(int cdfid, const OGRSpatialReference *poSRS,
5072 : char **ppszCFProjection, bool bWriteGDALTags,
5073 : const std::string &srsVarName)
5074 : {
5075 126 : char *pszCFProjection = nullptr;
5076 126 : char **papszKeyValues = nullptr;
5077 126 : poSRS->exportToCF1(&pszCFProjection, &papszKeyValues, nullptr, nullptr);
5078 :
5079 126 : if (bWriteGDALTags)
5080 : {
5081 125 : const char *pszWKT = CSLFetchNameValue(papszKeyValues, NCDF_CRS_WKT);
5082 125 : if (pszWKT)
5083 : {
5084 : // SPATIAL_REF is deprecated. Will be removed in GDAL 4.
5085 125 : papszKeyValues =
5086 125 : CSLSetNameValue(papszKeyValues, NCDF_SPATIAL_REF, pszWKT);
5087 : }
5088 : }
5089 :
5090 126 : const int nValues = CSLCount(papszKeyValues);
5091 :
5092 : int NCDFVarID;
5093 252 : std::string varNameRadix(pszCFProjection);
5094 126 : int nCounter = 2;
5095 : while (true)
5096 : {
5097 128 : NCDFVarID = -1;
5098 128 : nc_inq_varid(cdfid, pszCFProjection, &NCDFVarID);
5099 128 : if (NCDFVarID < 0)
5100 123 : break;
5101 :
5102 5 : int nbAttr = 0;
5103 5 : NCDF_ERR(nc_inq_varnatts(cdfid, NCDFVarID, &nbAttr));
5104 5 : bool bSame = nbAttr == nValues;
5105 41 : for (int i = 0; bSame && (i < nbAttr); i++)
5106 : {
5107 : char szAttrName[NC_MAX_NAME + 1];
5108 38 : szAttrName[0] = 0;
5109 38 : NCDF_ERR(nc_inq_attname(cdfid, NCDFVarID, i, szAttrName));
5110 :
5111 : const char *pszValue =
5112 38 : CSLFetchNameValue(papszKeyValues, szAttrName);
5113 38 : if (!pszValue)
5114 : {
5115 0 : bSame = false;
5116 2 : break;
5117 : }
5118 :
5119 38 : nc_type atttype = NC_NAT;
5120 38 : size_t attlen = 0;
5121 38 : NCDF_ERR(
5122 : nc_inq_att(cdfid, NCDFVarID, szAttrName, &atttype, &attlen));
5123 38 : if (atttype != NC_CHAR && atttype != NC_DOUBLE)
5124 : {
5125 0 : bSame = false;
5126 0 : break;
5127 : }
5128 38 : if (atttype == NC_CHAR)
5129 : {
5130 15 : if (CPLGetValueType(pszValue) != CPL_VALUE_STRING)
5131 : {
5132 0 : bSame = false;
5133 0 : break;
5134 : }
5135 15 : std::string val;
5136 15 : val.resize(attlen);
5137 15 : nc_get_att_text(cdfid, NCDFVarID, szAttrName, &val[0]);
5138 15 : if (val != pszValue)
5139 : {
5140 0 : bSame = false;
5141 0 : break;
5142 : }
5143 : }
5144 : else
5145 : {
5146 : const CPLStringList aosTokens(
5147 23 : CSLTokenizeString2(pszValue, ",", 0));
5148 23 : if (static_cast<size_t>(aosTokens.size()) != attlen)
5149 : {
5150 0 : bSame = false;
5151 0 : break;
5152 : }
5153 : double vals[2];
5154 23 : nc_get_att_double(cdfid, NCDFVarID, szAttrName, vals);
5155 44 : if (vals[0] != CPLAtof(aosTokens[0]) ||
5156 21 : (attlen == 2 && vals[1] != CPLAtof(aosTokens[1])))
5157 : {
5158 2 : bSame = false;
5159 2 : break;
5160 : }
5161 : }
5162 : }
5163 5 : if (bSame)
5164 : {
5165 3 : *ppszCFProjection = pszCFProjection;
5166 3 : CSLDestroy(papszKeyValues);
5167 3 : return NCDFVarID;
5168 : }
5169 2 : CPLFree(pszCFProjection);
5170 2 : pszCFProjection =
5171 2 : CPLStrdup(CPLSPrintf("%s_%d", varNameRadix.c_str(), nCounter));
5172 2 : nCounter++;
5173 2 : }
5174 :
5175 123 : *ppszCFProjection = pszCFProjection;
5176 :
5177 : const char *pszVarName;
5178 :
5179 123 : if (srsVarName != "")
5180 : {
5181 38 : pszVarName = srsVarName.c_str();
5182 : }
5183 : else
5184 : {
5185 85 : pszVarName = pszCFProjection;
5186 : }
5187 :
5188 123 : int status = nc_def_var(cdfid, pszVarName, NC_CHAR, 0, nullptr, &NCDFVarID);
5189 123 : NCDF_ERR(status);
5190 1178 : for (int i = 0; i < nValues; ++i)
5191 : {
5192 1055 : char *pszKey = nullptr;
5193 1055 : const char *pszValue = CPLParseNameValue(papszKeyValues[i], &pszKey);
5194 1055 : if (pszKey && pszValue)
5195 : {
5196 2110 : const CPLStringList aosTokens(CSLTokenizeString2(pszValue, ",", 0));
5197 1055 : double adfValues[2] = {0, 0};
5198 1055 : const int nDoubleCount = std::min(2, aosTokens.size());
5199 1055 : if (!(aosTokens.size() == 2 &&
5200 2109 : CPLGetValueType(aosTokens[0]) != CPL_VALUE_STRING) &&
5201 1054 : CPLGetValueType(pszValue) == CPL_VALUE_STRING)
5202 : {
5203 491 : status = nc_put_att_text(cdfid, NCDFVarID, pszKey,
5204 : strlen(pszValue), pszValue);
5205 : }
5206 : else
5207 : {
5208 1129 : for (int j = 0; j < nDoubleCount; ++j)
5209 565 : adfValues[j] = CPLAtof(aosTokens[j]);
5210 564 : status = nc_put_att_double(cdfid, NCDFVarID, pszKey, NC_DOUBLE,
5211 : nDoubleCount, adfValues);
5212 : }
5213 1055 : NCDF_ERR(status);
5214 : }
5215 1055 : CPLFree(pszKey);
5216 : }
5217 :
5218 123 : CSLDestroy(papszKeyValues);
5219 123 : return NCDFVarID;
5220 : }
5221 :
5222 : /************************************************************************/
5223 : /* NCDFWriteLonLatVarsAttributes() */
5224 : /************************************************************************/
5225 :
5226 100 : void NCDFWriteLonLatVarsAttributes(nccfdriver::netCDFVID &vcdf, int nVarLonID,
5227 : int nVarLatID)
5228 : {
5229 :
5230 : try
5231 : {
5232 100 : vcdf.nc_put_vatt_text(nVarLatID, CF_STD_NAME, CF_LATITUDE_STD_NAME);
5233 100 : vcdf.nc_put_vatt_text(nVarLatID, CF_LNG_NAME, CF_LATITUDE_LNG_NAME);
5234 100 : vcdf.nc_put_vatt_text(nVarLatID, CF_UNITS, CF_DEGREES_NORTH);
5235 100 : vcdf.nc_put_vatt_text(nVarLonID, CF_STD_NAME, CF_LONGITUDE_STD_NAME);
5236 100 : vcdf.nc_put_vatt_text(nVarLonID, CF_LNG_NAME, CF_LONGITUDE_LNG_NAME);
5237 100 : vcdf.nc_put_vatt_text(nVarLonID, CF_UNITS, CF_DEGREES_EAST);
5238 : }
5239 0 : catch (nccfdriver::SG_Exception &e)
5240 : {
5241 0 : CPLError(CE_Failure, CPLE_FileIO, "%s", e.get_err_msg());
5242 : }
5243 100 : }
5244 :
5245 : /************************************************************************/
5246 : /* NCDFWriteRLonRLatVarsAttributes() */
5247 : /************************************************************************/
5248 :
5249 0 : void NCDFWriteRLonRLatVarsAttributes(nccfdriver::netCDFVID &vcdf,
5250 : int nVarRLonID, int nVarRLatID)
5251 : {
5252 : try
5253 : {
5254 0 : vcdf.nc_put_vatt_text(nVarRLatID, CF_STD_NAME, "grid_latitude");
5255 0 : vcdf.nc_put_vatt_text(nVarRLatID, CF_LNG_NAME,
5256 : "latitude in rotated pole grid");
5257 0 : vcdf.nc_put_vatt_text(nVarRLatID, CF_UNITS, "degrees");
5258 0 : vcdf.nc_put_vatt_text(nVarRLatID, CF_AXIS, "Y");
5259 :
5260 0 : vcdf.nc_put_vatt_text(nVarRLonID, CF_STD_NAME, "grid_longitude");
5261 0 : vcdf.nc_put_vatt_text(nVarRLonID, CF_LNG_NAME,
5262 : "longitude in rotated pole grid");
5263 0 : vcdf.nc_put_vatt_text(nVarRLonID, CF_UNITS, "degrees");
5264 0 : vcdf.nc_put_vatt_text(nVarRLonID, CF_AXIS, "X");
5265 : }
5266 0 : catch (nccfdriver::SG_Exception &e)
5267 : {
5268 0 : CPLError(CE_Failure, CPLE_FileIO, "%s", e.get_err_msg());
5269 : }
5270 0 : }
5271 :
5272 : /************************************************************************/
5273 : /* NCDFGetProjectedCFUnit() */
5274 : /************************************************************************/
5275 :
5276 39 : std::string NCDFGetProjectedCFUnit(const OGRSpatialReference *poSRS)
5277 : {
5278 39 : char *pszUnitsToWrite = nullptr;
5279 39 : poSRS->exportToCF1(nullptr, nullptr, &pszUnitsToWrite, nullptr);
5280 39 : const std::string osRet = pszUnitsToWrite ? pszUnitsToWrite : std::string();
5281 39 : CPLFree(pszUnitsToWrite);
5282 78 : return osRet;
5283 : }
5284 :
5285 : /************************************************************************/
5286 : /* NCDFWriteXYVarsAttributes() */
5287 : /************************************************************************/
5288 :
5289 28 : void NCDFWriteXYVarsAttributes(nccfdriver::netCDFVID &vcdf, int nVarXID,
5290 : int nVarYID, const OGRSpatialReference *poSRS)
5291 : {
5292 56 : const std::string osUnitsToWrite = NCDFGetProjectedCFUnit(poSRS);
5293 :
5294 : try
5295 : {
5296 28 : vcdf.nc_put_vatt_text(nVarXID, CF_STD_NAME, CF_PROJ_X_COORD);
5297 28 : vcdf.nc_put_vatt_text(nVarXID, CF_LNG_NAME, CF_PROJ_X_COORD_LONG_NAME);
5298 28 : if (!osUnitsToWrite.empty())
5299 28 : vcdf.nc_put_vatt_text(nVarXID, CF_UNITS, osUnitsToWrite.c_str());
5300 28 : vcdf.nc_put_vatt_text(nVarYID, CF_STD_NAME, CF_PROJ_Y_COORD);
5301 28 : vcdf.nc_put_vatt_text(nVarYID, CF_LNG_NAME, CF_PROJ_Y_COORD_LONG_NAME);
5302 28 : if (!osUnitsToWrite.empty())
5303 28 : vcdf.nc_put_vatt_text(nVarYID, CF_UNITS, osUnitsToWrite.c_str());
5304 : }
5305 0 : catch (nccfdriver::SG_Exception &e)
5306 : {
5307 0 : CPLError(CE_Failure, CPLE_FileIO, "%s", e.get_err_msg());
5308 : }
5309 28 : }
5310 :
5311 : /************************************************************************/
5312 : /* AddProjectionVars() */
5313 : /************************************************************************/
5314 :
5315 160 : CPLErr netCDFDataset::AddProjectionVars(bool bDefsOnly,
5316 : GDALProgressFunc pfnProgress,
5317 : void *pProgressData)
5318 : {
5319 160 : if (nCFVersion >= 1.8)
5320 0 : return CE_None; // do nothing
5321 :
5322 160 : bool bWriteGridMapping = false;
5323 160 : bool bWriteLonLat = false;
5324 160 : bool bHasGeoloc = false;
5325 160 : bool bWriteGDALTags = false;
5326 160 : bool bWriteGeoTransform = false;
5327 :
5328 : // For GEOLOCATION information.
5329 160 : GDALDatasetH hDS_X = nullptr;
5330 160 : GDALRasterBandH hBand_X = nullptr;
5331 160 : GDALDatasetH hDS_Y = nullptr;
5332 160 : GDALRasterBandH hBand_Y = nullptr;
5333 :
5334 320 : OGRSpatialReference oSRS(m_oSRS);
5335 160 : if (!m_oSRS.IsEmpty())
5336 : {
5337 134 : if (oSRS.IsProjected())
5338 48 : bIsProjected = true;
5339 86 : else if (oSRS.IsGeographic())
5340 86 : bIsGeographic = true;
5341 : }
5342 :
5343 160 : if (bDefsOnly)
5344 : {
5345 80 : char *pszProjection = nullptr;
5346 80 : m_oSRS.exportToWkt(&pszProjection);
5347 80 : CPLDebug("GDAL_netCDF",
5348 : "SetProjection, WKT now = [%s]\nprojected: %d geographic: %d",
5349 80 : pszProjection ? pszProjection : "(null)",
5350 80 : static_cast<int>(bIsProjected),
5351 80 : static_cast<int>(bIsGeographic));
5352 80 : CPLFree(pszProjection);
5353 :
5354 80 : if (!m_bHasGeoTransform)
5355 5 : CPLDebug("GDAL_netCDF",
5356 : "netCDFDataset::AddProjectionVars() called, "
5357 : "but GeoTransform has not yet been defined!");
5358 :
5359 80 : if (!m_bHasProjection)
5360 6 : CPLDebug("GDAL_netCDF",
5361 : "netCDFDataset::AddProjectionVars() called, "
5362 : "but Projection has not yet been defined!");
5363 : }
5364 :
5365 : // Check GEOLOCATION information.
5366 160 : char **papszGeolocationInfo = netCDFDataset::GetMetadata("GEOLOCATION");
5367 160 : if (papszGeolocationInfo != nullptr)
5368 : {
5369 : // Look for geolocation datasets.
5370 : const char *pszDSName =
5371 10 : CSLFetchNameValue(papszGeolocationInfo, "X_DATASET");
5372 10 : if (pszDSName != nullptr)
5373 10 : hDS_X = GDALOpenShared(pszDSName, GA_ReadOnly);
5374 10 : pszDSName = CSLFetchNameValue(papszGeolocationInfo, "Y_DATASET");
5375 10 : if (pszDSName != nullptr)
5376 10 : hDS_Y = GDALOpenShared(pszDSName, GA_ReadOnly);
5377 :
5378 10 : if (hDS_X != nullptr && hDS_Y != nullptr)
5379 : {
5380 10 : int nBand = std::max(1, atoi(CSLFetchNameValueDef(
5381 10 : papszGeolocationInfo, "X_BAND", "0")));
5382 10 : hBand_X = GDALGetRasterBand(hDS_X, nBand);
5383 10 : nBand = std::max(1, atoi(CSLFetchNameValueDef(papszGeolocationInfo,
5384 10 : "Y_BAND", "0")));
5385 10 : hBand_Y = GDALGetRasterBand(hDS_Y, nBand);
5386 :
5387 : // If geoloc bands are found, do basic validation based on their
5388 : // dimensions.
5389 10 : if (hBand_X != nullptr && hBand_Y != nullptr)
5390 : {
5391 10 : int nXSize_XBand = GDALGetRasterXSize(hDS_X);
5392 10 : int nYSize_XBand = GDALGetRasterYSize(hDS_X);
5393 10 : int nXSize_YBand = GDALGetRasterXSize(hDS_Y);
5394 10 : int nYSize_YBand = GDALGetRasterYSize(hDS_Y);
5395 :
5396 : // TODO 1D geolocation arrays not implemented.
5397 10 : if (nYSize_XBand == 1 && nYSize_YBand == 1)
5398 : {
5399 0 : bHasGeoloc = false;
5400 0 : CPLDebug("GDAL_netCDF",
5401 : "1D GEOLOCATION arrays not supported yet");
5402 : }
5403 : // 2D bands must have same sizes as the raster bands.
5404 10 : else if (nXSize_XBand != nRasterXSize ||
5405 10 : nYSize_XBand != nRasterYSize ||
5406 10 : nXSize_YBand != nRasterXSize ||
5407 10 : nYSize_YBand != nRasterYSize)
5408 : {
5409 0 : bHasGeoloc = false;
5410 0 : CPLDebug("GDAL_netCDF",
5411 : "GEOLOCATION array sizes (%dx%d %dx%d) differ "
5412 : "from raster (%dx%d), not supported",
5413 : nXSize_XBand, nYSize_XBand, nXSize_YBand,
5414 : nYSize_YBand, nRasterXSize, nRasterYSize);
5415 : }
5416 : else
5417 : {
5418 10 : bHasGeoloc = true;
5419 10 : CPLDebug("GDAL_netCDF",
5420 : "dataset has GEOLOCATION information, will try to "
5421 : "write it");
5422 : }
5423 : }
5424 : }
5425 : }
5426 :
5427 : // Process projection options.
5428 160 : if (bIsProjected)
5429 : {
5430 : bool bIsCfProjection =
5431 48 : oSRS.exportToCF1(nullptr, nullptr, nullptr, nullptr) == OGRERR_NONE;
5432 48 : bWriteGridMapping = true;
5433 48 : bWriteGDALTags = CPL_TO_BOOL(
5434 48 : CSLFetchBoolean(papszCreationOptions, "WRITE_GDAL_TAGS", TRUE));
5435 : // Force WRITE_GDAL_TAGS if is not a CF projection.
5436 48 : if (!bWriteGDALTags && !bIsCfProjection)
5437 0 : bWriteGDALTags = true;
5438 48 : if (bWriteGDALTags)
5439 48 : bWriteGeoTransform = true;
5440 :
5441 : // Write lon/lat: default is NO, except if has geolocation.
5442 : // With IF_NEEDED: write if has geoloc or is not CF projection.
5443 : const char *pszValue =
5444 48 : CSLFetchNameValue(papszCreationOptions, "WRITE_LONLAT");
5445 48 : if (pszValue)
5446 : {
5447 2 : if (EQUAL(pszValue, "IF_NEEDED"))
5448 : {
5449 0 : bWriteLonLat = bHasGeoloc || !bIsCfProjection;
5450 : }
5451 : else
5452 : {
5453 2 : bWriteLonLat = CPLTestBool(pszValue);
5454 : }
5455 : }
5456 : else
5457 : {
5458 46 : bWriteLonLat = bHasGeoloc;
5459 : }
5460 :
5461 : // Save value of pszCFCoordinates for later.
5462 48 : if (bWriteLonLat)
5463 : {
5464 4 : pszCFCoordinates = NCDF_LONLAT;
5465 : }
5466 : }
5467 : else
5468 : {
5469 : // Files without a Datum will not have a grid_mapping variable and
5470 : // geographic information.
5471 112 : bWriteGridMapping = bIsGeographic;
5472 :
5473 112 : if (bHasGeoloc)
5474 : {
5475 8 : bWriteLonLat = true;
5476 : }
5477 : else
5478 : {
5479 104 : bWriteGDALTags = CPL_TO_BOOL(CSLFetchBoolean(
5480 104 : papszCreationOptions, "WRITE_GDAL_TAGS", bWriteGridMapping));
5481 104 : if (bWriteGDALTags)
5482 86 : bWriteGeoTransform = true;
5483 :
5484 104 : const char *pszValue = CSLFetchNameValueDef(papszCreationOptions,
5485 : "WRITE_LONLAT", "YES");
5486 104 : if (EQUAL(pszValue, "IF_NEEDED"))
5487 0 : bWriteLonLat = true;
5488 : else
5489 104 : bWriteLonLat = CPLTestBool(pszValue);
5490 : // Don't write lon/lat if no source geotransform.
5491 104 : if (!m_bHasGeoTransform)
5492 0 : bWriteLonLat = false;
5493 : // If we don't write lon/lat, set dimnames to X/Y and write gdal
5494 : // tags.
5495 104 : if (!bWriteLonLat)
5496 : {
5497 0 : CPLError(CE_Warning, CPLE_AppDefined,
5498 : "creating geographic file without lon/lat values!");
5499 0 : if (m_bHasGeoTransform)
5500 : {
5501 0 : bWriteGDALTags = true; // Not desirable if no geotransform.
5502 0 : bWriteGeoTransform = true;
5503 : }
5504 : }
5505 : }
5506 : }
5507 :
5508 : // Make sure we write grid_mapping if we need to write GDAL tags.
5509 160 : if (bWriteGDALTags)
5510 134 : bWriteGridMapping = true;
5511 :
5512 : // bottom-up value: new driver is bottom-up by default.
5513 : // Override with WRITE_BOTTOMUP.
5514 160 : bBottomUp = CPL_TO_BOOL(
5515 160 : CSLFetchBoolean(papszCreationOptions, "WRITE_BOTTOMUP", TRUE));
5516 :
5517 160 : if (bDefsOnly)
5518 : {
5519 80 : CPLDebug(
5520 : "GDAL_netCDF",
5521 : "bIsProjected=%d bIsGeographic=%d bWriteGridMapping=%d "
5522 : "bWriteGDALTags=%d bWriteLonLat=%d bBottomUp=%d bHasGeoloc=%d",
5523 80 : static_cast<int>(bIsProjected), static_cast<int>(bIsGeographic),
5524 : static_cast<int>(bWriteGridMapping),
5525 : static_cast<int>(bWriteGDALTags), static_cast<int>(bWriteLonLat),
5526 80 : static_cast<int>(bBottomUp), static_cast<int>(bHasGeoloc));
5527 : }
5528 :
5529 : // Exit if nothing to do.
5530 160 : if (!bIsProjected && !bWriteLonLat)
5531 0 : return CE_None;
5532 :
5533 : // Define dimension names.
5534 :
5535 160 : constexpr const char *ROTATED_POLE_VAR_NAME = "rotated_pole";
5536 :
5537 160 : if (bDefsOnly)
5538 : {
5539 80 : int nVarLonID = -1;
5540 80 : int nVarLatID = -1;
5541 80 : int nVarXID = -1;
5542 80 : int nVarYID = -1;
5543 :
5544 80 : m_bAddedProjectionVarsDefs = true;
5545 :
5546 : // Make sure we are in define mode.
5547 80 : SetDefineMode(true);
5548 :
5549 : // Write projection attributes.
5550 80 : if (bWriteGridMapping)
5551 : {
5552 67 : const int NCDFVarID = NCDFWriteSRSVariable(
5553 : cdfid, &oSRS, &pszCFProjection, bWriteGDALTags);
5554 67 : if (NCDFVarID < 0)
5555 0 : return CE_Failure;
5556 :
5557 : // Optional GDAL custom projection tags.
5558 67 : if (bWriteGDALTags)
5559 : {
5560 134 : CPLString osGeoTransform;
5561 469 : for (int i = 0; i < 6; i++)
5562 : {
5563 : osGeoTransform +=
5564 402 : CPLSPrintf("%.16g ", m_adfGeoTransform[i]);
5565 : }
5566 67 : CPLDebug("GDAL_netCDF", "szGeoTransform = %s",
5567 : osGeoTransform.c_str());
5568 :
5569 : // if( strlen(pszProj4Defn) > 0 ) {
5570 : // nc_put_att_text(cdfid, NCDFVarID, "proj4",
5571 : // strlen(pszProj4Defn), pszProj4Defn);
5572 : // }
5573 :
5574 : // For now, write the geotransform for back-compat or else
5575 : // the old (1.8.1) driver overrides the CF geotransform with
5576 : // empty values from dfNN, dfSN, dfEE, dfWE;
5577 :
5578 : // TODO: fix this in 1.8 branch, and then remove this here.
5579 67 : if (bWriteGeoTransform && m_bHasGeoTransform)
5580 : {
5581 : {
5582 66 : const int status = nc_put_att_text(
5583 : cdfid, NCDFVarID, NCDF_GEOTRANSFORM,
5584 : osGeoTransform.size(), osGeoTransform.c_str());
5585 66 : NCDF_ERR(status);
5586 : }
5587 : }
5588 : }
5589 :
5590 : // Write projection variable to band variable.
5591 : // Need to call later if there are no bands.
5592 67 : AddGridMappingRef();
5593 : } // end if( bWriteGridMapping )
5594 :
5595 : // Write CF Projection vars.
5596 :
5597 80 : const bool bIsRotatedPole =
5598 147 : pszCFProjection != nullptr &&
5599 67 : EQUAL(pszCFProjection, ROTATED_POLE_VAR_NAME);
5600 80 : if (bIsRotatedPole)
5601 : {
5602 : // Rename dims to rlat/rlon.
5603 : papszDimName
5604 0 : .Clear(); // If we add other dims one day, this has to change
5605 0 : papszDimName.AddString(NCDF_DIMNAME_RLAT);
5606 0 : papszDimName.AddString(NCDF_DIMNAME_RLON);
5607 :
5608 0 : int status = nc_rename_dim(cdfid, nYDimID, NCDF_DIMNAME_RLAT);
5609 0 : NCDF_ERR(status);
5610 0 : status = nc_rename_dim(cdfid, nXDimID, NCDF_DIMNAME_RLON);
5611 0 : NCDF_ERR(status);
5612 : }
5613 : // Rename dimensions if lon/lat.
5614 80 : else if (!bIsProjected && !bHasGeoloc)
5615 : {
5616 : // Rename dims to lat/lon.
5617 : papszDimName
5618 52 : .Clear(); // If we add other dims one day, this has to change
5619 52 : papszDimName.AddString(NCDF_DIMNAME_LAT);
5620 52 : papszDimName.AddString(NCDF_DIMNAME_LON);
5621 :
5622 52 : int status = nc_rename_dim(cdfid, nYDimID, NCDF_DIMNAME_LAT);
5623 52 : NCDF_ERR(status);
5624 52 : status = nc_rename_dim(cdfid, nXDimID, NCDF_DIMNAME_LON);
5625 52 : NCDF_ERR(status);
5626 : }
5627 :
5628 : // Write X/Y attributes.
5629 : else /* if( bIsProjected || bHasGeoloc ) */
5630 : {
5631 : // X
5632 : int anXDims[1];
5633 28 : anXDims[0] = nXDimID;
5634 28 : CPLDebug("GDAL_netCDF", "nc_def_var(%d,%s,%d)", cdfid,
5635 : CF_PROJ_X_VAR_NAME, NC_DOUBLE);
5636 28 : int status = nc_def_var(cdfid, CF_PROJ_X_VAR_NAME, NC_DOUBLE, 1,
5637 : anXDims, &nVarXID);
5638 28 : NCDF_ERR(status);
5639 :
5640 : // Y
5641 : int anYDims[1];
5642 28 : anYDims[0] = nYDimID;
5643 28 : CPLDebug("GDAL_netCDF", "nc_def_var(%d,%s,%d)", cdfid,
5644 : CF_PROJ_Y_VAR_NAME, NC_DOUBLE);
5645 28 : status = nc_def_var(cdfid, CF_PROJ_Y_VAR_NAME, NC_DOUBLE, 1,
5646 : anYDims, &nVarYID);
5647 28 : NCDF_ERR(status);
5648 :
5649 28 : if (bIsProjected)
5650 : {
5651 24 : NCDFWriteXYVarsAttributes(this->vcdf, nVarXID, nVarYID, &oSRS);
5652 : }
5653 : else
5654 : {
5655 4 : CPLAssert(bHasGeoloc);
5656 : try
5657 : {
5658 4 : vcdf.nc_put_vatt_text(nVarXID, CF_AXIS, CF_SG_X_AXIS);
5659 4 : vcdf.nc_put_vatt_text(nVarXID, CF_LNG_NAME,
5660 : "x-coordinate in Cartesian system");
5661 4 : vcdf.nc_put_vatt_text(nVarXID, CF_UNITS, "m");
5662 4 : vcdf.nc_put_vatt_text(nVarYID, CF_AXIS, CF_SG_Y_AXIS);
5663 4 : vcdf.nc_put_vatt_text(nVarYID, CF_LNG_NAME,
5664 : "y-coordinate in Cartesian system");
5665 4 : vcdf.nc_put_vatt_text(nVarYID, CF_UNITS, "m");
5666 :
5667 4 : pszCFCoordinates = NCDF_LONLAT;
5668 : }
5669 0 : catch (nccfdriver::SG_Exception &e)
5670 : {
5671 0 : CPLError(CE_Failure, CPLE_FileIO, "%s", e.get_err_msg());
5672 0 : return CE_Failure;
5673 : }
5674 : }
5675 : }
5676 :
5677 : // Write lat/lon attributes if needed.
5678 80 : if (bWriteLonLat)
5679 : {
5680 58 : int *panLatDims = nullptr;
5681 58 : int *panLonDims = nullptr;
5682 58 : int nLatDims = -1;
5683 58 : int nLonDims = -1;
5684 :
5685 : // Get information.
5686 58 : if (bHasGeoloc)
5687 : {
5688 : // Geoloc
5689 5 : nLatDims = 2;
5690 : panLatDims =
5691 5 : static_cast<int *>(CPLCalloc(nLatDims, sizeof(int)));
5692 5 : panLatDims[0] = nYDimID;
5693 5 : panLatDims[1] = nXDimID;
5694 5 : nLonDims = 2;
5695 : panLonDims =
5696 5 : static_cast<int *>(CPLCalloc(nLonDims, sizeof(int)));
5697 5 : panLonDims[0] = nYDimID;
5698 5 : panLonDims[1] = nXDimID;
5699 : }
5700 53 : else if (bIsProjected)
5701 : {
5702 : // Projected
5703 1 : nLatDims = 2;
5704 : panLatDims =
5705 1 : static_cast<int *>(CPLCalloc(nLatDims, sizeof(int)));
5706 1 : panLatDims[0] = nYDimID;
5707 1 : panLatDims[1] = nXDimID;
5708 1 : nLonDims = 2;
5709 : panLonDims =
5710 1 : static_cast<int *>(CPLCalloc(nLonDims, sizeof(int)));
5711 1 : panLonDims[0] = nYDimID;
5712 1 : panLonDims[1] = nXDimID;
5713 : }
5714 : else
5715 : {
5716 : // Geographic
5717 52 : nLatDims = 1;
5718 : panLatDims =
5719 52 : static_cast<int *>(CPLCalloc(nLatDims, sizeof(int)));
5720 52 : panLatDims[0] = nYDimID;
5721 52 : nLonDims = 1;
5722 : panLonDims =
5723 52 : static_cast<int *>(CPLCalloc(nLonDims, sizeof(int)));
5724 52 : panLonDims[0] = nXDimID;
5725 : }
5726 :
5727 58 : nc_type eLonLatType = NC_NAT;
5728 58 : if (bIsProjected)
5729 : {
5730 2 : eLonLatType = NC_FLOAT;
5731 4 : const char *pszValue = CSLFetchNameValueDef(
5732 2 : papszCreationOptions, "TYPE_LONLAT", "FLOAT");
5733 2 : if (EQUAL(pszValue, "DOUBLE"))
5734 0 : eLonLatType = NC_DOUBLE;
5735 : }
5736 : else
5737 : {
5738 56 : eLonLatType = NC_DOUBLE;
5739 112 : const char *pszValue = CSLFetchNameValueDef(
5740 56 : papszCreationOptions, "TYPE_LONLAT", "DOUBLE");
5741 56 : if (EQUAL(pszValue, "FLOAT"))
5742 0 : eLonLatType = NC_FLOAT;
5743 : }
5744 :
5745 : // Def vars and attributes.
5746 : {
5747 58 : const char *pszVarName =
5748 58 : bIsRotatedPole ? NCDF_DIMNAME_RLAT : CF_LATITUDE_VAR_NAME;
5749 58 : int status = nc_def_var(cdfid, pszVarName, eLonLatType,
5750 : nLatDims, panLatDims, &nVarLatID);
5751 58 : CPLDebug("GDAL_netCDF", "nc_def_var(%d,%s,%d,%d,-,-) got id %d",
5752 : cdfid, pszVarName, eLonLatType, nLatDims, nVarLatID);
5753 58 : NCDF_ERR(status);
5754 58 : DefVarDeflate(nVarLatID, false); // Don't set chunking.
5755 : }
5756 :
5757 : {
5758 58 : const char *pszVarName =
5759 58 : bIsRotatedPole ? NCDF_DIMNAME_RLON : CF_LONGITUDE_VAR_NAME;
5760 58 : int status = nc_def_var(cdfid, pszVarName, eLonLatType,
5761 : nLonDims, panLonDims, &nVarLonID);
5762 58 : CPLDebug("GDAL_netCDF", "nc_def_var(%d,%s,%d,%d,-,-) got id %d",
5763 : cdfid, pszVarName, eLonLatType, nLatDims, nVarLonID);
5764 58 : NCDF_ERR(status);
5765 58 : DefVarDeflate(nVarLonID, false); // Don't set chunking.
5766 : }
5767 :
5768 58 : if (bIsRotatedPole)
5769 0 : NCDFWriteRLonRLatVarsAttributes(this->vcdf, nVarLonID,
5770 : nVarLatID);
5771 : else
5772 58 : NCDFWriteLonLatVarsAttributes(this->vcdf, nVarLonID, nVarLatID);
5773 :
5774 58 : CPLFree(panLatDims);
5775 58 : CPLFree(panLonDims);
5776 : }
5777 : }
5778 :
5779 160 : if (!bDefsOnly)
5780 : {
5781 80 : m_bAddedProjectionVarsData = true;
5782 :
5783 80 : int nVarXID = -1;
5784 80 : int nVarYID = -1;
5785 :
5786 80 : nc_inq_varid(cdfid, CF_PROJ_X_VAR_NAME, &nVarXID);
5787 80 : nc_inq_varid(cdfid, CF_PROJ_Y_VAR_NAME, &nVarYID);
5788 :
5789 80 : int nVarLonID = -1;
5790 80 : int nVarLatID = -1;
5791 :
5792 80 : const bool bIsRotatedPole =
5793 147 : pszCFProjection != nullptr &&
5794 67 : EQUAL(pszCFProjection, ROTATED_POLE_VAR_NAME);
5795 80 : nc_inq_varid(cdfid,
5796 : bIsRotatedPole ? NCDF_DIMNAME_RLON : CF_LONGITUDE_VAR_NAME,
5797 : &nVarLonID);
5798 80 : nc_inq_varid(cdfid,
5799 : bIsRotatedPole ? NCDF_DIMNAME_RLAT : CF_LATITUDE_VAR_NAME,
5800 : &nVarLatID);
5801 :
5802 : // Get projection values.
5803 :
5804 80 : double *padLonVal = nullptr;
5805 80 : double *padLatVal = nullptr;
5806 :
5807 80 : if (bIsProjected)
5808 : {
5809 24 : OGRSpatialReference *poLatLonSRS = nullptr;
5810 24 : OGRCoordinateTransformation *poTransform = nullptr;
5811 :
5812 : size_t startX[1];
5813 : size_t countX[1];
5814 : size_t startY[1];
5815 : size_t countY[1];
5816 :
5817 24 : CPLDebug("GDAL_netCDF", "Getting (X,Y) values");
5818 :
5819 : double *padXVal =
5820 24 : static_cast<double *>(CPLMalloc(nRasterXSize * sizeof(double)));
5821 : double *padYVal =
5822 24 : static_cast<double *>(CPLMalloc(nRasterYSize * sizeof(double)));
5823 :
5824 : // Get Y values.
5825 24 : const double dfY0 = (!bBottomUp) ? m_adfGeoTransform[3] :
5826 : // Invert latitude values.
5827 24 : m_adfGeoTransform[3] +
5828 24 : (m_adfGeoTransform[5] * nRasterYSize);
5829 24 : const double dfDY = m_adfGeoTransform[5];
5830 :
5831 1435 : for (int j = 0; j < nRasterYSize; j++)
5832 : {
5833 : // The data point is centered inside the pixel.
5834 1411 : if (!bBottomUp)
5835 0 : padYVal[j] = dfY0 + (j + 0.5) * dfDY;
5836 : else // Invert latitude values.
5837 1411 : padYVal[j] = dfY0 - (j + 0.5) * dfDY;
5838 : }
5839 24 : startX[0] = 0;
5840 24 : countX[0] = nRasterXSize;
5841 :
5842 : // Get X values.
5843 24 : const double dfX0 = m_adfGeoTransform[0];
5844 24 : const double dfDX = m_adfGeoTransform[1];
5845 :
5846 1456 : for (int i = 0; i < nRasterXSize; i++)
5847 : {
5848 : // The data point is centered inside the pixel.
5849 1432 : padXVal[i] = dfX0 + (i + 0.5) * dfDX;
5850 : }
5851 24 : startY[0] = 0;
5852 24 : countY[0] = nRasterYSize;
5853 :
5854 : // Write X/Y values.
5855 :
5856 : // Make sure we are in data mode.
5857 24 : SetDefineMode(false);
5858 :
5859 24 : CPLDebug("GDAL_netCDF", "Writing X values");
5860 : int status =
5861 24 : nc_put_vara_double(cdfid, nVarXID, startX, countX, padXVal);
5862 24 : NCDF_ERR(status);
5863 :
5864 24 : CPLDebug("GDAL_netCDF", "Writing Y values");
5865 : status =
5866 24 : nc_put_vara_double(cdfid, nVarYID, startY, countY, padYVal);
5867 24 : NCDF_ERR(status);
5868 :
5869 24 : if (pfnProgress)
5870 20 : pfnProgress(0.20, nullptr, pProgressData);
5871 :
5872 : // Write lon/lat arrays (CF coordinates) if requested.
5873 :
5874 : // Get OGR transform if GEOLOCATION is not available.
5875 24 : if (bWriteLonLat && !bHasGeoloc)
5876 : {
5877 1 : poLatLonSRS = m_oSRS.CloneGeogCS();
5878 1 : if (poLatLonSRS != nullptr)
5879 : {
5880 1 : poLatLonSRS->SetAxisMappingStrategy(
5881 : OAMS_TRADITIONAL_GIS_ORDER);
5882 : poTransform =
5883 1 : OGRCreateCoordinateTransformation(&m_oSRS, poLatLonSRS);
5884 : }
5885 : // If no OGR transform, then don't write CF lon/lat.
5886 1 : if (poTransform == nullptr)
5887 : {
5888 0 : CPLError(CE_Failure, CPLE_AppDefined,
5889 : "Unable to get Coordinate Transform");
5890 0 : bWriteLonLat = false;
5891 : }
5892 : }
5893 :
5894 24 : if (bWriteLonLat)
5895 : {
5896 2 : if (!bHasGeoloc)
5897 1 : CPLDebug("GDAL_netCDF", "Transforming (X,Y)->(lon,lat)");
5898 : else
5899 1 : CPLDebug("GDAL_netCDF",
5900 : "Writing (lon,lat) from GEOLOCATION arrays");
5901 :
5902 2 : bool bOK = true;
5903 2 : double dfProgress = 0.2;
5904 :
5905 2 : size_t start[] = {0, 0};
5906 2 : size_t count[] = {1, (size_t)nRasterXSize};
5907 : padLatVal = static_cast<double *>(
5908 2 : CPLMalloc(nRasterXSize * sizeof(double)));
5909 : padLonVal = static_cast<double *>(
5910 2 : CPLMalloc(nRasterXSize * sizeof(double)));
5911 :
5912 61 : for (int j = 0; j < nRasterYSize && bOK && status == NC_NOERR;
5913 : j++)
5914 : {
5915 59 : start[0] = j;
5916 :
5917 : // Get values from geotransform.
5918 59 : if (!bHasGeoloc)
5919 : {
5920 : // Fill values to transform.
5921 420 : for (int i = 0; i < nRasterXSize; i++)
5922 : {
5923 400 : padLatVal[i] = padYVal[j];
5924 400 : padLonVal[i] = padXVal[i];
5925 : }
5926 :
5927 : // Do the transform.
5928 20 : bOK = CPL_TO_BOOL(poTransform->Transform(
5929 20 : nRasterXSize, padLonVal, padLatVal, nullptr));
5930 20 : if (!bOK)
5931 : {
5932 0 : CPLError(CE_Failure, CPLE_AppDefined,
5933 : "Unable to Transform (X,Y) to (lon,lat).");
5934 : }
5935 : }
5936 : // Get values from geoloc arrays.
5937 : else
5938 : {
5939 39 : CPLErr eErr = GDALRasterIO(
5940 : hBand_Y, GF_Read, 0, j, nRasterXSize, 1, padLatVal,
5941 : nRasterXSize, 1, GDT_Float64, 0, 0);
5942 39 : if (eErr == CE_None)
5943 : {
5944 39 : eErr = GDALRasterIO(
5945 : hBand_X, GF_Read, 0, j, nRasterXSize, 1,
5946 : padLonVal, nRasterXSize, 1, GDT_Float64, 0, 0);
5947 : }
5948 :
5949 39 : if (eErr == CE_None)
5950 : {
5951 39 : bOK = true;
5952 : }
5953 : else
5954 : {
5955 0 : bOK = false;
5956 0 : CPLError(CE_Failure, CPLE_AppDefined,
5957 : "Unable to get scanline %d", j);
5958 : }
5959 : }
5960 :
5961 : // Write data.
5962 59 : if (bOK)
5963 : {
5964 59 : status = nc_put_vara_double(cdfid, nVarLatID, start,
5965 : count, padLatVal);
5966 59 : NCDF_ERR(status);
5967 59 : status = nc_put_vara_double(cdfid, nVarLonID, start,
5968 : count, padLonVal);
5969 59 : NCDF_ERR(status);
5970 : }
5971 :
5972 59 : if (pfnProgress && (nRasterYSize / 10) > 0 &&
5973 59 : (j % (nRasterYSize / 10) == 0))
5974 : {
5975 23 : dfProgress += 0.08;
5976 23 : pfnProgress(dfProgress, nullptr, pProgressData);
5977 : }
5978 : }
5979 : }
5980 :
5981 24 : if (poLatLonSRS != nullptr)
5982 1 : delete poLatLonSRS;
5983 24 : if (poTransform != nullptr)
5984 1 : delete poTransform;
5985 :
5986 24 : CPLFree(padXVal);
5987 24 : CPLFree(padYVal);
5988 : } // Projected
5989 :
5990 : // If not projected/geographic and has geoloc
5991 56 : else if (!bIsGeographic && bHasGeoloc)
5992 : {
5993 : // Use
5994 : // https://cfconventions.org/Data/cf-conventions/cf-conventions-1.9/cf-conventions.html#_two_dimensional_latitude_longitude_coordinate_variables
5995 :
5996 4 : bool bOK = true;
5997 4 : double dfProgress = 0.2;
5998 :
5999 : // Make sure we are in data mode.
6000 4 : SetDefineMode(false);
6001 :
6002 : size_t startX[1];
6003 : size_t countX[1];
6004 : size_t startY[1];
6005 : size_t countY[1];
6006 4 : startX[0] = 0;
6007 4 : countX[0] = nRasterXSize;
6008 :
6009 4 : startY[0] = 0;
6010 4 : countY[0] = nRasterYSize;
6011 :
6012 8 : std::vector<double> adfXVal(nRasterXSize);
6013 16 : for (int i = 0; i < nRasterXSize; i++)
6014 12 : adfXVal[i] = i;
6015 :
6016 8 : std::vector<double> adfYVal(nRasterYSize);
6017 12 : for (int i = 0; i < nRasterYSize; i++)
6018 8 : adfYVal[i] = bBottomUp ? nRasterYSize - 1 - i : i;
6019 :
6020 4 : CPLDebug("GDAL_netCDF", "Writing X values");
6021 4 : int status = nc_put_vara_double(cdfid, nVarXID, startX, countX,
6022 4 : adfXVal.data());
6023 4 : NCDF_ERR(status);
6024 :
6025 4 : CPLDebug("GDAL_netCDF", "Writing Y values");
6026 4 : status = nc_put_vara_double(cdfid, nVarYID, startY, countY,
6027 4 : adfYVal.data());
6028 4 : NCDF_ERR(status);
6029 :
6030 4 : if (pfnProgress)
6031 0 : pfnProgress(0.20, nullptr, pProgressData);
6032 :
6033 4 : size_t start[] = {0, 0};
6034 4 : size_t count[] = {1, (size_t)nRasterXSize};
6035 : padLatVal =
6036 4 : static_cast<double *>(CPLMalloc(nRasterXSize * sizeof(double)));
6037 : padLonVal =
6038 4 : static_cast<double *>(CPLMalloc(nRasterXSize * sizeof(double)));
6039 :
6040 12 : for (int j = 0; j < nRasterYSize && bOK && status == NC_NOERR; j++)
6041 : {
6042 8 : start[0] = j;
6043 :
6044 8 : CPLErr eErr = GDALRasterIO(hBand_Y, GF_Read, 0,
6045 8 : bBottomUp ? nRasterYSize - 1 - j : j,
6046 : nRasterXSize, 1, padLatVal,
6047 : nRasterXSize, 1, GDT_Float64, 0, 0);
6048 8 : if (eErr == CE_None)
6049 : {
6050 8 : eErr = GDALRasterIO(hBand_X, GF_Read, 0,
6051 8 : bBottomUp ? nRasterYSize - 1 - j : j,
6052 : nRasterXSize, 1, padLonVal,
6053 : nRasterXSize, 1, GDT_Float64, 0, 0);
6054 : }
6055 :
6056 8 : if (eErr == CE_None)
6057 : {
6058 8 : bOK = true;
6059 : }
6060 : else
6061 : {
6062 0 : bOK = false;
6063 0 : CPLError(CE_Failure, CPLE_AppDefined,
6064 : "Unable to get scanline %d", j);
6065 : }
6066 :
6067 : // Write data.
6068 8 : if (bOK)
6069 : {
6070 8 : status = nc_put_vara_double(cdfid, nVarLatID, start, count,
6071 : padLatVal);
6072 8 : NCDF_ERR(status);
6073 8 : status = nc_put_vara_double(cdfid, nVarLonID, start, count,
6074 : padLonVal);
6075 8 : NCDF_ERR(status);
6076 : }
6077 :
6078 8 : if (pfnProgress && (nRasterYSize / 10) > 0 &&
6079 0 : (j % (nRasterYSize / 10) == 0))
6080 : {
6081 0 : dfProgress += 0.08;
6082 0 : pfnProgress(dfProgress, nullptr, pProgressData);
6083 : }
6084 4 : }
6085 : }
6086 :
6087 : // If not projected, assume geographic to catch grids without Datum.
6088 52 : else if (bWriteLonLat)
6089 : {
6090 : // Get latitude values.
6091 52 : const double dfY0 = (!bBottomUp) ? m_adfGeoTransform[3] :
6092 : // Invert latitude values.
6093 52 : m_adfGeoTransform[3] +
6094 52 : (m_adfGeoTransform[5] * nRasterYSize);
6095 52 : const double dfDY = m_adfGeoTransform[5];
6096 :
6097 : // Override lat values with the ones in GEOLOCATION/Y_VALUES.
6098 52 : if (netCDFDataset::GetMetadataItem("Y_VALUES", "GEOLOCATION") !=
6099 : nullptr)
6100 : {
6101 0 : int nTemp = 0;
6102 0 : padLatVal = Get1DGeolocation("Y_VALUES", nTemp);
6103 : // Make sure we got the correct amount, if not fallback to GT */
6104 : // could add test fabs(fabs(padLatVal[0]) - fabs(dfY0)) <= 0.1))
6105 0 : if (nTemp == nRasterYSize)
6106 : {
6107 0 : CPLDebug(
6108 : "GDAL_netCDF",
6109 : "Using Y_VALUES geolocation metadata for lat values");
6110 : }
6111 : else
6112 : {
6113 0 : CPLDebug("GDAL_netCDF",
6114 : "Got %d elements from Y_VALUES geolocation "
6115 : "metadata, need %d",
6116 : nTemp, nRasterYSize);
6117 0 : if (padLatVal)
6118 : {
6119 0 : CPLFree(padLatVal);
6120 0 : padLatVal = nullptr;
6121 : }
6122 : }
6123 : }
6124 :
6125 52 : if (padLatVal == nullptr)
6126 : {
6127 : padLatVal = static_cast<double *>(
6128 52 : CPLMalloc(nRasterYSize * sizeof(double)));
6129 3504 : for (int i = 0; i < nRasterYSize; i++)
6130 : {
6131 : // The data point is centered inside the pixel.
6132 3452 : if (!bBottomUp)
6133 0 : padLatVal[i] = dfY0 + (i + 0.5) * dfDY;
6134 : else // Invert latitude values.
6135 3452 : padLatVal[i] = dfY0 - (i + 0.5) * dfDY;
6136 : }
6137 : }
6138 :
6139 52 : size_t startLat[1] = {0};
6140 52 : size_t countLat[1] = {static_cast<size_t>(nRasterYSize)};
6141 :
6142 : // Get longitude values.
6143 52 : const double dfX0 = m_adfGeoTransform[0];
6144 52 : const double dfDX = m_adfGeoTransform[1];
6145 :
6146 : padLonVal =
6147 52 : static_cast<double *>(CPLMalloc(nRasterXSize * sizeof(double)));
6148 3556 : for (int i = 0; i < nRasterXSize; i++)
6149 : {
6150 : // The data point is centered inside the pixel.
6151 3504 : padLonVal[i] = dfX0 + (i + 0.5) * dfDX;
6152 : }
6153 :
6154 52 : size_t startLon[1] = {0};
6155 52 : size_t countLon[1] = {static_cast<size_t>(nRasterXSize)};
6156 :
6157 : // Write latitude and longitude values.
6158 :
6159 : // Make sure we are in data mode.
6160 52 : SetDefineMode(false);
6161 :
6162 : // Write values.
6163 52 : CPLDebug("GDAL_netCDF", "Writing lat values");
6164 :
6165 52 : int status = nc_put_vara_double(cdfid, nVarLatID, startLat,
6166 : countLat, padLatVal);
6167 52 : NCDF_ERR(status);
6168 :
6169 52 : CPLDebug("GDAL_netCDF", "Writing lon values");
6170 52 : status = nc_put_vara_double(cdfid, nVarLonID, startLon, countLon,
6171 : padLonVal);
6172 52 : NCDF_ERR(status);
6173 :
6174 : } // Not projected.
6175 :
6176 80 : CPLFree(padLatVal);
6177 80 : CPLFree(padLonVal);
6178 :
6179 80 : if (pfnProgress)
6180 39 : pfnProgress(1.00, nullptr, pProgressData);
6181 : }
6182 :
6183 160 : if (hDS_X != nullptr)
6184 : {
6185 10 : GDALClose(hDS_X);
6186 : }
6187 160 : if (hDS_Y != nullptr)
6188 : {
6189 10 : GDALClose(hDS_Y);
6190 : }
6191 :
6192 160 : return CE_None;
6193 : }
6194 :
6195 : // Write Projection variable to band variable.
6196 : // Moved from AddProjectionVars() for cases when bands are added after
6197 : // projection.
6198 369 : bool netCDFDataset::AddGridMappingRef()
6199 : {
6200 369 : bool bRet = true;
6201 369 : bool bOldDefineMode = bDefineMode;
6202 :
6203 556 : if ((GetAccess() == GA_Update) && (nBands >= 1) && (GetRasterBand(1)) &&
6204 187 : ((pszCFCoordinates != nullptr && !EQUAL(pszCFCoordinates, "")) ||
6205 181 : (pszCFProjection != nullptr && !EQUAL(pszCFProjection, ""))))
6206 : {
6207 71 : bAddedGridMappingRef = true;
6208 :
6209 : // Make sure we are in define mode.
6210 71 : SetDefineMode(true);
6211 :
6212 188 : for (int i = 1; i <= nBands; i++)
6213 : {
6214 : const int nVarId =
6215 117 : static_cast<netCDFRasterBand *>(GetRasterBand(i))->nZId;
6216 :
6217 117 : if (pszCFProjection != nullptr && !EQUAL(pszCFProjection, ""))
6218 : {
6219 : int status =
6220 226 : nc_put_att_text(cdfid, nVarId, CF_GRD_MAPPING,
6221 113 : strlen(pszCFProjection), pszCFProjection);
6222 113 : NCDF_ERR(status);
6223 113 : if (status != NC_NOERR)
6224 0 : bRet = false;
6225 : }
6226 117 : if (pszCFCoordinates != nullptr && !EQUAL(pszCFCoordinates, ""))
6227 : {
6228 : int status =
6229 6 : nc_put_att_text(cdfid, nVarId, CF_COORDINATES,
6230 : strlen(pszCFCoordinates), pszCFCoordinates);
6231 6 : NCDF_ERR(status);
6232 6 : if (status != NC_NOERR)
6233 0 : bRet = false;
6234 : }
6235 : }
6236 :
6237 : // Go back to previous define mode.
6238 71 : SetDefineMode(bOldDefineMode);
6239 : }
6240 369 : return bRet;
6241 : }
6242 :
6243 : /************************************************************************/
6244 : /* GetGeoTransform() */
6245 : /************************************************************************/
6246 :
6247 107 : CPLErr netCDFDataset::GetGeoTransform(double *padfTransform)
6248 :
6249 : {
6250 107 : memcpy(padfTransform, m_adfGeoTransform, sizeof(double) * 6);
6251 107 : if (m_bHasGeoTransform)
6252 77 : return CE_None;
6253 :
6254 30 : return GDALPamDataset::GetGeoTransform(padfTransform);
6255 : }
6256 :
6257 : /************************************************************************/
6258 : /* rint() */
6259 : /************************************************************************/
6260 :
6261 0 : double netCDFDataset::rint(double dfX)
6262 : {
6263 0 : return std::round(dfX);
6264 : }
6265 :
6266 : /************************************************************************/
6267 : /* NCDFReadIsoMetadata() */
6268 : /************************************************************************/
6269 :
6270 16 : static void NCDFReadMetadataAsJson(int cdfid, CPLJSONObject &obj)
6271 : {
6272 16 : int nbAttr = 0;
6273 16 : NCDF_ERR(nc_inq_varnatts(cdfid, NC_GLOBAL, &nbAttr));
6274 :
6275 32 : std::map<std::string, CPLJSONArray> oMapNameToArray;
6276 40 : for (int l = 0; l < nbAttr; l++)
6277 : {
6278 : char szAttrName[NC_MAX_NAME + 1];
6279 24 : szAttrName[0] = 0;
6280 24 : NCDF_ERR(nc_inq_attname(cdfid, NC_GLOBAL, l, szAttrName));
6281 :
6282 24 : char *pszMetaValue = nullptr;
6283 24 : if (NCDFGetAttr(cdfid, NC_GLOBAL, szAttrName, &pszMetaValue) == CE_None)
6284 : {
6285 24 : nc_type nAttrType = NC_NAT;
6286 24 : size_t nAttrLen = 0;
6287 :
6288 24 : NCDF_ERR(nc_inq_att(cdfid, NC_GLOBAL, szAttrName, &nAttrType,
6289 : &nAttrLen));
6290 :
6291 24 : std::string osAttrName(szAttrName);
6292 24 : const auto sharpPos = osAttrName.find('#');
6293 24 : if (sharpPos == std::string::npos)
6294 : {
6295 16 : if (nAttrType == NC_DOUBLE || nAttrType == NC_FLOAT)
6296 4 : obj.Add(osAttrName, CPLAtof(pszMetaValue));
6297 : else
6298 12 : obj.Add(osAttrName, pszMetaValue);
6299 : }
6300 : else
6301 : {
6302 8 : osAttrName.resize(sharpPos);
6303 8 : auto iter = oMapNameToArray.find(osAttrName);
6304 8 : if (iter == oMapNameToArray.end())
6305 : {
6306 8 : CPLJSONArray array;
6307 4 : obj.Add(osAttrName, array);
6308 4 : oMapNameToArray[osAttrName] = array;
6309 4 : array.Add(pszMetaValue);
6310 : }
6311 : else
6312 : {
6313 4 : iter->second.Add(pszMetaValue);
6314 : }
6315 : }
6316 24 : CPLFree(pszMetaValue);
6317 24 : pszMetaValue = nullptr;
6318 : }
6319 : }
6320 :
6321 16 : int nSubGroups = 0;
6322 16 : int *panSubGroupIds = nullptr;
6323 16 : NCDFGetSubGroups(cdfid, &nSubGroups, &panSubGroupIds);
6324 16 : oMapNameToArray.clear();
6325 28 : for (int i = 0; i < nSubGroups; i++)
6326 : {
6327 24 : CPLJSONObject subObj;
6328 12 : NCDFReadMetadataAsJson(panSubGroupIds[i], subObj);
6329 :
6330 24 : std::string osGroupName;
6331 12 : osGroupName.resize(NC_MAX_NAME);
6332 12 : NCDF_ERR(nc_inq_grpname(panSubGroupIds[i], &osGroupName[0]));
6333 12 : osGroupName.resize(strlen(osGroupName.data()));
6334 12 : const auto sharpPos = osGroupName.find('#');
6335 12 : if (sharpPos == std::string::npos)
6336 : {
6337 4 : obj.Add(osGroupName, subObj);
6338 : }
6339 : else
6340 : {
6341 8 : osGroupName.resize(sharpPos);
6342 8 : auto iter = oMapNameToArray.find(osGroupName);
6343 8 : if (iter == oMapNameToArray.end())
6344 : {
6345 8 : CPLJSONArray array;
6346 4 : obj.Add(osGroupName, array);
6347 4 : oMapNameToArray[osGroupName] = array;
6348 4 : array.Add(subObj);
6349 : }
6350 : else
6351 : {
6352 4 : iter->second.Add(subObj);
6353 : }
6354 : }
6355 : }
6356 16 : CPLFree(panSubGroupIds);
6357 16 : }
6358 :
6359 4 : std::string NCDFReadMetadataAsJson(int cdfid)
6360 : {
6361 8 : CPLJSONDocument oDoc;
6362 8 : CPLJSONObject oRoot = oDoc.GetRoot();
6363 4 : NCDFReadMetadataAsJson(cdfid, oRoot);
6364 8 : return oDoc.SaveAsString();
6365 : }
6366 :
6367 : /************************************************************************/
6368 : /* ReadAttributes() */
6369 : /************************************************************************/
6370 1758 : CPLErr netCDFDataset::ReadAttributes(int cdfidIn, int var)
6371 :
6372 : {
6373 1758 : char *pszVarFullName = nullptr;
6374 1758 : ERR_RET(NCDFGetVarFullName(cdfidIn, var, &pszVarFullName));
6375 :
6376 : // For metadata in Sentinel 5
6377 1758 : if (STARTS_WITH(pszVarFullName, "/METADATA/"))
6378 : {
6379 6 : for (const char *key :
6380 : {"ISO_METADATA", "ESA_METADATA", "EOP_METADATA", "QA_STATISTICS",
6381 8 : "GRANULE_DESCRIPTION", "ALGORITHM_SETTINGS"})
6382 : {
6383 14 : if (var == NC_GLOBAL &&
6384 7 : strcmp(pszVarFullName,
6385 : CPLSPrintf("/METADATA/%s/NC_GLOBAL", key)) == 0)
6386 : {
6387 1 : CPLFree(pszVarFullName);
6388 1 : CPLStringList aosList;
6389 2 : aosList.AddString(CPLString(NCDFReadMetadataAsJson(cdfidIn))
6390 1 : .replaceAll("\\/", '/'));
6391 1 : m_oMapDomainToJSon[key] = std::move(aosList);
6392 1 : return CE_None;
6393 : }
6394 : }
6395 : }
6396 1757 : if (STARTS_WITH(pszVarFullName, "/PRODUCT/SUPPORT_DATA/"))
6397 : {
6398 0 : CPLFree(pszVarFullName);
6399 0 : CPLStringList aosList;
6400 : aosList.AddString(
6401 0 : CPLString(NCDFReadMetadataAsJson(cdfidIn)).replaceAll("\\/", '/'));
6402 0 : m_oMapDomainToJSon["SUPPORT_DATA"] = std::move(aosList);
6403 0 : return CE_None;
6404 : }
6405 :
6406 1757 : size_t nMetaNameSize =
6407 1757 : sizeof(char) * (strlen(pszVarFullName) + 1 + NC_MAX_NAME + 1);
6408 1757 : char *pszMetaName = static_cast<char *>(CPLMalloc(nMetaNameSize));
6409 :
6410 1757 : int nbAttr = 0;
6411 1757 : NCDF_ERR(nc_inq_varnatts(cdfidIn, var, &nbAttr));
6412 :
6413 8800 : for (int l = 0; l < nbAttr; l++)
6414 : {
6415 : char szAttrName[NC_MAX_NAME + 1];
6416 7043 : szAttrName[0] = 0;
6417 7043 : NCDF_ERR(nc_inq_attname(cdfidIn, var, l, szAttrName));
6418 7043 : snprintf(pszMetaName, nMetaNameSize, "%s#%s", pszVarFullName,
6419 : szAttrName);
6420 :
6421 7043 : char *pszMetaTemp = nullptr;
6422 7043 : if (NCDFGetAttr(cdfidIn, var, szAttrName, &pszMetaTemp) == CE_None)
6423 : {
6424 7042 : papszMetadata =
6425 7042 : CSLSetNameValue(papszMetadata, pszMetaName, pszMetaTemp);
6426 7042 : CPLFree(pszMetaTemp);
6427 7042 : pszMetaTemp = nullptr;
6428 : }
6429 : else
6430 : {
6431 1 : CPLDebug("GDAL_netCDF", "invalid metadata %s", pszMetaName);
6432 : }
6433 : }
6434 :
6435 1757 : CPLFree(pszVarFullName);
6436 1757 : CPLFree(pszMetaName);
6437 :
6438 1757 : if (var == NC_GLOBAL)
6439 : {
6440 : // Recurse on sub-groups.
6441 516 : int nSubGroups = 0;
6442 516 : int *panSubGroupIds = nullptr;
6443 516 : NCDFGetSubGroups(cdfidIn, &nSubGroups, &panSubGroupIds);
6444 545 : for (int i = 0; i < nSubGroups; i++)
6445 : {
6446 29 : ReadAttributes(panSubGroupIds[i], var);
6447 : }
6448 516 : CPLFree(panSubGroupIds);
6449 : }
6450 :
6451 1757 : return CE_None;
6452 : }
6453 :
6454 : /************************************************************************/
6455 : /* netCDFDataset::CreateSubDatasetList() */
6456 : /************************************************************************/
6457 50 : void netCDFDataset::CreateSubDatasetList(int nGroupId)
6458 : {
6459 : char szVarStdName[NC_MAX_NAME + 1];
6460 50 : int *ponDimIds = nullptr;
6461 : nc_type nAttype;
6462 : size_t nAttlen;
6463 :
6464 50 : netCDFDataset *poDS = this;
6465 :
6466 : int nVarCount;
6467 50 : nc_inq_nvars(nGroupId, &nVarCount);
6468 :
6469 324 : for (int nVar = 0; nVar < nVarCount; nVar++)
6470 : {
6471 :
6472 : int nDims;
6473 274 : nc_inq_varndims(nGroupId, nVar, &nDims);
6474 :
6475 274 : if (nDims >= 2)
6476 : {
6477 155 : ponDimIds = static_cast<int *>(CPLCalloc(nDims, sizeof(int)));
6478 155 : nc_inq_vardimid(nGroupId, nVar, ponDimIds);
6479 :
6480 : // Create Sub dataset list.
6481 155 : CPLString osDim;
6482 480 : for (int i = 0; i < nDims; i++)
6483 : {
6484 : size_t nDimLen;
6485 325 : nc_inq_dimlen(nGroupId, ponDimIds[i], &nDimLen);
6486 325 : osDim += CPLSPrintf("%dx", (int)nDimLen);
6487 : }
6488 155 : CPLFree(ponDimIds);
6489 :
6490 : nc_type nVarType;
6491 155 : nc_inq_vartype(nGroupId, nVar, &nVarType);
6492 : // Get rid of the last "x" character.
6493 155 : osDim.pop_back();
6494 155 : const char *pszType = "";
6495 155 : switch (nVarType)
6496 : {
6497 37 : case NC_BYTE:
6498 37 : pszType = "8-bit integer";
6499 37 : break;
6500 2 : case NC_CHAR:
6501 2 : pszType = "8-bit character";
6502 2 : break;
6503 6 : case NC_SHORT:
6504 6 : pszType = "16-bit integer";
6505 6 : break;
6506 10 : case NC_INT:
6507 10 : pszType = "32-bit integer";
6508 10 : break;
6509 51 : case NC_FLOAT:
6510 51 : pszType = "32-bit floating-point";
6511 51 : break;
6512 31 : case NC_DOUBLE:
6513 31 : pszType = "64-bit floating-point";
6514 31 : break;
6515 4 : case NC_UBYTE:
6516 4 : pszType = "8-bit unsigned integer";
6517 4 : break;
6518 1 : case NC_USHORT:
6519 1 : pszType = "16-bit unsigned integer";
6520 1 : break;
6521 1 : case NC_UINT:
6522 1 : pszType = "32-bit unsigned integer";
6523 1 : break;
6524 1 : case NC_INT64:
6525 1 : pszType = "64-bit integer";
6526 1 : break;
6527 1 : case NC_UINT64:
6528 1 : pszType = "64-bit unsigned integer";
6529 1 : break;
6530 10 : default:
6531 10 : break;
6532 : }
6533 :
6534 155 : char *pszName = nullptr;
6535 155 : if (NCDFGetVarFullName(nGroupId, nVar, &pszName) != CE_None)
6536 0 : continue;
6537 :
6538 155 : nSubDatasets++;
6539 :
6540 155 : nAttlen = 0;
6541 155 : nc_inq_att(nGroupId, nVar, CF_STD_NAME, &nAttype, &nAttlen);
6542 310 : if (nAttlen < sizeof(szVarStdName) &&
6543 155 : nc_get_att_text(nGroupId, nVar, CF_STD_NAME, szVarStdName) ==
6544 : NC_NOERR)
6545 : {
6546 51 : szVarStdName[nAttlen] = '\0';
6547 : }
6548 : else
6549 : {
6550 104 : snprintf(szVarStdName, sizeof(szVarStdName), "%s", pszName);
6551 : }
6552 :
6553 : char szTemp[NC_MAX_NAME + 1];
6554 155 : snprintf(szTemp, sizeof(szTemp), "SUBDATASET_%d_NAME",
6555 : nSubDatasets);
6556 :
6557 155 : if (strchr(pszName, ' ') || strchr(pszName, ':'))
6558 : {
6559 1 : poDS->papszSubDatasets = CSLSetNameValue(
6560 : poDS->papszSubDatasets, szTemp,
6561 : CPLSPrintf("NETCDF:\"%s\":\"%s\"", poDS->osFilename.c_str(),
6562 : pszName));
6563 : }
6564 : else
6565 : {
6566 154 : poDS->papszSubDatasets = CSLSetNameValue(
6567 : poDS->papszSubDatasets, szTemp,
6568 : CPLSPrintf("NETCDF:\"%s\":%s", poDS->osFilename.c_str(),
6569 : pszName));
6570 : }
6571 :
6572 155 : CPLFree(pszName);
6573 :
6574 155 : snprintf(szTemp, sizeof(szTemp), "SUBDATASET_%d_DESC",
6575 : nSubDatasets);
6576 :
6577 155 : poDS->papszSubDatasets =
6578 155 : CSLSetNameValue(poDS->papszSubDatasets, szTemp,
6579 : CPLSPrintf("[%s] %s (%s)", osDim.c_str(),
6580 : szVarStdName, pszType));
6581 : }
6582 : }
6583 :
6584 : // Recurse on sub groups.
6585 50 : int nSubGroups = 0;
6586 50 : int *panSubGroupIds = nullptr;
6587 50 : NCDFGetSubGroups(nGroupId, &nSubGroups, &panSubGroupIds);
6588 55 : for (int i = 0; i < nSubGroups; i++)
6589 : {
6590 5 : CreateSubDatasetList(panSubGroupIds[i]);
6591 : }
6592 50 : CPLFree(panSubGroupIds);
6593 50 : }
6594 :
6595 : /************************************************************************/
6596 : /* TestCapability() */
6597 : /************************************************************************/
6598 :
6599 248 : int netCDFDataset::TestCapability(const char *pszCap)
6600 : {
6601 248 : if (EQUAL(pszCap, ODsCCreateLayer))
6602 : {
6603 223 : return eAccess == GA_Update && nBands == 0 &&
6604 218 : (eMultipleLayerBehavior != SINGLE_LAYER ||
6605 229 : this->GetLayerCount() == 0 || bSGSupport);
6606 : }
6607 136 : else if (EQUAL(pszCap, ODsCZGeometries))
6608 2 : return true;
6609 :
6610 134 : return false;
6611 : }
6612 :
6613 : /************************************************************************/
6614 : /* GetLayer() */
6615 : /************************************************************************/
6616 :
6617 384 : OGRLayer *netCDFDataset::GetLayer(int nIdx)
6618 : {
6619 384 : if (nIdx < 0 || nIdx >= this->GetLayerCount())
6620 2 : return nullptr;
6621 382 : return papoLayers[nIdx].get();
6622 : }
6623 :
6624 : /************************************************************************/
6625 : /* ICreateLayer() */
6626 : /************************************************************************/
6627 :
6628 59 : OGRLayer *netCDFDataset::ICreateLayer(const char *pszName,
6629 : const OGRGeomFieldDefn *poGeomFieldDefn,
6630 : CSLConstList papszOptions)
6631 : {
6632 59 : int nLayerCDFId = cdfid;
6633 59 : if (!TestCapability(ODsCCreateLayer))
6634 0 : return nullptr;
6635 :
6636 59 : const auto eGType = poGeomFieldDefn ? poGeomFieldDefn->GetType() : wkbNone;
6637 : const auto poSpatialRef =
6638 59 : poGeomFieldDefn ? poGeomFieldDefn->GetSpatialRef() : nullptr;
6639 :
6640 118 : CPLString osNetCDFLayerName(pszName);
6641 59 : const netCDFWriterConfigLayer *poLayerConfig = nullptr;
6642 59 : if (oWriterConfig.m_bIsValid)
6643 : {
6644 : std::map<CPLString, netCDFWriterConfigLayer>::const_iterator
6645 2 : oLayerIter = oWriterConfig.m_oLayers.find(pszName);
6646 2 : if (oLayerIter != oWriterConfig.m_oLayers.end())
6647 : {
6648 1 : poLayerConfig = &(oLayerIter->second);
6649 1 : osNetCDFLayerName = poLayerConfig->m_osNetCDFName;
6650 : }
6651 : }
6652 :
6653 59 : netCDFDataset *poLayerDataset = nullptr;
6654 59 : if (eMultipleLayerBehavior == SEPARATE_FILES)
6655 : {
6656 2 : char **papszDatasetOptions = nullptr;
6657 2 : papszDatasetOptions = CSLSetNameValue(
6658 : papszDatasetOptions, "CONFIG_FILE",
6659 2 : CSLFetchNameValue(papszCreationOptions, "CONFIG_FILE"));
6660 : papszDatasetOptions =
6661 2 : CSLSetNameValue(papszDatasetOptions, "FORMAT",
6662 2 : CSLFetchNameValue(papszCreationOptions, "FORMAT"));
6663 2 : papszDatasetOptions = CSLSetNameValue(
6664 : papszDatasetOptions, "WRITE_GDAL_TAGS",
6665 2 : CSLFetchNameValue(papszCreationOptions, "WRITE_GDAL_TAGS"));
6666 : const CPLString osLayerFilename(
6667 2 : CPLFormFilenameSafe(osFilename, osNetCDFLayerName, "nc"));
6668 2 : CPLAcquireMutex(hNCMutex, 1000.0);
6669 2 : poLayerDataset =
6670 2 : CreateLL(osLayerFilename, 0, 0, 0, papszDatasetOptions);
6671 2 : CPLReleaseMutex(hNCMutex);
6672 2 : CSLDestroy(papszDatasetOptions);
6673 2 : if (poLayerDataset == nullptr)
6674 0 : return nullptr;
6675 :
6676 2 : nLayerCDFId = poLayerDataset->cdfid;
6677 2 : NCDFAddGDALHistory(nLayerCDFId, osLayerFilename, bWriteGDALVersion,
6678 2 : bWriteGDALHistory, "", "Create",
6679 : NCDF_CONVENTIONS_CF_V1_6);
6680 : }
6681 57 : else if (eMultipleLayerBehavior == SEPARATE_GROUPS)
6682 : {
6683 2 : SetDefineMode(true);
6684 :
6685 2 : nLayerCDFId = -1;
6686 2 : int status = nc_def_grp(cdfid, osNetCDFLayerName, &nLayerCDFId);
6687 2 : NCDF_ERR(status);
6688 2 : if (status != NC_NOERR)
6689 0 : return nullptr;
6690 :
6691 2 : NCDFAddGDALHistory(nLayerCDFId, osFilename, bWriteGDALVersion,
6692 2 : bWriteGDALHistory, "", "Create",
6693 : NCDF_CONVENTIONS_CF_V1_6);
6694 : }
6695 :
6696 : // Make a clone to workaround a bug in released MapServer versions
6697 : // that destroys the passed SRS instead of releasing it .
6698 59 : OGRSpatialReference *poSRS = nullptr;
6699 59 : if (poSpatialRef)
6700 : {
6701 43 : poSRS = poSpatialRef->Clone();
6702 43 : poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
6703 : }
6704 : std::shared_ptr<netCDFLayer> poLayer(
6705 59 : new netCDFLayer(poLayerDataset ? poLayerDataset : this, nLayerCDFId,
6706 118 : osNetCDFLayerName, eGType, poSRS));
6707 59 : if (poSRS != nullptr)
6708 43 : poSRS->Release();
6709 :
6710 : // Fetch layer creation options coming from config file
6711 59 : char **papszNewOptions = CSLDuplicate(papszOptions);
6712 59 : if (oWriterConfig.m_bIsValid)
6713 : {
6714 2 : std::map<CPLString, CPLString>::const_iterator oIter;
6715 3 : for (oIter = oWriterConfig.m_oLayerCreationOptions.begin();
6716 3 : oIter != oWriterConfig.m_oLayerCreationOptions.end(); ++oIter)
6717 : {
6718 : papszNewOptions =
6719 1 : CSLSetNameValue(papszNewOptions, oIter->first, oIter->second);
6720 : }
6721 2 : if (poLayerConfig != nullptr)
6722 : {
6723 3 : for (oIter = poLayerConfig->m_oLayerCreationOptions.begin();
6724 3 : oIter != poLayerConfig->m_oLayerCreationOptions.end(); ++oIter)
6725 : {
6726 2 : papszNewOptions = CSLSetNameValue(papszNewOptions, oIter->first,
6727 2 : oIter->second);
6728 : }
6729 : }
6730 : }
6731 :
6732 59 : const bool bRet = poLayer->Create(papszNewOptions, poLayerConfig);
6733 59 : CSLDestroy(papszNewOptions);
6734 :
6735 59 : if (!bRet)
6736 : {
6737 0 : return nullptr;
6738 : }
6739 :
6740 59 : if (poLayerDataset != nullptr)
6741 2 : apoVectorDatasets.push_back(poLayerDataset);
6742 :
6743 59 : papoLayers.push_back(poLayer);
6744 59 : return poLayer.get();
6745 : }
6746 :
6747 : /************************************************************************/
6748 : /* CloneAttributes() */
6749 : /************************************************************************/
6750 :
6751 137 : bool netCDFDataset::CloneAttributes(int old_cdfid, int new_cdfid, int nSrcVarId,
6752 : int nDstVarId)
6753 : {
6754 137 : int nAttCount = -1;
6755 137 : int status = nc_inq_varnatts(old_cdfid, nSrcVarId, &nAttCount);
6756 137 : NCDF_ERR(status);
6757 :
6758 693 : for (int i = 0; i < nAttCount; i++)
6759 : {
6760 : char szName[NC_MAX_NAME + 1];
6761 556 : szName[0] = 0;
6762 556 : status = nc_inq_attname(old_cdfid, nSrcVarId, i, szName);
6763 556 : NCDF_ERR(status);
6764 :
6765 : status =
6766 556 : nc_copy_att(old_cdfid, nSrcVarId, szName, new_cdfid, nDstVarId);
6767 556 : NCDF_ERR(status);
6768 556 : if (status != NC_NOERR)
6769 0 : return false;
6770 : }
6771 :
6772 137 : return true;
6773 : }
6774 :
6775 : /************************************************************************/
6776 : /* CloneVariableContent() */
6777 : /************************************************************************/
6778 :
6779 121 : bool netCDFDataset::CloneVariableContent(int old_cdfid, int new_cdfid,
6780 : int nSrcVarId, int nDstVarId)
6781 : {
6782 121 : int nVarDimCount = -1;
6783 121 : int status = nc_inq_varndims(old_cdfid, nSrcVarId, &nVarDimCount);
6784 121 : NCDF_ERR(status);
6785 121 : int anDimIds[] = {-1, 1};
6786 121 : status = nc_inq_vardimid(old_cdfid, nSrcVarId, anDimIds);
6787 121 : NCDF_ERR(status);
6788 121 : nc_type nc_datatype = NC_NAT;
6789 121 : status = nc_inq_vartype(old_cdfid, nSrcVarId, &nc_datatype);
6790 121 : NCDF_ERR(status);
6791 121 : size_t nTypeSize = 0;
6792 121 : switch (nc_datatype)
6793 : {
6794 35 : case NC_BYTE:
6795 : case NC_CHAR:
6796 35 : nTypeSize = 1;
6797 35 : break;
6798 4 : case NC_SHORT:
6799 4 : nTypeSize = 2;
6800 4 : break;
6801 24 : case NC_INT:
6802 24 : nTypeSize = 4;
6803 24 : break;
6804 4 : case NC_FLOAT:
6805 4 : nTypeSize = 4;
6806 4 : break;
6807 43 : case NC_DOUBLE:
6808 43 : nTypeSize = 8;
6809 43 : break;
6810 2 : case NC_UBYTE:
6811 2 : nTypeSize = 1;
6812 2 : break;
6813 2 : case NC_USHORT:
6814 2 : nTypeSize = 2;
6815 2 : break;
6816 2 : case NC_UINT:
6817 2 : nTypeSize = 4;
6818 2 : break;
6819 4 : case NC_INT64:
6820 : case NC_UINT64:
6821 4 : nTypeSize = 8;
6822 4 : break;
6823 1 : case NC_STRING:
6824 1 : nTypeSize = sizeof(char *);
6825 1 : break;
6826 0 : default:
6827 : {
6828 0 : CPLError(CE_Failure, CPLE_NotSupported, "Unsupported data type: %d",
6829 : nc_datatype);
6830 0 : return false;
6831 : }
6832 : }
6833 :
6834 121 : size_t nElems = 1;
6835 : size_t anStart[NC_MAX_DIMS];
6836 : size_t anCount[NC_MAX_DIMS];
6837 121 : size_t nRecords = 1;
6838 261 : for (int i = 0; i < nVarDimCount; i++)
6839 : {
6840 140 : anStart[i] = 0;
6841 140 : if (i == 0)
6842 : {
6843 116 : anCount[i] = 1;
6844 116 : status = nc_inq_dimlen(old_cdfid, anDimIds[i], &nRecords);
6845 116 : NCDF_ERR(status);
6846 : }
6847 : else
6848 : {
6849 24 : anCount[i] = 0;
6850 24 : status = nc_inq_dimlen(old_cdfid, anDimIds[i], &anCount[i]);
6851 24 : NCDF_ERR(status);
6852 24 : nElems *= anCount[i];
6853 : }
6854 : }
6855 :
6856 : /* Workaround in some cases a netCDF bug:
6857 : * https://github.com/Unidata/netcdf-c/pull/1442 */
6858 121 : if (nRecords > 0 && nRecords < 10 * 1000 * 1000 / (nElems * nTypeSize))
6859 : {
6860 119 : nElems *= nRecords;
6861 119 : anCount[0] = nRecords;
6862 119 : nRecords = 1;
6863 : }
6864 :
6865 121 : void *pBuffer = VSI_MALLOC2_VERBOSE(nElems, nTypeSize);
6866 121 : if (pBuffer == nullptr)
6867 0 : return false;
6868 :
6869 240 : for (size_t iRecord = 0; iRecord < nRecords; iRecord++)
6870 : {
6871 119 : anStart[0] = iRecord;
6872 :
6873 119 : switch (nc_datatype)
6874 : {
6875 5 : case NC_BYTE:
6876 : status =
6877 5 : nc_get_vara_schar(old_cdfid, nSrcVarId, anStart, anCount,
6878 : static_cast<signed char *>(pBuffer));
6879 5 : if (!status)
6880 5 : status = nc_put_vara_schar(
6881 : new_cdfid, nDstVarId, anStart, anCount,
6882 : static_cast<signed char *>(pBuffer));
6883 5 : break;
6884 28 : case NC_CHAR:
6885 : status =
6886 28 : nc_get_vara_text(old_cdfid, nSrcVarId, anStart, anCount,
6887 : static_cast<char *>(pBuffer));
6888 28 : if (!status)
6889 : status =
6890 28 : nc_put_vara_text(new_cdfid, nDstVarId, anStart, anCount,
6891 : static_cast<char *>(pBuffer));
6892 28 : break;
6893 4 : case NC_SHORT:
6894 : status =
6895 4 : nc_get_vara_short(old_cdfid, nSrcVarId, anStart, anCount,
6896 : static_cast<short *>(pBuffer));
6897 4 : if (!status)
6898 4 : status = nc_put_vara_short(new_cdfid, nDstVarId, anStart,
6899 : anCount,
6900 : static_cast<short *>(pBuffer));
6901 4 : break;
6902 24 : case NC_INT:
6903 24 : status = nc_get_vara_int(old_cdfid, nSrcVarId, anStart, anCount,
6904 : static_cast<int *>(pBuffer));
6905 24 : if (!status)
6906 : status =
6907 24 : nc_put_vara_int(new_cdfid, nDstVarId, anStart, anCount,
6908 : static_cast<int *>(pBuffer));
6909 24 : break;
6910 4 : case NC_FLOAT:
6911 : status =
6912 4 : nc_get_vara_float(old_cdfid, nSrcVarId, anStart, anCount,
6913 : static_cast<float *>(pBuffer));
6914 4 : if (!status)
6915 4 : status = nc_put_vara_float(new_cdfid, nDstVarId, anStart,
6916 : anCount,
6917 : static_cast<float *>(pBuffer));
6918 4 : break;
6919 43 : case NC_DOUBLE:
6920 : status =
6921 43 : nc_get_vara_double(old_cdfid, nSrcVarId, anStart, anCount,
6922 : static_cast<double *>(pBuffer));
6923 43 : if (!status)
6924 43 : status = nc_put_vara_double(new_cdfid, nDstVarId, anStart,
6925 : anCount,
6926 : static_cast<double *>(pBuffer));
6927 43 : break;
6928 1 : case NC_STRING:
6929 : status =
6930 1 : nc_get_vara_string(old_cdfid, nSrcVarId, anStart, anCount,
6931 : static_cast<char **>(pBuffer));
6932 1 : if (!status)
6933 : {
6934 1 : status = nc_put_vara_string(
6935 : new_cdfid, nDstVarId, anStart, anCount,
6936 : static_cast<const char **>(pBuffer));
6937 1 : nc_free_string(nElems, static_cast<char **>(pBuffer));
6938 : }
6939 1 : break;
6940 :
6941 2 : case NC_UBYTE:
6942 : status =
6943 2 : nc_get_vara_uchar(old_cdfid, nSrcVarId, anStart, anCount,
6944 : static_cast<unsigned char *>(pBuffer));
6945 2 : if (!status)
6946 2 : status = nc_put_vara_uchar(
6947 : new_cdfid, nDstVarId, anStart, anCount,
6948 : static_cast<unsigned char *>(pBuffer));
6949 2 : break;
6950 2 : case NC_USHORT:
6951 : status =
6952 2 : nc_get_vara_ushort(old_cdfid, nSrcVarId, anStart, anCount,
6953 : static_cast<unsigned short *>(pBuffer));
6954 2 : if (!status)
6955 2 : status = nc_put_vara_ushort(
6956 : new_cdfid, nDstVarId, anStart, anCount,
6957 : static_cast<unsigned short *>(pBuffer));
6958 2 : break;
6959 2 : case NC_UINT:
6960 : status =
6961 2 : nc_get_vara_uint(old_cdfid, nSrcVarId, anStart, anCount,
6962 : static_cast<unsigned int *>(pBuffer));
6963 2 : if (!status)
6964 : status =
6965 2 : nc_put_vara_uint(new_cdfid, nDstVarId, anStart, anCount,
6966 : static_cast<unsigned int *>(pBuffer));
6967 2 : break;
6968 2 : case NC_INT64:
6969 : status =
6970 2 : nc_get_vara_longlong(old_cdfid, nSrcVarId, anStart, anCount,
6971 : static_cast<long long *>(pBuffer));
6972 2 : if (!status)
6973 2 : status = nc_put_vara_longlong(
6974 : new_cdfid, nDstVarId, anStart, anCount,
6975 : static_cast<long long *>(pBuffer));
6976 2 : break;
6977 2 : case NC_UINT64:
6978 2 : status = nc_get_vara_ulonglong(
6979 : old_cdfid, nSrcVarId, anStart, anCount,
6980 : static_cast<unsigned long long *>(pBuffer));
6981 2 : if (!status)
6982 2 : status = nc_put_vara_ulonglong(
6983 : new_cdfid, nDstVarId, anStart, anCount,
6984 : static_cast<unsigned long long *>(pBuffer));
6985 2 : break;
6986 0 : default:
6987 0 : status = NC_EBADTYPE;
6988 : }
6989 :
6990 119 : NCDF_ERR(status);
6991 119 : if (status != NC_NOERR)
6992 : {
6993 0 : VSIFree(pBuffer);
6994 0 : return false;
6995 : }
6996 : }
6997 :
6998 121 : VSIFree(pBuffer);
6999 121 : return true;
7000 : }
7001 :
7002 : /************************************************************************/
7003 : /* NCDFIsUnlimitedDim() */
7004 : /************************************************************************/
7005 :
7006 58 : bool NCDFIsUnlimitedDim(bool bIsNC4, int cdfid, int nDimId)
7007 : {
7008 58 : if (bIsNC4)
7009 : {
7010 16 : int nUnlimitedDims = 0;
7011 16 : nc_inq_unlimdims(cdfid, &nUnlimitedDims, nullptr);
7012 16 : bool bFound = false;
7013 16 : if (nUnlimitedDims)
7014 : {
7015 : int *panUnlimitedDimIds =
7016 16 : static_cast<int *>(CPLMalloc(sizeof(int) * nUnlimitedDims));
7017 16 : nc_inq_unlimdims(cdfid, nullptr, panUnlimitedDimIds);
7018 30 : for (int i = 0; i < nUnlimitedDims; i++)
7019 : {
7020 22 : if (panUnlimitedDimIds[i] == nDimId)
7021 : {
7022 8 : bFound = true;
7023 8 : break;
7024 : }
7025 : }
7026 16 : CPLFree(panUnlimitedDimIds);
7027 : }
7028 16 : return bFound;
7029 : }
7030 : else
7031 : {
7032 42 : int nUnlimitedDimId = -1;
7033 42 : nc_inq(cdfid, nullptr, nullptr, nullptr, &nUnlimitedDimId);
7034 42 : return nDimId == nUnlimitedDimId;
7035 : }
7036 : }
7037 :
7038 : /************************************************************************/
7039 : /* CloneGrp() */
7040 : /************************************************************************/
7041 :
7042 16 : bool netCDFDataset::CloneGrp(int nOldGrpId, int nNewGrpId, bool bIsNC4,
7043 : int nLayerId, int nDimIdToGrow, size_t nNewSize)
7044 : {
7045 : // Clone dimensions
7046 16 : int nDimCount = -1;
7047 16 : int status = nc_inq_ndims(nOldGrpId, &nDimCount);
7048 16 : NCDF_ERR(status);
7049 16 : if (nDimCount < 0 || nDimCount > NC_MAX_DIMS)
7050 0 : return false;
7051 : int anDimIds[NC_MAX_DIMS];
7052 16 : int nUnlimiDimID = -1;
7053 16 : status = nc_inq_unlimdim(nOldGrpId, &nUnlimiDimID);
7054 16 : NCDF_ERR(status);
7055 16 : if (bIsNC4)
7056 : {
7057 : // In NC4, the dimension ids of a group are not necessarily in
7058 : // [0,nDimCount-1] range
7059 8 : int nDimCount2 = -1;
7060 8 : status = nc_inq_dimids(nOldGrpId, &nDimCount2, anDimIds, FALSE);
7061 8 : NCDF_ERR(status);
7062 8 : CPLAssert(nDimCount == nDimCount2);
7063 : }
7064 : else
7065 : {
7066 36 : for (int i = 0; i < nDimCount; i++)
7067 28 : anDimIds[i] = i;
7068 : }
7069 60 : for (int i = 0; i < nDimCount; i++)
7070 : {
7071 : char szDimName[NC_MAX_NAME + 1];
7072 44 : szDimName[0] = 0;
7073 44 : size_t nLen = 0;
7074 44 : const int nDimId = anDimIds[i];
7075 44 : status = nc_inq_dim(nOldGrpId, nDimId, szDimName, &nLen);
7076 44 : NCDF_ERR(status);
7077 44 : if (NCDFIsUnlimitedDim(bIsNC4, nOldGrpId, nDimId))
7078 16 : nLen = NC_UNLIMITED;
7079 28 : else if (nDimId == nDimIdToGrow && nOldGrpId == nLayerId)
7080 13 : nLen = nNewSize;
7081 44 : int nNewDimId = -1;
7082 44 : status = nc_def_dim(nNewGrpId, szDimName, nLen, &nNewDimId);
7083 44 : NCDF_ERR(status);
7084 44 : CPLAssert(nDimId == nNewDimId);
7085 44 : if (status != NC_NOERR)
7086 : {
7087 0 : return false;
7088 : }
7089 : }
7090 :
7091 : // Clone main attributes
7092 16 : if (!CloneAttributes(nOldGrpId, nNewGrpId, NC_GLOBAL, NC_GLOBAL))
7093 : {
7094 0 : return false;
7095 : }
7096 :
7097 : // Clone variable definitions
7098 16 : int nVarCount = -1;
7099 16 : status = nc_inq_nvars(nOldGrpId, &nVarCount);
7100 16 : NCDF_ERR(status);
7101 :
7102 137 : for (int i = 0; i < nVarCount; i++)
7103 : {
7104 : char szVarName[NC_MAX_NAME + 1];
7105 121 : szVarName[0] = 0;
7106 121 : status = nc_inq_varname(nOldGrpId, i, szVarName);
7107 121 : NCDF_ERR(status);
7108 121 : nc_type nc_datatype = NC_NAT;
7109 121 : status = nc_inq_vartype(nOldGrpId, i, &nc_datatype);
7110 121 : NCDF_ERR(status);
7111 121 : int nVarDimCount = -1;
7112 121 : status = nc_inq_varndims(nOldGrpId, i, &nVarDimCount);
7113 121 : NCDF_ERR(status);
7114 121 : status = nc_inq_vardimid(nOldGrpId, i, anDimIds);
7115 121 : NCDF_ERR(status);
7116 121 : int nNewVarId = -1;
7117 121 : status = nc_def_var(nNewGrpId, szVarName, nc_datatype, nVarDimCount,
7118 : anDimIds, &nNewVarId);
7119 121 : NCDF_ERR(status);
7120 121 : CPLAssert(i == nNewVarId);
7121 121 : if (status != NC_NOERR)
7122 : {
7123 0 : return false;
7124 : }
7125 :
7126 121 : if (!CloneAttributes(nOldGrpId, nNewGrpId, i, i))
7127 : {
7128 0 : return false;
7129 : }
7130 : }
7131 :
7132 16 : status = nc_enddef(nNewGrpId);
7133 16 : NCDF_ERR(status);
7134 16 : if (status != NC_NOERR)
7135 : {
7136 0 : return false;
7137 : }
7138 :
7139 : // Clone variable content
7140 137 : for (int i = 0; i < nVarCount; i++)
7141 : {
7142 121 : if (!CloneVariableContent(nOldGrpId, nNewGrpId, i, i))
7143 : {
7144 0 : return false;
7145 : }
7146 : }
7147 :
7148 16 : return true;
7149 : }
7150 :
7151 : /************************************************************************/
7152 : /* GrowDim() */
7153 : /************************************************************************/
7154 :
7155 13 : bool netCDFDataset::GrowDim(int nLayerId, int nDimIdToGrow, size_t nNewSize)
7156 : {
7157 : int nCreationMode;
7158 : // Set nCreationMode based on eFormat.
7159 13 : switch (eFormat)
7160 : {
7161 : #ifdef NETCDF_HAS_NC2
7162 0 : case NCDF_FORMAT_NC2:
7163 0 : nCreationMode = NC_CLOBBER | NC_64BIT_OFFSET;
7164 0 : break;
7165 : #endif
7166 5 : case NCDF_FORMAT_NC4:
7167 5 : nCreationMode = NC_CLOBBER | NC_NETCDF4;
7168 5 : break;
7169 0 : case NCDF_FORMAT_NC4C:
7170 0 : nCreationMode = NC_CLOBBER | NC_NETCDF4 | NC_CLASSIC_MODEL;
7171 0 : break;
7172 8 : case NCDF_FORMAT_NC:
7173 : default:
7174 8 : nCreationMode = NC_CLOBBER;
7175 8 : break;
7176 : }
7177 :
7178 13 : int new_cdfid = -1;
7179 26 : CPLString osTmpFilename(osFilename + ".tmp");
7180 26 : CPLString osFilenameForNCCreate(osTmpFilename);
7181 : #if defined(_WIN32) && !defined(NETCDF_USES_UTF8)
7182 : if (CPLTestBool(CPLGetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")))
7183 : {
7184 : char *pszTemp =
7185 : CPLRecode(osFilenameForNCCreate, CPL_ENC_UTF8, "CP_ACP");
7186 : osFilenameForNCCreate = pszTemp;
7187 : CPLFree(pszTemp);
7188 : }
7189 : #endif
7190 13 : int status = nc_create(osFilenameForNCCreate, nCreationMode, &new_cdfid);
7191 13 : NCDF_ERR(status);
7192 13 : if (status != NC_NOERR)
7193 0 : return false;
7194 :
7195 13 : if (!CloneGrp(cdfid, new_cdfid, eFormat == NCDF_FORMAT_NC4, nLayerId,
7196 : nDimIdToGrow, nNewSize))
7197 : {
7198 0 : GDAL_nc_close(new_cdfid);
7199 0 : return false;
7200 : }
7201 :
7202 13 : int nGroupCount = 0;
7203 26 : std::vector<CPLString> oListGrpName;
7204 31 : if (eFormat == NCDF_FORMAT_NC4 &&
7205 18 : nc_inq_grps(cdfid, &nGroupCount, nullptr) == NC_NOERR &&
7206 5 : nGroupCount > 0)
7207 : {
7208 : int *panGroupIds =
7209 2 : static_cast<int *>(CPLMalloc(sizeof(int) * nGroupCount));
7210 2 : status = nc_inq_grps(cdfid, nullptr, panGroupIds);
7211 2 : NCDF_ERR(status);
7212 5 : for (int i = 0; i < nGroupCount; i++)
7213 : {
7214 : char szGroupName[NC_MAX_NAME + 1];
7215 3 : szGroupName[0] = 0;
7216 3 : NCDF_ERR(nc_inq_grpname(panGroupIds[i], szGroupName));
7217 3 : int nNewGrpId = -1;
7218 3 : status = nc_def_grp(new_cdfid, szGroupName, &nNewGrpId);
7219 3 : NCDF_ERR(status);
7220 3 : if (status != NC_NOERR)
7221 : {
7222 0 : CPLFree(panGroupIds);
7223 0 : GDAL_nc_close(new_cdfid);
7224 0 : return false;
7225 : }
7226 3 : if (!CloneGrp(panGroupIds[i], nNewGrpId, /*bIsNC4=*/true, nLayerId,
7227 : nDimIdToGrow, nNewSize))
7228 : {
7229 0 : CPLFree(panGroupIds);
7230 0 : GDAL_nc_close(new_cdfid);
7231 0 : return false;
7232 : }
7233 : }
7234 2 : CPLFree(panGroupIds);
7235 :
7236 5 : for (int i = 0; i < this->GetLayerCount(); i++)
7237 : {
7238 3 : auto poLayer = dynamic_cast<netCDFLayer *>(papoLayers[i].get());
7239 3 : if (poLayer)
7240 : {
7241 : char szGroupName[NC_MAX_NAME + 1];
7242 3 : szGroupName[0] = 0;
7243 3 : status = nc_inq_grpname(poLayer->GetCDFID(), szGroupName);
7244 3 : NCDF_ERR(status);
7245 3 : oListGrpName.push_back(szGroupName);
7246 : }
7247 : }
7248 : }
7249 :
7250 13 : GDAL_nc_close(cdfid);
7251 13 : cdfid = -1;
7252 13 : GDAL_nc_close(new_cdfid);
7253 :
7254 26 : CPLString osOriFilename(osFilename + ".ori");
7255 26 : if (VSIRename(osFilename, osOriFilename) != 0 ||
7256 13 : VSIRename(osTmpFilename, osFilename) != 0)
7257 : {
7258 0 : CPLError(CE_Failure, CPLE_FileIO, "Renaming of files failed");
7259 0 : return false;
7260 : }
7261 13 : VSIUnlink(osOriFilename);
7262 :
7263 26 : CPLString osFilenameForNCOpen(osFilename);
7264 : #if defined(_WIN32) && !defined(NETCDF_USES_UTF8)
7265 : if (CPLTestBool(CPLGetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")))
7266 : {
7267 : char *pszTemp = CPLRecode(osFilenameForNCOpen, CPL_ENC_UTF8, "CP_ACP");
7268 : osFilenameForNCOpen = pszTemp;
7269 : CPLFree(pszTemp);
7270 : }
7271 : #endif
7272 13 : status = GDAL_nc_open(osFilenameForNCOpen, NC_WRITE, &cdfid);
7273 13 : NCDF_ERR(status);
7274 13 : if (status != NC_NOERR)
7275 0 : return false;
7276 13 : bDefineMode = false;
7277 :
7278 13 : if (!oListGrpName.empty())
7279 : {
7280 5 : for (int i = 0; i < this->GetLayerCount(); i++)
7281 : {
7282 3 : auto poLayer = dynamic_cast<netCDFLayer *>(papoLayers[i].get());
7283 3 : if (poLayer)
7284 : {
7285 3 : int nNewLayerCDFID = -1;
7286 3 : status = nc_inq_ncid(cdfid, oListGrpName[i].c_str(),
7287 : &nNewLayerCDFID);
7288 3 : NCDF_ERR(status);
7289 3 : poLayer->SetCDFID(nNewLayerCDFID);
7290 : }
7291 : }
7292 : }
7293 : else
7294 : {
7295 22 : for (int i = 0; i < this->GetLayerCount(); i++)
7296 : {
7297 11 : auto poLayer = dynamic_cast<netCDFLayer *>(papoLayers[i].get());
7298 11 : if (poLayer)
7299 11 : poLayer->SetCDFID(cdfid);
7300 : }
7301 : }
7302 :
7303 13 : return true;
7304 : }
7305 :
7306 : #ifdef ENABLE_NCDUMP
7307 :
7308 : /************************************************************************/
7309 : /* netCDFDatasetCreateTempFile() */
7310 : /************************************************************************/
7311 :
7312 : /* Create a netCDF file from a text dump (format of ncdump) */
7313 : /* Mostly to easy fuzzing of the driver, while still generating valid */
7314 : /* netCDF files. */
7315 : /* Note: not all data types are supported ! */
7316 4 : bool netCDFDatasetCreateTempFile(NetCDFFormatEnum eFormat,
7317 : const char *pszTmpFilename, VSILFILE *fpSrc)
7318 : {
7319 4 : CPL_IGNORE_RET_VAL(eFormat);
7320 4 : int nCreateMode = NC_CLOBBER;
7321 4 : if (eFormat == NCDF_FORMAT_NC4)
7322 1 : nCreateMode |= NC_NETCDF4;
7323 3 : else if (eFormat == NCDF_FORMAT_NC4C)
7324 0 : nCreateMode |= NC_NETCDF4 | NC_CLASSIC_MODEL;
7325 4 : int nCdfId = -1;
7326 4 : int status = nc_create(pszTmpFilename, nCreateMode, &nCdfId);
7327 4 : if (status != NC_NOERR)
7328 : {
7329 0 : return false;
7330 : }
7331 4 : VSIFSeekL(fpSrc, 0, SEEK_SET);
7332 : const char *pszLine;
7333 4 : constexpr int SECTION_NONE = 0;
7334 4 : constexpr int SECTION_DIMENSIONS = 1;
7335 4 : constexpr int SECTION_VARIABLES = 2;
7336 4 : constexpr int SECTION_DATA = 3;
7337 4 : int nActiveSection = SECTION_NONE;
7338 8 : std::map<CPLString, int> oMapDimToId;
7339 8 : std::map<int, int> oMapDimIdToDimLen;
7340 8 : std::map<CPLString, int> oMapVarToId;
7341 8 : std::map<int, std::vector<int>> oMapVarIdToVectorOfDimId;
7342 8 : std::map<int, int> oMapVarIdToType;
7343 4 : std::set<CPLString> oSetAttrDefined;
7344 4 : oMapVarToId[""] = -1;
7345 4 : size_t nTotalVarSize = 0;
7346 208 : while ((pszLine = CPLReadLineL(fpSrc)) != nullptr)
7347 : {
7348 204 : if (STARTS_WITH(pszLine, "dimensions:") &&
7349 : nActiveSection == SECTION_NONE)
7350 : {
7351 4 : nActiveSection = SECTION_DIMENSIONS;
7352 : }
7353 200 : else if (STARTS_WITH(pszLine, "variables:") &&
7354 : nActiveSection == SECTION_DIMENSIONS)
7355 : {
7356 4 : nActiveSection = SECTION_VARIABLES;
7357 : }
7358 196 : else if (STARTS_WITH(pszLine, "data:") &&
7359 : nActiveSection == SECTION_VARIABLES)
7360 : {
7361 4 : nActiveSection = SECTION_DATA;
7362 4 : status = nc_enddef(nCdfId);
7363 4 : if (status != NC_NOERR)
7364 : {
7365 0 : CPLDebug("netCDF", "nc_enddef() failed: %s",
7366 : nc_strerror(status));
7367 : }
7368 : }
7369 192 : else if (nActiveSection == SECTION_DIMENSIONS)
7370 : {
7371 9 : char **papszTokens = CSLTokenizeString2(pszLine, " \t=;", 0);
7372 9 : if (CSLCount(papszTokens) == 2)
7373 : {
7374 9 : const char *pszDimName = papszTokens[0];
7375 9 : bool bValidName = true;
7376 9 : if (STARTS_WITH(pszDimName, "_nc4_non_coord_"))
7377 : {
7378 : // This is an internal netcdf prefix. Using it may
7379 : // cause memory leaks.
7380 0 : bValidName = false;
7381 : }
7382 9 : if (!bValidName)
7383 : {
7384 0 : CPLDebug("netCDF",
7385 : "nc_def_dim(%s) failed: invalid name found",
7386 : pszDimName);
7387 0 : CSLDestroy(papszTokens);
7388 0 : continue;
7389 : }
7390 :
7391 : const bool bIsASCII =
7392 9 : CPLIsASCII(pszDimName, static_cast<size_t>(-1));
7393 9 : if (!bIsASCII)
7394 : {
7395 : // Workaround https://github.com/Unidata/netcdf-c/pull/450
7396 0 : CPLDebug("netCDF",
7397 : "nc_def_dim(%s) failed: rejected because "
7398 : "of non-ASCII characters",
7399 : pszDimName);
7400 0 : CSLDestroy(papszTokens);
7401 0 : continue;
7402 : }
7403 9 : int nDimSize = EQUAL(papszTokens[1], "UNLIMITED")
7404 : ? NC_UNLIMITED
7405 9 : : atoi(papszTokens[1]);
7406 9 : if (nDimSize >= 1000)
7407 1 : nDimSize = 1000; // to avoid very long processing
7408 9 : if (nDimSize >= 0)
7409 : {
7410 9 : int nDimId = -1;
7411 9 : status = nc_def_dim(nCdfId, pszDimName, nDimSize, &nDimId);
7412 9 : if (status != NC_NOERR)
7413 : {
7414 0 : CPLDebug("netCDF", "nc_def_dim(%s, %d) failed: %s",
7415 : pszDimName, nDimSize, nc_strerror(status));
7416 : }
7417 : else
7418 : {
7419 : #ifdef DEBUG_VERBOSE
7420 : CPLDebug("netCDF", "nc_def_dim(%s, %d) (%s) succeeded",
7421 : pszDimName, nDimSize, pszLine);
7422 : #endif
7423 9 : oMapDimToId[pszDimName] = nDimId;
7424 9 : oMapDimIdToDimLen[nDimId] = nDimSize;
7425 : }
7426 : }
7427 : }
7428 9 : CSLDestroy(papszTokens);
7429 : }
7430 183 : else if (nActiveSection == SECTION_VARIABLES)
7431 : {
7432 390 : while (*pszLine == ' ' || *pszLine == '\t')
7433 249 : pszLine++;
7434 141 : const char *pszColumn = strchr(pszLine, ':');
7435 141 : const char *pszEqual = strchr(pszLine, '=');
7436 141 : if (pszColumn == nullptr)
7437 : {
7438 21 : char **papszTokens = CSLTokenizeString2(pszLine, " \t=(),;", 0);
7439 21 : if (CSLCount(papszTokens) >= 2)
7440 : {
7441 17 : const char *pszVarName = papszTokens[1];
7442 17 : bool bValidName = true;
7443 17 : if (STARTS_WITH(pszVarName, "_nc4_non_coord_"))
7444 : {
7445 : // This is an internal netcdf prefix. Using it may
7446 : // cause memory leaks.
7447 0 : bValidName = false;
7448 : }
7449 138 : for (int i = 0; pszVarName[i]; i++)
7450 : {
7451 121 : if (!((pszVarName[i] >= 'a' && pszVarName[i] <= 'z') ||
7452 28 : (pszVarName[i] >= 'A' && pszVarName[i] <= 'Z') ||
7453 9 : (pszVarName[i] >= '0' && pszVarName[i] <= '9') ||
7454 6 : pszVarName[i] == '_'))
7455 : {
7456 0 : bValidName = false;
7457 : }
7458 : }
7459 17 : if (!bValidName)
7460 : {
7461 0 : CPLDebug(
7462 : "netCDF",
7463 : "nc_def_var(%s) failed: illegal character found",
7464 : pszVarName);
7465 0 : CSLDestroy(papszTokens);
7466 0 : continue;
7467 : }
7468 17 : if (oMapVarToId.find(pszVarName) != oMapVarToId.end())
7469 : {
7470 0 : CPLDebug("netCDF",
7471 : "nc_def_var(%s) failed: already defined",
7472 : pszVarName);
7473 0 : CSLDestroy(papszTokens);
7474 0 : continue;
7475 : }
7476 17 : const char *pszVarType = papszTokens[0];
7477 17 : int nc_datatype = NC_BYTE;
7478 17 : size_t nDataTypeSize = 1;
7479 17 : if (EQUAL(pszVarType, "char"))
7480 : {
7481 6 : nc_datatype = NC_CHAR;
7482 6 : nDataTypeSize = 1;
7483 : }
7484 11 : else if (EQUAL(pszVarType, "byte"))
7485 : {
7486 3 : nc_datatype = NC_BYTE;
7487 3 : nDataTypeSize = 1;
7488 : }
7489 8 : else if (EQUAL(pszVarType, "short"))
7490 : {
7491 0 : nc_datatype = NC_SHORT;
7492 0 : nDataTypeSize = 2;
7493 : }
7494 8 : else if (EQUAL(pszVarType, "int"))
7495 : {
7496 0 : nc_datatype = NC_INT;
7497 0 : nDataTypeSize = 4;
7498 : }
7499 8 : else if (EQUAL(pszVarType, "float"))
7500 : {
7501 0 : nc_datatype = NC_FLOAT;
7502 0 : nDataTypeSize = 4;
7503 : }
7504 8 : else if (EQUAL(pszVarType, "double"))
7505 : {
7506 8 : nc_datatype = NC_DOUBLE;
7507 8 : nDataTypeSize = 8;
7508 : }
7509 0 : else if (EQUAL(pszVarType, "ubyte"))
7510 : {
7511 0 : nc_datatype = NC_UBYTE;
7512 0 : nDataTypeSize = 1;
7513 : }
7514 0 : else if (EQUAL(pszVarType, "ushort"))
7515 : {
7516 0 : nc_datatype = NC_USHORT;
7517 0 : nDataTypeSize = 2;
7518 : }
7519 0 : else if (EQUAL(pszVarType, "uint"))
7520 : {
7521 0 : nc_datatype = NC_UINT;
7522 0 : nDataTypeSize = 4;
7523 : }
7524 0 : else if (EQUAL(pszVarType, "int64"))
7525 : {
7526 0 : nc_datatype = NC_INT64;
7527 0 : nDataTypeSize = 8;
7528 : }
7529 0 : else if (EQUAL(pszVarType, "uint64"))
7530 : {
7531 0 : nc_datatype = NC_UINT64;
7532 0 : nDataTypeSize = 8;
7533 : }
7534 :
7535 17 : int nDims = CSLCount(papszTokens) - 2;
7536 17 : if (nDims >= 32)
7537 : {
7538 : // The number of dimensions in a netCDFv4 file is
7539 : // limited by #define H5S_MAX_RANK 32
7540 : // but libnetcdf doesn't check that...
7541 0 : CPLDebug("netCDF",
7542 : "nc_def_var(%s) failed: too many dimensions",
7543 : pszVarName);
7544 0 : CSLDestroy(papszTokens);
7545 0 : continue;
7546 : }
7547 17 : std::vector<int> aoDimIds;
7548 17 : bool bFailed = false;
7549 17 : size_t nSize = 1;
7550 35 : for (int i = 0; i < nDims; i++)
7551 : {
7552 18 : const char *pszDimName = papszTokens[2 + i];
7553 18 : if (oMapDimToId.find(pszDimName) == oMapDimToId.end())
7554 : {
7555 0 : bFailed = true;
7556 0 : break;
7557 : }
7558 18 : const int nDimId = oMapDimToId[pszDimName];
7559 18 : aoDimIds.push_back(nDimId);
7560 :
7561 18 : const size_t nDimSize = oMapDimIdToDimLen[nDimId];
7562 18 : if (nDimSize != 0)
7563 : {
7564 18 : if (nSize >
7565 18 : std::numeric_limits<size_t>::max() / nDimSize)
7566 : {
7567 0 : bFailed = true;
7568 0 : break;
7569 : }
7570 : else
7571 : {
7572 18 : nSize *= nDimSize;
7573 : }
7574 : }
7575 : }
7576 17 : if (bFailed)
7577 : {
7578 0 : CPLDebug("netCDF",
7579 : "nc_def_var(%s) failed: unknown dimension(s)",
7580 : pszVarName);
7581 0 : CSLDestroy(papszTokens);
7582 0 : continue;
7583 : }
7584 17 : if (nSize > 100U * 1024 * 1024 / nDataTypeSize)
7585 : {
7586 0 : CPLDebug("netCDF",
7587 : "nc_def_var(%s) failed: too large data",
7588 : pszVarName);
7589 0 : CSLDestroy(papszTokens);
7590 0 : continue;
7591 : }
7592 17 : if (nTotalVarSize >
7593 34 : std::numeric_limits<size_t>::max() - nSize ||
7594 17 : nTotalVarSize + nSize > 100 * 1024 * 1024)
7595 : {
7596 0 : CPLDebug("netCDF",
7597 : "nc_def_var(%s) failed: too large data",
7598 : pszVarName);
7599 0 : CSLDestroy(papszTokens);
7600 0 : continue;
7601 : }
7602 17 : nTotalVarSize += nSize;
7603 :
7604 17 : int nVarId = -1;
7605 : status =
7606 30 : nc_def_var(nCdfId, pszVarName, nc_datatype, nDims,
7607 13 : (nDims) ? &aoDimIds[0] : nullptr, &nVarId);
7608 17 : if (status != NC_NOERR)
7609 : {
7610 0 : CPLDebug("netCDF", "nc_def_var(%s) failed: %s",
7611 : pszVarName, nc_strerror(status));
7612 : }
7613 : else
7614 : {
7615 : #ifdef DEBUG_VERBOSE
7616 : CPLDebug("netCDF", "nc_def_var(%s) (%s) succeeded",
7617 : pszVarName, pszLine);
7618 : #endif
7619 17 : oMapVarToId[pszVarName] = nVarId;
7620 17 : oMapVarIdToType[nVarId] = nc_datatype;
7621 17 : oMapVarIdToVectorOfDimId[nVarId] = std::move(aoDimIds);
7622 : }
7623 : }
7624 21 : CSLDestroy(papszTokens);
7625 : }
7626 120 : else if (pszEqual != nullptr && pszEqual - pszColumn > 0)
7627 : {
7628 116 : CPLString osVarName(pszLine, pszColumn - pszLine);
7629 116 : CPLString osAttrName(pszColumn + 1, pszEqual - pszColumn - 1);
7630 116 : osAttrName.Trim();
7631 116 : if (oMapVarToId.find(osVarName) == oMapVarToId.end())
7632 : {
7633 0 : CPLDebug("netCDF",
7634 : "nc_put_att(%s:%s) failed: "
7635 : "no corresponding variable",
7636 : osVarName.c_str(), osAttrName.c_str());
7637 0 : continue;
7638 : }
7639 116 : bool bValidName = true;
7640 1743 : for (size_t i = 0; i < osAttrName.size(); i++)
7641 : {
7642 1865 : if (!((osAttrName[i] >= 'a' && osAttrName[i] <= 'z') ||
7643 238 : (osAttrName[i] >= 'A' && osAttrName[i] <= 'Z') ||
7644 158 : (osAttrName[i] >= '0' && osAttrName[i] <= '9') ||
7645 158 : osAttrName[i] == '_'))
7646 : {
7647 0 : bValidName = false;
7648 : }
7649 : }
7650 116 : if (!bValidName)
7651 : {
7652 0 : CPLDebug(
7653 : "netCDF",
7654 : "nc_put_att(%s:%s) failed: illegal character found",
7655 : osVarName.c_str(), osAttrName.c_str());
7656 0 : continue;
7657 : }
7658 116 : if (oSetAttrDefined.find(osVarName + ":" + osAttrName) !=
7659 232 : oSetAttrDefined.end())
7660 : {
7661 0 : CPLDebug("netCDF",
7662 : "nc_put_att(%s:%s) failed: already defined",
7663 : osVarName.c_str(), osAttrName.c_str());
7664 0 : continue;
7665 : }
7666 :
7667 116 : const int nVarId = oMapVarToId[osVarName];
7668 116 : const char *pszValue = pszEqual + 1;
7669 232 : while (*pszValue == ' ')
7670 116 : pszValue++;
7671 :
7672 116 : status = NC_EBADTYPE;
7673 116 : if (*pszValue == '"')
7674 : {
7675 : // For _FillValue, the attribute type should match
7676 : // the variable type. Leaks memory with NC4 otherwise
7677 74 : if (osAttrName == "_FillValue")
7678 : {
7679 0 : CPLDebug("netCDF", "nc_put_att_(%s:%s) failed: %s",
7680 : osVarName.c_str(), osAttrName.c_str(),
7681 : nc_strerror(status));
7682 0 : continue;
7683 : }
7684 :
7685 : // Unquote and unescape string value
7686 74 : CPLString osVal(pszValue + 1);
7687 222 : while (!osVal.empty())
7688 : {
7689 222 : if (osVal.back() == ';' || osVal.back() == ' ')
7690 : {
7691 148 : osVal.pop_back();
7692 : }
7693 74 : else if (osVal.back() == '"')
7694 : {
7695 74 : osVal.pop_back();
7696 74 : break;
7697 : }
7698 : else
7699 : {
7700 0 : break;
7701 : }
7702 : }
7703 74 : osVal.replaceAll("\\\"", '"');
7704 74 : status = nc_put_att_text(nCdfId, nVarId, osAttrName,
7705 : osVal.size(), osVal.c_str());
7706 : }
7707 : else
7708 : {
7709 84 : CPLString osVal(pszValue);
7710 126 : while (!osVal.empty())
7711 : {
7712 126 : if (osVal.back() == ';' || osVal.back() == ' ')
7713 : {
7714 84 : osVal.pop_back();
7715 : }
7716 : else
7717 : {
7718 42 : break;
7719 : }
7720 : }
7721 42 : int nc_datatype = -1;
7722 42 : if (!osVal.empty() && osVal.back() == 'b')
7723 : {
7724 3 : nc_datatype = NC_BYTE;
7725 3 : osVal.pop_back();
7726 : }
7727 39 : else if (!osVal.empty() && osVal.back() == 's')
7728 : {
7729 3 : nc_datatype = NC_SHORT;
7730 3 : osVal.pop_back();
7731 : }
7732 42 : if (CPLGetValueType(osVal) == CPL_VALUE_INTEGER)
7733 : {
7734 7 : if (nc_datatype < 0)
7735 4 : nc_datatype = NC_INT;
7736 : }
7737 35 : else if (CPLGetValueType(osVal) == CPL_VALUE_REAL)
7738 : {
7739 32 : nc_datatype = NC_DOUBLE;
7740 : }
7741 : else
7742 : {
7743 3 : nc_datatype = -1;
7744 : }
7745 :
7746 : // For _FillValue, check that the attribute type matches
7747 : // the variable type. Leaks memory with NC4 otherwise
7748 42 : if (osAttrName == "_FillValue")
7749 : {
7750 6 : if (nVarId < 0 ||
7751 3 : nc_datatype != oMapVarIdToType[nVarId])
7752 : {
7753 0 : nc_datatype = -1;
7754 : }
7755 : }
7756 :
7757 42 : if (nc_datatype == NC_BYTE)
7758 : {
7759 : signed char chVal =
7760 3 : static_cast<signed char>(atoi(osVal));
7761 3 : status = nc_put_att_schar(nCdfId, nVarId, osAttrName,
7762 : NC_BYTE, 1, &chVal);
7763 : }
7764 39 : else if (nc_datatype == NC_SHORT)
7765 : {
7766 0 : short nVal = static_cast<short>(atoi(osVal));
7767 0 : status = nc_put_att_short(nCdfId, nVarId, osAttrName,
7768 : NC_SHORT, 1, &nVal);
7769 : }
7770 39 : else if (nc_datatype == NC_INT)
7771 : {
7772 4 : int nVal = static_cast<int>(atoi(osVal));
7773 4 : status = nc_put_att_int(nCdfId, nVarId, osAttrName,
7774 : NC_INT, 1, &nVal);
7775 : }
7776 35 : else if (nc_datatype == NC_DOUBLE)
7777 : {
7778 32 : double dfVal = CPLAtof(osVal);
7779 32 : status = nc_put_att_double(nCdfId, nVarId, osAttrName,
7780 : NC_DOUBLE, 1, &dfVal);
7781 : }
7782 : }
7783 116 : if (status != NC_NOERR)
7784 : {
7785 3 : CPLDebug("netCDF", "nc_put_att_(%s:%s) failed: %s",
7786 : osVarName.c_str(), osAttrName.c_str(),
7787 : nc_strerror(status));
7788 : }
7789 : else
7790 : {
7791 113 : oSetAttrDefined.insert(osVarName + ":" + osAttrName);
7792 : #ifdef DEBUG_VERBOSE
7793 : CPLDebug("netCDF", "nc_put_att_(%s:%s) (%s) succeeded",
7794 : osVarName.c_str(), osAttrName.c_str(), pszLine);
7795 : #endif
7796 : }
7797 : }
7798 : }
7799 42 : else if (nActiveSection == SECTION_DATA)
7800 : {
7801 55 : while (*pszLine == ' ' || *pszLine == '\t')
7802 17 : pszLine++;
7803 38 : const char *pszEqual = strchr(pszLine, '=');
7804 38 : if (pszEqual)
7805 : {
7806 17 : CPLString osVarName(pszLine, pszEqual - pszLine);
7807 17 : osVarName.Trim();
7808 17 : if (oMapVarToId.find(osVarName) == oMapVarToId.end())
7809 0 : continue;
7810 17 : const int nVarId = oMapVarToId[osVarName];
7811 17 : CPLString osAccVal(pszEqual + 1);
7812 17 : osAccVal.Trim();
7813 153 : while (osAccVal.empty() || osAccVal.back() != ';')
7814 : {
7815 136 : pszLine = CPLReadLineL(fpSrc);
7816 136 : if (pszLine == nullptr)
7817 0 : break;
7818 272 : CPLString osVal(pszLine);
7819 136 : osVal.Trim();
7820 136 : osAccVal += osVal;
7821 : }
7822 17 : if (pszLine == nullptr)
7823 0 : break;
7824 17 : osAccVal.pop_back();
7825 :
7826 : const std::vector<int> aoDimIds =
7827 34 : oMapVarIdToVectorOfDimId[nVarId];
7828 17 : size_t nSize = 1;
7829 34 : std::vector<size_t> aoStart, aoEdge;
7830 17 : aoStart.resize(aoDimIds.size());
7831 17 : aoEdge.resize(aoDimIds.size());
7832 35 : for (size_t i = 0; i < aoDimIds.size(); ++i)
7833 : {
7834 18 : const size_t nDimSize = oMapDimIdToDimLen[aoDimIds[i]];
7835 36 : if (nDimSize != 0 &&
7836 18 : nSize > std::numeric_limits<size_t>::max() / nDimSize)
7837 : {
7838 0 : nSize = 0;
7839 : }
7840 : else
7841 : {
7842 18 : nSize *= nDimSize;
7843 : }
7844 18 : aoStart[i] = 0;
7845 18 : aoEdge[i] = nDimSize;
7846 : }
7847 :
7848 17 : status = NC_EBADTYPE;
7849 17 : if (nSize == 0)
7850 : {
7851 : // Might happen with a unlimited dimension
7852 : }
7853 17 : else if (oMapVarIdToType[nVarId] == NC_DOUBLE)
7854 : {
7855 8 : if (!aoStart.empty())
7856 : {
7857 : char **papszTokens =
7858 8 : CSLTokenizeString2(osAccVal, " ,;", 0);
7859 8 : size_t nTokens = CSLCount(papszTokens);
7860 8 : if (nTokens >= nSize)
7861 : {
7862 : double *padfVals = static_cast<double *>(
7863 8 : VSI_CALLOC_VERBOSE(nSize, sizeof(double)));
7864 8 : if (padfVals)
7865 : {
7866 132 : for (size_t i = 0; i < nSize; i++)
7867 : {
7868 124 : padfVals[i] = CPLAtof(papszTokens[i]);
7869 : }
7870 8 : status = nc_put_vara_double(
7871 8 : nCdfId, nVarId, &aoStart[0], &aoEdge[0],
7872 : padfVals);
7873 8 : VSIFree(padfVals);
7874 : }
7875 : }
7876 8 : CSLDestroy(papszTokens);
7877 : }
7878 : }
7879 9 : else if (oMapVarIdToType[nVarId] == NC_BYTE)
7880 : {
7881 3 : if (!aoStart.empty())
7882 : {
7883 : char **papszTokens =
7884 3 : CSLTokenizeString2(osAccVal, " ,;", 0);
7885 3 : size_t nTokens = CSLCount(papszTokens);
7886 3 : if (nTokens >= nSize)
7887 : {
7888 : signed char *panVals = static_cast<signed char *>(
7889 3 : VSI_CALLOC_VERBOSE(nSize, sizeof(signed char)));
7890 3 : if (panVals)
7891 : {
7892 1203 : for (size_t i = 0; i < nSize; i++)
7893 : {
7894 1200 : panVals[i] = static_cast<signed char>(
7895 1200 : atoi(papszTokens[i]));
7896 : }
7897 3 : status = nc_put_vara_schar(nCdfId, nVarId,
7898 3 : &aoStart[0],
7899 3 : &aoEdge[0], panVals);
7900 3 : VSIFree(panVals);
7901 : }
7902 : }
7903 3 : CSLDestroy(papszTokens);
7904 : }
7905 : }
7906 6 : else if (oMapVarIdToType[nVarId] == NC_CHAR)
7907 : {
7908 6 : if (aoStart.size() == 2)
7909 : {
7910 4 : std::vector<CPLString> aoStrings;
7911 2 : bool bInString = false;
7912 4 : CPLString osCurString;
7913 935 : for (size_t i = 0; i < osAccVal.size();)
7914 : {
7915 933 : if (!bInString)
7916 : {
7917 8 : if (osAccVal[i] == '"')
7918 : {
7919 4 : bInString = true;
7920 4 : osCurString.clear();
7921 : }
7922 8 : i++;
7923 : }
7924 926 : else if (osAccVal[i] == '\\' &&
7925 926 : i + 1 < osAccVal.size() &&
7926 1 : osAccVal[i + 1] == '"')
7927 : {
7928 1 : osCurString += '"';
7929 1 : i += 2;
7930 : }
7931 924 : else if (osAccVal[i] == '"')
7932 : {
7933 4 : aoStrings.push_back(osCurString);
7934 4 : osCurString.clear();
7935 4 : bInString = false;
7936 4 : i++;
7937 : }
7938 : else
7939 : {
7940 920 : osCurString += osAccVal[i];
7941 920 : i++;
7942 : }
7943 : }
7944 2 : const size_t nRecords = oMapDimIdToDimLen[aoDimIds[0]];
7945 2 : const size_t nWidth = oMapDimIdToDimLen[aoDimIds[1]];
7946 2 : size_t nIters = aoStrings.size();
7947 2 : if (nIters > nRecords)
7948 0 : nIters = nRecords;
7949 6 : for (size_t i = 0; i < nIters; i++)
7950 : {
7951 : size_t anIndex[2];
7952 4 : anIndex[0] = i;
7953 4 : anIndex[1] = 0;
7954 : size_t anCount[2];
7955 4 : anCount[0] = 1;
7956 4 : anCount[1] = aoStrings[i].size();
7957 4 : if (anCount[1] > nWidth)
7958 0 : anCount[1] = nWidth;
7959 : status =
7960 4 : nc_put_vara_text(nCdfId, nVarId, anIndex,
7961 4 : anCount, aoStrings[i].c_str());
7962 4 : if (status != NC_NOERR)
7963 0 : break;
7964 : }
7965 : }
7966 : }
7967 17 : if (status != NC_NOERR)
7968 : {
7969 4 : CPLDebug("netCDF", "nc_put_var_(%s) failed: %s",
7970 : osVarName.c_str(), nc_strerror(status));
7971 : }
7972 : }
7973 : }
7974 : }
7975 :
7976 4 : GDAL_nc_close(nCdfId);
7977 4 : return true;
7978 : }
7979 :
7980 : #endif // ENABLE_NCDUMP
7981 :
7982 : /************************************************************************/
7983 : /* Open() */
7984 : /************************************************************************/
7985 :
7986 663 : GDALDataset *netCDFDataset::Open(GDALOpenInfo *poOpenInfo)
7987 :
7988 : {
7989 : #ifdef NCDF_DEBUG
7990 : CPLDebug("GDAL_netCDF", "\n=====\nOpen(), filename=[%s]",
7991 : poOpenInfo->pszFilename);
7992 : #endif
7993 :
7994 : // Does this appear to be a netcdf file?
7995 663 : NetCDFFormatEnum eTmpFormat = NCDF_FORMAT_NONE;
7996 663 : if (!STARTS_WITH_CI(poOpenInfo->pszFilename, "NETCDF:"))
7997 : {
7998 604 : eTmpFormat = netCDFIdentifyFormat(poOpenInfo, /* bCheckExt = */ true);
7999 : #ifdef NCDF_DEBUG
8000 : CPLDebug("GDAL_netCDF", "identified format %d", eTmpFormat);
8001 : #endif
8002 : // Note: not calling Identify() directly, because we want the file type.
8003 : // Only support NCDF_FORMAT* formats.
8004 604 : if (NCDF_FORMAT_NC == eTmpFormat || NCDF_FORMAT_NC2 == eTmpFormat ||
8005 2 : NCDF_FORMAT_NC4 == eTmpFormat || NCDF_FORMAT_NC4C == eTmpFormat)
8006 : {
8007 : // ok
8008 : }
8009 2 : else if (eTmpFormat == NCDF_FORMAT_HDF4 &&
8010 0 : poOpenInfo->IsSingleAllowedDriver("netCDF"))
8011 : {
8012 : // ok
8013 : }
8014 : else
8015 : {
8016 2 : return nullptr;
8017 : }
8018 : }
8019 : else
8020 : {
8021 : #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
8022 : // We don't necessarily want to catch bugs in libnetcdf ...
8023 : if (CPLGetConfigOption("DISABLE_OPEN_REAL_NETCDF_FILES", nullptr))
8024 : {
8025 : return nullptr;
8026 : }
8027 : #endif
8028 : }
8029 :
8030 661 : if (poOpenInfo->nOpenFlags & GDAL_OF_MULTIDIM_RASTER)
8031 : {
8032 173 : return OpenMultiDim(poOpenInfo);
8033 : }
8034 :
8035 976 : CPLMutexHolderD(&hNCMutex);
8036 :
8037 488 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll deadlock with
8038 : // GDALDataset own mutex.
8039 488 : netCDFDataset *poDS = new netCDFDataset();
8040 488 : poDS->papszOpenOptions = CSLDuplicate(poOpenInfo->papszOpenOptions);
8041 488 : CPLAcquireMutex(hNCMutex, 1000.0);
8042 :
8043 488 : poDS->SetDescription(poOpenInfo->pszFilename);
8044 :
8045 : // Check if filename start with NETCDF: tag.
8046 488 : bool bTreatAsSubdataset = false;
8047 976 : CPLString osSubdatasetName;
8048 :
8049 : #ifdef ENABLE_NCDUMP
8050 488 : const char *pszHeader =
8051 : reinterpret_cast<const char *>(poOpenInfo->pabyHeader);
8052 488 : if (poOpenInfo->fpL != nullptr && STARTS_WITH(pszHeader, "netcdf ") &&
8053 3 : strstr(pszHeader, "dimensions:") && strstr(pszHeader, "variables:"))
8054 : {
8055 : // By default create a temporary file that will be destroyed,
8056 : // unless NETCDF_TMP_FILE is defined. Can be useful to see which
8057 : // netCDF file has been generated from a potential fuzzed input.
8058 3 : poDS->osFilename = CPLGetConfigOption("NETCDF_TMP_FILE", "");
8059 3 : if (poDS->osFilename.empty())
8060 : {
8061 3 : poDS->bFileToDestroyAtClosing = true;
8062 3 : poDS->osFilename = CPLGenerateTempFilenameSafe("netcdf_tmp");
8063 : }
8064 3 : if (!netCDFDatasetCreateTempFile(eTmpFormat, poDS->osFilename,
8065 : poOpenInfo->fpL))
8066 : {
8067 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll
8068 : // deadlock with GDALDataset own mutex.
8069 0 : delete poDS;
8070 0 : CPLAcquireMutex(hNCMutex, 1000.0);
8071 0 : return nullptr;
8072 : }
8073 3 : bTreatAsSubdataset = false;
8074 3 : poDS->eFormat = eTmpFormat;
8075 : }
8076 : else
8077 : #endif
8078 :
8079 485 : if (STARTS_WITH_CI(poOpenInfo->pszFilename, "NETCDF:"))
8080 : {
8081 : char **papszName =
8082 59 : CSLTokenizeString2(poOpenInfo->pszFilename, ":",
8083 : CSLT_HONOURSTRINGS | CSLT_PRESERVEESCAPES);
8084 :
8085 118 : if (CSLCount(papszName) >= 3 &&
8086 59 : ((strlen(papszName[1]) == 1 && /* D:\\bla */
8087 0 : (papszName[2][0] == '/' || papszName[2][0] == '\\')) ||
8088 59 : EQUAL(papszName[1], "http") || EQUAL(papszName[1], "https") ||
8089 59 : EQUAL(papszName[1], "/vsicurl/http") ||
8090 59 : EQUAL(papszName[1], "/vsicurl/https") ||
8091 59 : EQUAL(papszName[1], "/vsicurl_streaming/http") ||
8092 59 : EQUAL(papszName[1], "/vsicurl_streaming/https")))
8093 : {
8094 0 : const int nCountBefore = CSLCount(papszName);
8095 0 : CPLString osTmp = papszName[1];
8096 0 : osTmp += ':';
8097 0 : osTmp += papszName[2];
8098 0 : CPLFree(papszName[1]);
8099 0 : CPLFree(papszName[2]);
8100 0 : papszName[1] = CPLStrdup(osTmp);
8101 0 : memmove(papszName + 2, papszName + 3,
8102 0 : (nCountBefore - 2) * sizeof(char *));
8103 : }
8104 :
8105 59 : if (CSLCount(papszName) == 3)
8106 : {
8107 59 : poDS->osFilename = papszName[1];
8108 59 : osSubdatasetName = papszName[2];
8109 59 : bTreatAsSubdataset = true;
8110 59 : CSLDestroy(papszName);
8111 : }
8112 0 : else if (CSLCount(papszName) == 2)
8113 : {
8114 0 : poDS->osFilename = papszName[1];
8115 0 : osSubdatasetName = "";
8116 0 : bTreatAsSubdataset = false;
8117 0 : CSLDestroy(papszName);
8118 : }
8119 : else
8120 : {
8121 0 : CSLDestroy(papszName);
8122 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll
8123 : // deadlock with GDALDataset own mutex.
8124 0 : delete poDS;
8125 0 : CPLAcquireMutex(hNCMutex, 1000.0);
8126 0 : CPLError(CE_Failure, CPLE_AppDefined,
8127 : "Failed to parse NETCDF: prefix string into expected 2, 3 "
8128 : "or 4 fields.");
8129 0 : return nullptr;
8130 : }
8131 :
8132 118 : if (!STARTS_WITH(poDS->osFilename, "http://") &&
8133 59 : !STARTS_WITH(poDS->osFilename, "https://"))
8134 : {
8135 : // Identify Format from real file, with bCheckExt=FALSE.
8136 : GDALOpenInfo *poOpenInfo2 =
8137 59 : new GDALOpenInfo(poDS->osFilename.c_str(), GA_ReadOnly);
8138 59 : poDS->eFormat =
8139 59 : netCDFIdentifyFormat(poOpenInfo2, /* bCheckExt = */ false);
8140 59 : delete poOpenInfo2;
8141 59 : if (NCDF_FORMAT_NONE == poDS->eFormat ||
8142 59 : NCDF_FORMAT_UNKNOWN == poDS->eFormat)
8143 : {
8144 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll
8145 : // deadlock with GDALDataset own mutex.
8146 0 : delete poDS;
8147 0 : CPLAcquireMutex(hNCMutex, 1000.0);
8148 0 : return nullptr;
8149 : }
8150 : }
8151 : }
8152 : else
8153 : {
8154 426 : poDS->osFilename = poOpenInfo->pszFilename;
8155 426 : bTreatAsSubdataset = false;
8156 426 : poDS->eFormat = eTmpFormat;
8157 : }
8158 :
8159 : // Try opening the dataset.
8160 : #if defined(NCDF_DEBUG) && defined(ENABLE_UFFD)
8161 : CPLDebug("GDAL_netCDF", "calling nc_open_mem(%s)",
8162 : poDS->osFilename.c_str());
8163 : #elif defined(NCDF_DEBUG) && !defined(ENABLE_UFFD)
8164 : CPLDebug("GDAL_netCDF", "calling nc_open(%s)", poDS->osFilename.c_str());
8165 : #endif
8166 488 : int cdfid = -1;
8167 488 : const int nMode = ((poOpenInfo->nOpenFlags & GDAL_OF_UPDATE) != 0)
8168 : ? NC_WRITE
8169 : : NC_NOWRITE;
8170 976 : CPLString osFilenameForNCOpen(poDS->osFilename);
8171 : #if defined(_WIN32) && !defined(NETCDF_USES_UTF8)
8172 : if (CPLTestBool(CPLGetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")))
8173 : {
8174 : char *pszTemp = CPLRecode(osFilenameForNCOpen, CPL_ENC_UTF8, "CP_ACP");
8175 : osFilenameForNCOpen = pszTemp;
8176 : CPLFree(pszTemp);
8177 : }
8178 : #endif
8179 488 : int status2 = -1;
8180 :
8181 : #ifdef ENABLE_UFFD
8182 488 : cpl_uffd_context *pCtx = nullptr;
8183 : #endif
8184 :
8185 503 : if (STARTS_WITH(osFilenameForNCOpen, "/vsimem/") &&
8186 15 : poOpenInfo->eAccess == GA_ReadOnly)
8187 : {
8188 15 : vsi_l_offset nLength = 0;
8189 15 : poDS->fpVSIMEM = VSIFOpenL(osFilenameForNCOpen, "rb");
8190 15 : if (poDS->fpVSIMEM)
8191 : {
8192 : // We assume that the file will not be modified. If it is, then
8193 : // pabyBuffer might become invalid.
8194 : GByte *pabyBuffer =
8195 15 : VSIGetMemFileBuffer(osFilenameForNCOpen, &nLength, false);
8196 15 : if (pabyBuffer)
8197 : {
8198 15 : status2 = nc_open_mem(CPLGetFilename(osFilenameForNCOpen),
8199 : nMode, static_cast<size_t>(nLength),
8200 : pabyBuffer, &cdfid);
8201 : }
8202 : }
8203 : }
8204 : else
8205 : {
8206 : const bool bVsiFile =
8207 473 : !strncmp(osFilenameForNCOpen, "/vsi", strlen("/vsi"));
8208 : #ifdef ENABLE_UFFD
8209 473 : bool bReadOnly = (poOpenInfo->eAccess == GA_ReadOnly);
8210 473 : void *pVma = nullptr;
8211 473 : uint64_t nVmaSize = 0;
8212 :
8213 473 : if (bVsiFile)
8214 : {
8215 2 : if (bReadOnly)
8216 : {
8217 2 : if (CPLIsUserFaultMappingSupported())
8218 : {
8219 2 : pCtx = CPLCreateUserFaultMapping(osFilenameForNCOpen, &pVma,
8220 : &nVmaSize);
8221 : }
8222 : else
8223 : {
8224 0 : CPLError(CE_Failure, CPLE_AppDefined,
8225 : "Opening a /vsi file with the netCDF driver "
8226 : "requires Linux userfaultfd to be available. "
8227 : "If running from Docker, "
8228 : "--security-opt seccomp=unconfined might be "
8229 : "needed.%s",
8230 0 : ((poDS->eFormat == NCDF_FORMAT_NC4 ||
8231 0 : poDS->eFormat == NCDF_FORMAT_HDF5) &&
8232 0 : GDALGetDriverByName("HDF5"))
8233 : ? " Or you may set the GDAL_SKIP=netCDF "
8234 : "configuration option to force the use of "
8235 : "the HDF5 driver."
8236 : : "");
8237 : }
8238 : }
8239 : else
8240 : {
8241 0 : CPLError(CE_Failure, CPLE_AppDefined,
8242 : "Opening a /vsi file with the netCDF driver is only "
8243 : "supported in read-only mode");
8244 : }
8245 : }
8246 473 : if (pCtx != nullptr && pVma != nullptr && nVmaSize > 0)
8247 : {
8248 : // netCDF code, at least for netCDF 4.7.0, is confused by filenames
8249 : // like /vsicurl/http[s]://example.com/foo.nc, so just pass the
8250 : // final part
8251 2 : status2 = nc_open_mem(CPLGetFilename(osFilenameForNCOpen), nMode,
8252 : static_cast<size_t>(nVmaSize), pVma, &cdfid);
8253 : }
8254 : else
8255 471 : status2 = GDAL_nc_open(osFilenameForNCOpen, nMode, &cdfid);
8256 : #else
8257 : if (bVsiFile)
8258 : {
8259 : CPLError(
8260 : CE_Failure, CPLE_AppDefined,
8261 : "Opening a /vsi file with the netCDF driver requires Linux "
8262 : "userfaultfd to be available.%s",
8263 : ((poDS->eFormat == NCDF_FORMAT_NC4 ||
8264 : poDS->eFormat == NCDF_FORMAT_HDF5) &&
8265 : GDALGetDriverByName("HDF5"))
8266 : ? " Or you may set the GDAL_SKIP=netCDF "
8267 : "configuration option to force the use of the HDF5 "
8268 : "driver."
8269 : : "");
8270 : status2 = NC_EIO;
8271 : }
8272 : else
8273 : {
8274 : status2 = GDAL_nc_open(osFilenameForNCOpen, nMode, &cdfid);
8275 : }
8276 : #endif
8277 : }
8278 488 : if (status2 != NC_NOERR)
8279 : {
8280 : #ifdef NCDF_DEBUG
8281 : CPLDebug("GDAL_netCDF", "error opening");
8282 : #endif
8283 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll deadlock
8284 : // with GDALDataset own mutex.
8285 0 : delete poDS;
8286 0 : CPLAcquireMutex(hNCMutex, 1000.0);
8287 0 : return nullptr;
8288 : }
8289 : #ifdef NCDF_DEBUG
8290 : CPLDebug("GDAL_netCDF", "got cdfid=%d", cdfid);
8291 : #endif
8292 :
8293 : #if defined(ENABLE_NCDUMP) && !defined(_WIN32)
8294 : // Try to destroy the temporary file right now on Unix
8295 488 : if (poDS->bFileToDestroyAtClosing)
8296 : {
8297 3 : if (VSIUnlink(poDS->osFilename) == 0)
8298 : {
8299 3 : poDS->bFileToDestroyAtClosing = false;
8300 : }
8301 : }
8302 : #endif
8303 :
8304 : // Is this a real netCDF file?
8305 : int ndims;
8306 : int ngatts;
8307 : int nvars;
8308 : int unlimdimid;
8309 488 : int status = nc_inq(cdfid, &ndims, &nvars, &ngatts, &unlimdimid);
8310 488 : if (status != NC_NOERR)
8311 : {
8312 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll deadlock
8313 : // with GDALDataset own mutex.
8314 0 : delete poDS;
8315 0 : CPLAcquireMutex(hNCMutex, 1000.0);
8316 0 : return nullptr;
8317 : }
8318 :
8319 : // Get file type from netcdf.
8320 488 : int nTmpFormat = NCDF_FORMAT_NONE;
8321 488 : status = nc_inq_format(cdfid, &nTmpFormat);
8322 488 : if (status != NC_NOERR)
8323 : {
8324 0 : NCDF_ERR(status);
8325 : }
8326 : else
8327 : {
8328 488 : CPLDebug("GDAL_netCDF",
8329 : "driver detected file type=%d, libnetcdf detected type=%d",
8330 488 : poDS->eFormat, nTmpFormat);
8331 488 : if (static_cast<NetCDFFormatEnum>(nTmpFormat) != poDS->eFormat)
8332 : {
8333 : // Warn if file detection conflicts with that from libnetcdf
8334 : // except for NC4C, which we have no way of detecting initially.
8335 24 : if (nTmpFormat != NCDF_FORMAT_NC4C &&
8336 12 : !STARTS_WITH(poDS->osFilename, "http://") &&
8337 0 : !STARTS_WITH(poDS->osFilename, "https://"))
8338 : {
8339 0 : CPLError(CE_Warning, CPLE_AppDefined,
8340 : "NetCDF driver detected file type=%d, but libnetcdf "
8341 : "detected type=%d",
8342 0 : poDS->eFormat, nTmpFormat);
8343 : }
8344 12 : CPLDebug("GDAL_netCDF", "setting file type to %d, was %d",
8345 12 : nTmpFormat, poDS->eFormat);
8346 12 : poDS->eFormat = static_cast<NetCDFFormatEnum>(nTmpFormat);
8347 : }
8348 : }
8349 :
8350 : // Does the request variable exist?
8351 488 : if (bTreatAsSubdataset)
8352 : {
8353 : int dummy;
8354 59 : if (NCDFOpenSubDataset(cdfid, osSubdatasetName.c_str(), &dummy,
8355 59 : &dummy) != CE_None)
8356 : {
8357 0 : CPLError(CE_Warning, CPLE_AppDefined,
8358 : "%s is a netCDF file, but %s is not a variable.",
8359 : poOpenInfo->pszFilename, osSubdatasetName.c_str());
8360 :
8361 0 : GDAL_nc_close(cdfid);
8362 : #ifdef ENABLE_UFFD
8363 0 : NETCDF_UFFD_UNMAP(pCtx);
8364 : #endif
8365 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll
8366 : // deadlock with GDALDataset own mutex.
8367 0 : delete poDS;
8368 0 : CPLAcquireMutex(hNCMutex, 1000.0);
8369 0 : return nullptr;
8370 : }
8371 : }
8372 :
8373 : // Figure out whether or not the listed dataset has support for simple
8374 : // geometries (CF-1.8)
8375 488 : poDS->nCFVersion = nccfdriver::getCFVersion(cdfid);
8376 488 : bool bHasSimpleGeometries = false; // but not necessarily valid
8377 488 : if (poDS->nCFVersion >= 1.8)
8378 : {
8379 75 : bHasSimpleGeometries = poDS->DetectAndFillSGLayers(cdfid);
8380 75 : if (bHasSimpleGeometries)
8381 : {
8382 67 : poDS->bSGSupport = true;
8383 67 : poDS->vcdf.enableFullVirtualMode();
8384 : }
8385 : }
8386 :
8387 : char szConventions[NC_MAX_NAME + 1];
8388 488 : szConventions[0] = '\0';
8389 488 : nc_type nAttype = NC_NAT;
8390 488 : size_t nAttlen = 0;
8391 488 : nc_inq_att(cdfid, NC_GLOBAL, "Conventions", &nAttype, &nAttlen);
8392 976 : if (nAttlen >= sizeof(szConventions) ||
8393 488 : nc_get_att_text(cdfid, NC_GLOBAL, "Conventions", szConventions) !=
8394 : NC_NOERR)
8395 : {
8396 56 : CPLDebug("GDAL_netCDF", "No UNIDATA NC_GLOBAL:Conventions attribute");
8397 : // Note that 'Conventions' is always capital 'C' in CF spec.
8398 : }
8399 : else
8400 : {
8401 432 : szConventions[nAttlen] = '\0';
8402 : }
8403 :
8404 : // Create band information objects.
8405 488 : CPLDebug("GDAL_netCDF", "var_count = %d", nvars);
8406 :
8407 : // Create a corresponding GDALDataset.
8408 : // Create Netcdf Subdataset if filename as NETCDF tag.
8409 488 : poDS->cdfid = cdfid;
8410 : #ifdef ENABLE_UFFD
8411 488 : poDS->pCtx = pCtx;
8412 : #endif
8413 488 : poDS->eAccess = poOpenInfo->eAccess;
8414 488 : poDS->bDefineMode = false;
8415 :
8416 488 : poDS->ReadAttributes(cdfid, NC_GLOBAL);
8417 :
8418 : // Identify coordinate and boundary variables that we should
8419 : // ignore as Raster Bands.
8420 488 : char **papszIgnoreVars = nullptr;
8421 488 : NCDFGetCoordAndBoundVarFullNames(cdfid, &papszIgnoreVars);
8422 : // Filter variables to keep only valid 2+D raster bands and vector fields.
8423 488 : int nRasterVars = 0;
8424 488 : int nIgnoredVars = 0;
8425 488 : int nGroupID = -1;
8426 488 : int nVarID = -1;
8427 :
8428 : std::map<std::array<int, 3>, std::vector<std::pair<int, int>>>
8429 976 : oMap2DDimsToGroupAndVar;
8430 1126 : if ((poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
8431 150 : STARTS_WITH(CSLFetchNameValueDef(poDS->papszMetadata,
8432 : "NC_GLOBAL#mission_name", ""),
8433 1 : "Sentinel 3") &&
8434 1 : EQUAL(CSLFetchNameValueDef(poDS->papszMetadata,
8435 : "NC_GLOBAL#altimeter_sensor_name", ""),
8436 638 : "SRAL") &&
8437 1 : EQUAL(CSLFetchNameValueDef(poDS->papszMetadata,
8438 : "NC_GLOBAL#radiometer_sensor_name", ""),
8439 : "MWR"))
8440 : {
8441 1 : if (poDS->eAccess == GA_Update)
8442 : {
8443 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll
8444 : // deadlock with GDALDataset own mutex.
8445 0 : delete poDS;
8446 0 : return nullptr;
8447 : }
8448 1 : poDS->ProcessSentinel3_SRAL_MWR();
8449 : }
8450 : else
8451 : {
8452 487 : poDS->FilterVars(cdfid, (poOpenInfo->nOpenFlags & GDAL_OF_RASTER) != 0,
8453 636 : (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
8454 149 : !bHasSimpleGeometries,
8455 : papszIgnoreVars, &nRasterVars, &nGroupID, &nVarID,
8456 : &nIgnoredVars, oMap2DDimsToGroupAndVar);
8457 : }
8458 488 : CSLDestroy(papszIgnoreVars);
8459 :
8460 : // Case where there is no raster variable
8461 488 : if (nRasterVars == 0 && !bTreatAsSubdataset)
8462 : {
8463 119 : poDS->GDALPamDataset::SetMetadata(poDS->papszMetadata);
8464 119 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll deadlock
8465 : // with GDALDataset own mutex.
8466 119 : poDS->TryLoadXML();
8467 : // If the dataset has been opened in raster mode only, exit
8468 119 : if ((poOpenInfo->nOpenFlags & GDAL_OF_RASTER) != 0 &&
8469 9 : (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) == 0)
8470 : {
8471 4 : delete poDS;
8472 4 : poDS = nullptr;
8473 : }
8474 : // Otherwise if the dataset is opened in vector mode, that there is
8475 : // no vector layer and we are in read-only, exit too.
8476 115 : else if (poDS->GetLayerCount() == 0 &&
8477 123 : (poOpenInfo->nOpenFlags & GDAL_OF_VECTOR) != 0 &&
8478 8 : poOpenInfo->eAccess == GA_ReadOnly)
8479 : {
8480 8 : delete poDS;
8481 8 : poDS = nullptr;
8482 : }
8483 119 : CPLAcquireMutex(hNCMutex, 1000.0);
8484 119 : return poDS;
8485 : }
8486 :
8487 : // We have more than one variable with 2 dimensions in the
8488 : // file, then treat this as a subdataset container dataset.
8489 369 : bool bSeveralVariablesAsBands = false;
8490 369 : if ((nRasterVars > 1) && !bTreatAsSubdataset)
8491 : {
8492 27 : if (CPLFetchBool(poOpenInfo->papszOpenOptions, "VARIABLES_AS_BANDS",
8493 33 : false) &&
8494 6 : oMap2DDimsToGroupAndVar.size() == 1)
8495 : {
8496 6 : std::tie(nGroupID, nVarID) =
8497 12 : oMap2DDimsToGroupAndVar.begin()->second.front();
8498 6 : bSeveralVariablesAsBands = true;
8499 : }
8500 : else
8501 : {
8502 21 : poDS->CreateSubDatasetList(cdfid);
8503 21 : poDS->GDALPamDataset::SetMetadata(poDS->papszMetadata);
8504 21 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll
8505 : // deadlock with GDALDataset own mutex.
8506 21 : poDS->TryLoadXML();
8507 21 : CPLAcquireMutex(hNCMutex, 1000.0);
8508 21 : return poDS;
8509 : }
8510 : }
8511 :
8512 : // If we are not treating things as a subdataset, then capture
8513 : // the name of the single available variable as the subdataset.
8514 348 : if (!bTreatAsSubdataset)
8515 : {
8516 289 : char *pszVarName = nullptr;
8517 289 : NCDF_ERR(NCDFGetVarFullName(nGroupID, nVarID, &pszVarName));
8518 289 : osSubdatasetName = (pszVarName != nullptr ? pszVarName : "");
8519 289 : CPLFree(pszVarName);
8520 : }
8521 :
8522 : // We have ignored at least one variable, so we should report them
8523 : // as subdatasets for reference.
8524 348 : if (nIgnoredVars > 0 && !bTreatAsSubdataset)
8525 : {
8526 24 : CPLDebug("GDAL_netCDF",
8527 : "As %d variables were ignored, creating subdataset list "
8528 : "for reference. Variable #%d [%s] is the main variable",
8529 : nIgnoredVars, nVarID, osSubdatasetName.c_str());
8530 24 : poDS->CreateSubDatasetList(cdfid);
8531 : }
8532 :
8533 : // Open the NETCDF subdataset NETCDF:"filename":subdataset.
8534 348 : int var = -1;
8535 348 : NCDFOpenSubDataset(cdfid, osSubdatasetName.c_str(), &nGroupID, &var);
8536 : // Now we can forget the root cdfid and only use the selected group.
8537 348 : cdfid = nGroupID;
8538 348 : int nd = 0;
8539 348 : nc_inq_varndims(cdfid, var, &nd);
8540 :
8541 348 : poDS->m_anDimIds.resize(nd);
8542 :
8543 : // X, Y, Z position in array
8544 696 : std::vector<int> anBandDimPos(nd);
8545 :
8546 348 : nc_inq_vardimid(cdfid, var, poDS->m_anDimIds.data());
8547 :
8548 : // Check if somebody tried to pass a variable with less than 1D.
8549 348 : if (nd < 1)
8550 : {
8551 0 : CPLError(CE_Warning, CPLE_AppDefined,
8552 : "Variable has %d dimension(s) - not supported.", nd);
8553 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll deadlock
8554 : // with GDALDataset own mutex.
8555 0 : delete poDS;
8556 0 : CPLAcquireMutex(hNCMutex, 1000.0);
8557 0 : return nullptr;
8558 : }
8559 :
8560 : // CF-1 Convention
8561 : //
8562 : // Dimensions to appear in the relative order T, then Z, then Y,
8563 : // then X to the file. All other dimensions should, whenever
8564 : // possible, be placed to the left of the spatiotemporal
8565 : // dimensions.
8566 :
8567 : // Verify that dimensions are in the {T,Z,Y,X} or {T,Z,Y,X} order
8568 : // Ideally we should detect for other ordering and act accordingly
8569 : // Only done if file has Conventions=CF-* and only prints warning
8570 : // To disable set GDAL_NETCDF_VERIFY_DIMS=NO and to use only
8571 : // attributes (not varnames) set GDAL_NETCDF_VERIFY_DIMS=STRICT
8572 : const bool bCheckDims =
8573 696 : CPLTestBool(CPLGetConfigOption("GDAL_NETCDF_VERIFY_DIMS", "YES")) &&
8574 348 : STARTS_WITH_CI(szConventions, "CF");
8575 :
8576 348 : if (nd >= 2 && bCheckDims)
8577 : {
8578 264 : char szDimName1[NC_MAX_NAME + 1] = {};
8579 264 : char szDimName2[NC_MAX_NAME + 1] = {};
8580 264 : status = nc_inq_dimname(cdfid, poDS->m_anDimIds[nd - 1], szDimName1);
8581 264 : NCDF_ERR(status);
8582 264 : status = nc_inq_dimname(cdfid, poDS->m_anDimIds[nd - 2], szDimName2);
8583 264 : NCDF_ERR(status);
8584 420 : if (NCDFIsVarLongitude(cdfid, -1, szDimName1) == false &&
8585 156 : NCDFIsVarProjectionX(cdfid, -1, szDimName1) == false)
8586 : {
8587 4 : CPLError(CE_Warning, CPLE_AppDefined,
8588 : "dimension #%d (%s) is not a Longitude/X dimension.",
8589 : nd - 1, szDimName1);
8590 : }
8591 420 : if (NCDFIsVarLatitude(cdfid, -1, szDimName2) == false &&
8592 156 : NCDFIsVarProjectionY(cdfid, -1, szDimName2) == false)
8593 : {
8594 4 : CPLError(CE_Warning, CPLE_AppDefined,
8595 : "dimension #%d (%s) is not a Latitude/Y dimension.",
8596 : nd - 2, szDimName2);
8597 : }
8598 264 : if ((NCDFIsVarLongitude(cdfid, -1, szDimName2) ||
8599 266 : NCDFIsVarProjectionX(cdfid, -1, szDimName2)) &&
8600 2 : (NCDFIsVarLatitude(cdfid, -1, szDimName1) ||
8601 0 : NCDFIsVarProjectionY(cdfid, -1, szDimName1)))
8602 : {
8603 2 : poDS->bSwitchedXY = true;
8604 : }
8605 264 : if (nd >= 3)
8606 : {
8607 52 : char szDimName3[NC_MAX_NAME + 1] = {};
8608 : status =
8609 52 : nc_inq_dimname(cdfid, poDS->m_anDimIds[nd - 3], szDimName3);
8610 52 : NCDF_ERR(status);
8611 52 : if (nd >= 4)
8612 : {
8613 13 : char szDimName4[NC_MAX_NAME + 1] = {};
8614 : status =
8615 13 : nc_inq_dimname(cdfid, poDS->m_anDimIds[nd - 4], szDimName4);
8616 13 : NCDF_ERR(status);
8617 13 : if (NCDFIsVarVerticalCoord(cdfid, -1, szDimName3) == false)
8618 : {
8619 0 : CPLError(CE_Warning, CPLE_AppDefined,
8620 : "dimension #%d (%s) is not a Vertical dimension.",
8621 : nd - 3, szDimName3);
8622 : }
8623 13 : if (NCDFIsVarTimeCoord(cdfid, -1, szDimName4) == false)
8624 : {
8625 0 : CPLError(CE_Warning, CPLE_AppDefined,
8626 : "dimension #%d (%s) is not a Time dimension.",
8627 : nd - 4, szDimName4);
8628 : }
8629 : }
8630 : else
8631 : {
8632 75 : if (NCDFIsVarVerticalCoord(cdfid, -1, szDimName3) == false &&
8633 36 : NCDFIsVarTimeCoord(cdfid, -1, szDimName3) == false)
8634 : {
8635 0 : CPLError(CE_Warning, CPLE_AppDefined,
8636 : "dimension #%d (%s) is not a "
8637 : "Time or Vertical dimension.",
8638 : nd - 3, szDimName3);
8639 : }
8640 : }
8641 : }
8642 : }
8643 :
8644 : // For example for EMIT data (https://earth.jpl.nasa.gov/emit/data/data-portal/coverage-and-forecasts/),
8645 : // dimension order is downtrack, crosstrack, bands
8646 348 : bool bYXBandOrder = false;
8647 348 : if (nd == 3)
8648 : {
8649 44 : char szDimName[NC_MAX_NAME + 1] = {};
8650 44 : status = nc_inq_dimname(cdfid, poDS->m_anDimIds[2], szDimName);
8651 44 : NCDF_ERR(status);
8652 44 : bYXBandOrder =
8653 44 : strcmp(szDimName, "bands") == 0 || strcmp(szDimName, "band") == 0;
8654 : }
8655 :
8656 : // Get X dimensions information.
8657 : size_t xdim;
8658 348 : poDS->nXDimID = poDS->m_anDimIds[bYXBandOrder ? 1 : nd - 1];
8659 348 : nc_inq_dimlen(cdfid, poDS->nXDimID, &xdim);
8660 :
8661 : // Get Y dimension information.
8662 : size_t ydim;
8663 348 : if (nd >= 2)
8664 : {
8665 344 : poDS->nYDimID = poDS->m_anDimIds[bYXBandOrder ? 0 : nd - 2];
8666 344 : nc_inq_dimlen(cdfid, poDS->nYDimID, &ydim);
8667 : }
8668 : else
8669 : {
8670 4 : poDS->nYDimID = -1;
8671 4 : ydim = 1;
8672 : }
8673 :
8674 348 : if (xdim > INT_MAX || ydim > INT_MAX)
8675 : {
8676 0 : CPLError(CE_Failure, CPLE_AppDefined,
8677 : "Invalid raster dimensions: " CPL_FRMT_GUIB "x" CPL_FRMT_GUIB,
8678 : static_cast<GUIntBig>(xdim), static_cast<GUIntBig>(ydim));
8679 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll deadlock
8680 : // with GDALDataset own mutex.
8681 0 : delete poDS;
8682 0 : CPLAcquireMutex(hNCMutex, 1000.0);
8683 0 : return nullptr;
8684 : }
8685 :
8686 348 : poDS->nRasterXSize = static_cast<int>(xdim);
8687 348 : poDS->nRasterYSize = static_cast<int>(ydim);
8688 :
8689 348 : unsigned int k = 0;
8690 1119 : for (int j = 0; j < nd; j++)
8691 : {
8692 771 : if (poDS->m_anDimIds[j] == poDS->nXDimID)
8693 : {
8694 348 : anBandDimPos[0] = j; // Save Position of XDim
8695 348 : k++;
8696 : }
8697 771 : if (poDS->m_anDimIds[j] == poDS->nYDimID)
8698 : {
8699 344 : anBandDimPos[1] = j; // Save Position of YDim
8700 344 : k++;
8701 : }
8702 : }
8703 : // X and Y Dimension Ids were not found!
8704 348 : if ((nd >= 2 && k != 2) || (nd == 1 && k != 1))
8705 : {
8706 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll deadlock
8707 : // with GDALDataset own mutex.
8708 0 : delete poDS;
8709 0 : CPLAcquireMutex(hNCMutex, 1000.0);
8710 0 : return nullptr;
8711 : }
8712 :
8713 : // Read Metadata for this variable.
8714 :
8715 : // Should disable as is also done at band level, except driver needs the
8716 : // variables as metadata (e.g. projection).
8717 348 : poDS->ReadAttributes(cdfid, var);
8718 :
8719 : // Read Metadata for each dimension.
8720 348 : int *panDimIds = nullptr;
8721 348 : NCDFGetVisibleDims(cdfid, &ndims, &panDimIds);
8722 : // With NetCDF-4 groups panDimIds is not always [0..dim_count-1] like
8723 : // in NetCDF-3 because we see only the dimensions of the selected group
8724 : // and its parents.
8725 : // poDS->papszDimName is indexed by dim IDs, so it must contains all IDs
8726 : // [0..max(panDimIds)], but they are not all useful so we fill names
8727 : // of useless dims with empty string.
8728 348 : if (panDimIds)
8729 : {
8730 348 : const int nMaxDimId = *std::max_element(panDimIds, panDimIds + ndims);
8731 348 : std::set<int> oSetExistingDimIds;
8732 1155 : for (int i = 0; i < ndims; i++)
8733 : {
8734 807 : oSetExistingDimIds.insert(panDimIds[i]);
8735 : }
8736 348 : std::set<int> oSetDimIdsUsedByVar;
8737 1119 : for (int i = 0; i < nd; i++)
8738 : {
8739 771 : oSetDimIdsUsedByVar.insert(poDS->m_anDimIds[i]);
8740 : }
8741 1157 : for (int j = 0; j <= nMaxDimId; j++)
8742 : {
8743 : // Is j dim used?
8744 809 : if (oSetExistingDimIds.find(j) != oSetExistingDimIds.end())
8745 : {
8746 : // Useful dim.
8747 807 : char szTemp[NC_MAX_NAME + 1] = {};
8748 807 : status = nc_inq_dimname(cdfid, j, szTemp);
8749 807 : if (status != NC_NOERR)
8750 : {
8751 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll
8752 : // deadlock with GDALDataset own
8753 : // mutex.
8754 0 : delete poDS;
8755 0 : CPLAcquireMutex(hNCMutex, 1000.0);
8756 0 : return nullptr;
8757 : }
8758 807 : poDS->papszDimName.AddString(szTemp);
8759 :
8760 807 : if (oSetDimIdsUsedByVar.find(j) != oSetDimIdsUsedByVar.end())
8761 : {
8762 771 : int nDimGroupId = -1;
8763 771 : int nDimVarId = -1;
8764 771 : if (NCDFResolveVar(cdfid, poDS->papszDimName[j],
8765 771 : &nDimGroupId, &nDimVarId) == CE_None)
8766 : {
8767 571 : poDS->ReadAttributes(nDimGroupId, nDimVarId);
8768 : }
8769 : }
8770 : }
8771 : else
8772 : {
8773 : // Useless dim.
8774 2 : poDS->papszDimName.AddString("");
8775 : }
8776 : }
8777 348 : CPLFree(panDimIds);
8778 : }
8779 :
8780 : // Set projection info.
8781 696 : std::vector<std::string> aosRemovedMDItems;
8782 348 : if (nd > 1)
8783 : {
8784 344 : poDS->SetProjectionFromVar(cdfid, var,
8785 : /*bReadSRSOnly=*/false,
8786 : /* pszGivenGM = */ nullptr,
8787 : /* returnProjStr = */ nullptr,
8788 : /* sg = */ nullptr, &aosRemovedMDItems);
8789 : }
8790 :
8791 : // Override bottom-up with GDAL_NETCDF_BOTTOMUP config option.
8792 348 : const char *pszValue = CPLGetConfigOption("GDAL_NETCDF_BOTTOMUP", nullptr);
8793 348 : if (pszValue)
8794 : {
8795 24 : poDS->bBottomUp = CPLTestBool(pszValue);
8796 24 : CPLDebug("GDAL_netCDF",
8797 : "set bBottomUp=%d because GDAL_NETCDF_BOTTOMUP=%s",
8798 24 : static_cast<int>(poDS->bBottomUp), pszValue);
8799 : }
8800 :
8801 : // Save non-spatial dimension info.
8802 :
8803 348 : int *panBandZLev = nullptr;
8804 348 : int nDim = (nd >= 2) ? 2 : 1;
8805 : size_t lev_count;
8806 348 : size_t nTotLevCount = 1;
8807 348 : nc_type nType = NC_NAT;
8808 :
8809 696 : CPLString osExtraDimNames;
8810 :
8811 348 : if (nd > 2)
8812 : {
8813 60 : nDim = 2;
8814 60 : panBandZLev = static_cast<int *>(CPLCalloc(nd - 2, sizeof(int)));
8815 :
8816 60 : osExtraDimNames = "{";
8817 :
8818 60 : char szDimName[NC_MAX_NAME + 1] = {};
8819 :
8820 60 : bool bREPORT_EXTRA_DIM_VALUESWarningEmitted = false;
8821 259 : for (int j = 0; j < nd; j++)
8822 : {
8823 338 : if ((poDS->m_anDimIds[j] != poDS->nXDimID) &&
8824 139 : (poDS->m_anDimIds[j] != poDS->nYDimID))
8825 : {
8826 79 : nc_inq_dimlen(cdfid, poDS->m_anDimIds[j], &lev_count);
8827 79 : nTotLevCount *= lev_count;
8828 79 : panBandZLev[nDim - 2] = static_cast<int>(lev_count);
8829 79 : anBandDimPos[nDim] = j; // Save Position of ZDim
8830 : // Save non-spatial dimension names.
8831 79 : if (nc_inq_dimname(cdfid, poDS->m_anDimIds[j], szDimName) ==
8832 : NC_NOERR)
8833 : {
8834 79 : osExtraDimNames += szDimName;
8835 79 : if (j < nd - 3)
8836 : {
8837 19 : osExtraDimNames += ",";
8838 : }
8839 :
8840 79 : int nIdxGroupID = -1;
8841 79 : int nIdxVarID = Get1DVariableIndexedByDimension(
8842 79 : cdfid, poDS->m_anDimIds[j], szDimName, true,
8843 79 : &nIdxGroupID);
8844 79 : poDS->m_anExtraDimGroupIds.push_back(nIdxGroupID);
8845 79 : poDS->m_anExtraDimVarIds.push_back(nIdxVarID);
8846 :
8847 79 : if (nIdxVarID >= 0)
8848 : {
8849 70 : nc_inq_vartype(nIdxGroupID, nIdxVarID, &nType);
8850 : char szExtraDimDef[NC_MAX_NAME + 1];
8851 70 : snprintf(szExtraDimDef, sizeof(szExtraDimDef),
8852 : "{%ld,%d}", (long)lev_count, nType);
8853 : char szTemp[NC_MAX_NAME + 32 + 1];
8854 70 : snprintf(szTemp, sizeof(szTemp), "NETCDF_DIM_%s_DEF",
8855 : szDimName);
8856 70 : poDS->papszMetadata = CSLSetNameValue(
8857 : poDS->papszMetadata, szTemp, szExtraDimDef);
8858 :
8859 : // Retrieving data for unlimited dimensions might be
8860 : // costly on network storage, so don't do it.
8861 : // Each band will capture the value along the extra
8862 : // dimension in its NETCDF_DIM_xxxx band metadata item
8863 : // Addresses use case of
8864 : // https://lists.osgeo.org/pipermail/gdal-dev/2023-May/057209.html
8865 : const bool bIsLocal =
8866 70 : VSIIsLocal(osFilenameForNCOpen.c_str());
8867 : bool bListDimValues =
8868 71 : bIsLocal || lev_count == 1 ||
8869 1 : !NCDFIsUnlimitedDim(poDS->eFormat ==
8870 : NCDF_FORMAT_NC4,
8871 1 : cdfid, poDS->m_anDimIds[j]);
8872 : const char *pszGDAL_NETCDF_REPORT_EXTRA_DIM_VALUES =
8873 70 : CPLGetConfigOption(
8874 : "GDAL_NETCDF_REPORT_EXTRA_DIM_VALUES", nullptr);
8875 70 : if (pszGDAL_NETCDF_REPORT_EXTRA_DIM_VALUES)
8876 : {
8877 2 : bListDimValues = CPLTestBool(
8878 : pszGDAL_NETCDF_REPORT_EXTRA_DIM_VALUES);
8879 : }
8880 68 : else if (!bListDimValues && !bIsLocal &&
8881 1 : !bREPORT_EXTRA_DIM_VALUESWarningEmitted)
8882 : {
8883 1 : bREPORT_EXTRA_DIM_VALUESWarningEmitted = true;
8884 1 : CPLDebug(
8885 : "GDAL_netCDF",
8886 : "Listing extra dimension values is skipped "
8887 : "because this dataset is hosted on a network "
8888 : "file system, and such an operation could be "
8889 : "slow. If you still want to proceed, set the "
8890 : "GDAL_NETCDF_REPORT_EXTRA_DIM_VALUES "
8891 : "configuration option to YES");
8892 : }
8893 70 : if (bListDimValues)
8894 : {
8895 68 : char *pszTemp = nullptr;
8896 68 : if (NCDFGet1DVar(nIdxGroupID, nIdxVarID,
8897 68 : &pszTemp) == CE_None)
8898 : {
8899 68 : snprintf(szTemp, sizeof(szTemp),
8900 : "NETCDF_DIM_%s_VALUES", szDimName);
8901 68 : poDS->papszMetadata = CSLSetNameValue(
8902 : poDS->papszMetadata, szTemp, pszTemp);
8903 68 : CPLFree(pszTemp);
8904 : }
8905 : }
8906 : }
8907 : }
8908 : else
8909 : {
8910 0 : poDS->m_anExtraDimGroupIds.push_back(-1);
8911 0 : poDS->m_anExtraDimVarIds.push_back(-1);
8912 : }
8913 :
8914 79 : nDim++;
8915 : }
8916 : }
8917 60 : osExtraDimNames += "}";
8918 60 : poDS->papszMetadata = CSLSetNameValue(
8919 : poDS->papszMetadata, "NETCDF_DIM_EXTRA", osExtraDimNames);
8920 : }
8921 :
8922 : // Store Metadata.
8923 358 : for (const auto &osStr : aosRemovedMDItems)
8924 10 : poDS->papszMetadata =
8925 10 : CSLSetNameValue(poDS->papszMetadata, osStr.c_str(), nullptr);
8926 :
8927 348 : poDS->GDALPamDataset::SetMetadata(poDS->papszMetadata);
8928 :
8929 : // Create bands.
8930 :
8931 : // Arbitrary threshold.
8932 : int nMaxBandCount =
8933 348 : atoi(CPLGetConfigOption("GDAL_MAX_BAND_COUNT", "32768"));
8934 348 : if (nMaxBandCount <= 0)
8935 0 : nMaxBandCount = 32768;
8936 348 : if (nTotLevCount > static_cast<unsigned int>(nMaxBandCount))
8937 : {
8938 0 : CPLError(CE_Warning, CPLE_AppDefined,
8939 : "Limiting number of bands to %d instead of %u", nMaxBandCount,
8940 : static_cast<unsigned int>(nTotLevCount));
8941 0 : nTotLevCount = static_cast<unsigned int>(nMaxBandCount);
8942 : }
8943 348 : if (poDS->nRasterXSize == 0 || poDS->nRasterYSize == 0)
8944 : {
8945 0 : poDS->nRasterXSize = 0;
8946 0 : poDS->nRasterYSize = 0;
8947 0 : nTotLevCount = 0;
8948 0 : if (poDS->GetLayerCount() == 0)
8949 : {
8950 0 : CPLFree(panBandZLev);
8951 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll
8952 : // deadlock with GDALDataset own mutex.
8953 0 : delete poDS;
8954 0 : CPLAcquireMutex(hNCMutex, 1000.0);
8955 0 : return nullptr;
8956 : }
8957 : }
8958 348 : if (bSeveralVariablesAsBands)
8959 : {
8960 6 : const auto &listVariables = oMap2DDimsToGroupAndVar.begin()->second;
8961 24 : for (int iBand = 0; iBand < static_cast<int>(listVariables.size());
8962 : ++iBand)
8963 : {
8964 18 : int bandVarGroupId = listVariables[iBand].first;
8965 18 : int bandVarId = listVariables[iBand].second;
8966 : netCDFRasterBand *poBand = new netCDFRasterBand(
8967 0 : netCDFRasterBand::CONSTRUCTOR_OPEN(), poDS, bandVarGroupId,
8968 18 : bandVarId, nDim, 0, nullptr, anBandDimPos.data(), iBand + 1);
8969 18 : poDS->SetBand(iBand + 1, poBand);
8970 : }
8971 : }
8972 : else
8973 : {
8974 792 : for (unsigned int lev = 0; lev < nTotLevCount; lev++)
8975 : {
8976 : netCDFRasterBand *poBand = new netCDFRasterBand(
8977 0 : netCDFRasterBand::CONSTRUCTOR_OPEN(), poDS, cdfid, var, nDim,
8978 450 : lev, panBandZLev, anBandDimPos.data(), lev + 1);
8979 450 : poDS->SetBand(lev + 1, poBand);
8980 : }
8981 : }
8982 :
8983 348 : if (panBandZLev)
8984 60 : CPLFree(panBandZLev);
8985 : // Handle angular geographic coordinates here
8986 :
8987 : // Initialize any PAM information.
8988 348 : if (bTreatAsSubdataset)
8989 : {
8990 59 : poDS->SetPhysicalFilename(poDS->osFilename);
8991 59 : poDS->SetSubdatasetName(osSubdatasetName);
8992 : }
8993 :
8994 348 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll deadlock with
8995 : // GDALDataset own mutex.
8996 348 : poDS->TryLoadXML();
8997 :
8998 348 : if (bTreatAsSubdataset)
8999 59 : poDS->oOvManager.Initialize(poDS, ":::VIRTUAL:::");
9000 : else
9001 289 : poDS->oOvManager.Initialize(poDS, poDS->osFilename);
9002 :
9003 348 : CPLAcquireMutex(hNCMutex, 1000.0);
9004 :
9005 348 : return poDS;
9006 : }
9007 :
9008 : /************************************************************************/
9009 : /* CopyMetadata() */
9010 : /* */
9011 : /* Create a copy of metadata for NC_GLOBAL or a variable */
9012 : /************************************************************************/
9013 :
9014 153 : static void CopyMetadata(GDALDataset *poSrcDS, GDALRasterBand *poSrcBand,
9015 : GDALRasterBand *poDstBand, int nCdfId, int CDFVarID,
9016 : const char *pszPrefix)
9017 : {
9018 : // Remove the following band meta but set them later from band data.
9019 153 : const char *const papszIgnoreBand[] = {
9020 : CF_ADD_OFFSET, CF_SCALE_FACTOR, "valid_range", "_Unsigned",
9021 : NCDF_FillValue, "coordinates", nullptr};
9022 153 : const char *const papszIgnoreGlobal[] = {"NETCDF_DIM_EXTRA", nullptr};
9023 :
9024 153 : CSLConstList papszMetadata = nullptr;
9025 153 : if (poSrcDS)
9026 : {
9027 64 : papszMetadata = poSrcDS->GetMetadata();
9028 : }
9029 89 : else if (poSrcBand)
9030 : {
9031 89 : papszMetadata = poSrcBand->GetMetadata();
9032 : }
9033 :
9034 632 : for (const auto &[pszKey, pszValue] : cpl::IterateNameValue(papszMetadata))
9035 : {
9036 : #ifdef NCDF_DEBUG
9037 : CPLDebug("GDAL_netCDF", "copy metadata [%s]=[%s]", pszKey, pszValue);
9038 : #endif
9039 :
9040 479 : CPLString osMetaName(pszKey);
9041 :
9042 : // Check for items that match pszPrefix if applicable.
9043 479 : if (pszPrefix && !EQUAL(pszPrefix, ""))
9044 : {
9045 : // Remove prefix.
9046 115 : if (STARTS_WITH(osMetaName.c_str(), pszPrefix))
9047 : {
9048 17 : osMetaName = osMetaName.substr(strlen(pszPrefix));
9049 : }
9050 : // Only copy items that match prefix.
9051 : else
9052 : {
9053 98 : continue;
9054 : }
9055 : }
9056 :
9057 : // Fix various issues with metadata translation.
9058 381 : if (CDFVarID == NC_GLOBAL)
9059 : {
9060 : // Do not copy items in papszIgnoreGlobal and NETCDF_DIM_*.
9061 479 : if ((CSLFindString(papszIgnoreGlobal, osMetaName) != -1) ||
9062 237 : (STARTS_WITH(osMetaName, "NETCDF_DIM_")))
9063 21 : continue;
9064 : // Remove NC_GLOBAL prefix for netcdf global Metadata.
9065 221 : else if (STARTS_WITH(osMetaName, "NC_GLOBAL#"))
9066 : {
9067 33 : osMetaName = osMetaName.substr(strlen("NC_GLOBAL#"));
9068 : }
9069 : // GDAL Metadata renamed as GDAL-[meta].
9070 188 : else if (strstr(osMetaName, "#") == nullptr)
9071 : {
9072 15 : osMetaName = "GDAL_" + osMetaName;
9073 : }
9074 : // Keep time, lev and depth information for safe-keeping.
9075 : // Time and vertical coordinate handling need improvements.
9076 : /*
9077 : else if( STARTS_WITH(szMetaName, "time#") )
9078 : {
9079 : szMetaName[4] = '-';
9080 : }
9081 : else if( STARTS_WITH(szMetaName, "lev#") )
9082 : {
9083 : szMetaName[3] = '-';
9084 : }
9085 : else if( STARTS_WITH(szMetaName, "depth#") )
9086 : {
9087 : szMetaName[5] = '-';
9088 : }
9089 : */
9090 : // Only copy data without # (previously all data was copied).
9091 221 : if (strstr(osMetaName, "#") != nullptr)
9092 173 : continue;
9093 : // netCDF attributes do not like the '#' character.
9094 : // for( unsigned int h=0; h < strlen(szMetaName) -1 ; h++ ) {
9095 : // if( szMetaName[h] == '#') szMetaName[h] = '-';
9096 : // }
9097 : }
9098 : else
9099 : {
9100 : // Do not copy varname, stats, NETCDF_DIM_*, nodata
9101 : // and items in papszIgnoreBand.
9102 139 : if (STARTS_WITH(osMetaName, "NETCDF_VARNAME") ||
9103 107 : STARTS_WITH(osMetaName, "STATISTICS_") ||
9104 107 : STARTS_WITH(osMetaName, "NETCDF_DIM_") ||
9105 74 : STARTS_WITH(osMetaName, "missing_value") ||
9106 293 : STARTS_WITH(osMetaName, "_FillValue") ||
9107 47 : CSLFindString(papszIgnoreBand, osMetaName) != -1)
9108 97 : continue;
9109 : }
9110 :
9111 : #ifdef NCDF_DEBUG
9112 : CPLDebug("GDAL_netCDF", "copy name=[%s] value=[%s]", osMetaName.c_str(),
9113 : pszValue);
9114 : #endif
9115 90 : if (NCDFPutAttr(nCdfId, CDFVarID, osMetaName, pszValue) != CE_None)
9116 : {
9117 0 : CPLDebug("GDAL_netCDF", "NCDFPutAttr(%d, %d, %s, %s) failed",
9118 : nCdfId, CDFVarID, osMetaName.c_str(), pszValue);
9119 : }
9120 : }
9121 :
9122 : // Set add_offset and scale_factor here if present.
9123 153 : if (poSrcBand && poDstBand)
9124 : {
9125 :
9126 89 : int bGotAddOffset = FALSE;
9127 89 : const double dfAddOffset = poSrcBand->GetOffset(&bGotAddOffset);
9128 89 : int bGotScale = FALSE;
9129 89 : const double dfScale = poSrcBand->GetScale(&bGotScale);
9130 :
9131 89 : if (bGotAddOffset && dfAddOffset != 0.0)
9132 1 : poDstBand->SetOffset(dfAddOffset);
9133 89 : if (bGotScale && dfScale != 1.0)
9134 1 : poDstBand->SetScale(dfScale);
9135 : }
9136 153 : }
9137 :
9138 : /************************************************************************/
9139 : /* CreateLL() */
9140 : /* */
9141 : /* Shared functionality between netCDFDataset::Create() and */
9142 : /* netCDF::CreateCopy() for creating netcdf file based on a set of */
9143 : /* options and a configuration. */
9144 : /************************************************************************/
9145 :
9146 196 : netCDFDataset *netCDFDataset::CreateLL(const char *pszFilename, int nXSize,
9147 : int nYSize, int nBandsIn,
9148 : char **papszOptions)
9149 : {
9150 196 : if (!((nXSize == 0 && nYSize == 0 && nBandsIn == 0) ||
9151 124 : (nXSize > 0 && nYSize > 0 && nBandsIn > 0)))
9152 : {
9153 1 : return nullptr;
9154 : }
9155 :
9156 195 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll deadlock with
9157 : // GDALDataset own mutex.
9158 195 : netCDFDataset *poDS = new netCDFDataset();
9159 195 : CPLAcquireMutex(hNCMutex, 1000.0);
9160 :
9161 195 : poDS->nRasterXSize = nXSize;
9162 195 : poDS->nRasterYSize = nYSize;
9163 195 : poDS->eAccess = GA_Update;
9164 195 : poDS->osFilename = pszFilename;
9165 :
9166 : // From gtiff driver, is this ok?
9167 : /*
9168 : poDS->nBlockXSize = nXSize;
9169 : poDS->nBlockYSize = 1;
9170 : poDS->nBlocksPerBand =
9171 : ((nYSize + poDS->nBlockYSize - 1) / poDS->nBlockYSize)
9172 : * ((nXSize + poDS->nBlockXSize - 1) / poDS->nBlockXSize);
9173 : */
9174 :
9175 : // process options.
9176 195 : poDS->papszCreationOptions = CSLDuplicate(papszOptions);
9177 195 : poDS->ProcessCreationOptions();
9178 :
9179 195 : if (poDS->eMultipleLayerBehavior == SEPARATE_FILES)
9180 : {
9181 : VSIStatBuf sStat;
9182 2 : if (VSIStat(pszFilename, &sStat) == 0)
9183 : {
9184 0 : if (!VSI_ISDIR(sStat.st_mode))
9185 : {
9186 0 : CPLError(CE_Failure, CPLE_FileIO,
9187 : "%s is an existing file, but not a directory",
9188 : pszFilename);
9189 0 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll
9190 : // deadlock with GDALDataset own
9191 : // mutex.
9192 0 : delete poDS;
9193 0 : CPLAcquireMutex(hNCMutex, 1000.0);
9194 0 : return nullptr;
9195 : }
9196 : }
9197 2 : else if (VSIMkdir(pszFilename, 0755) != 0)
9198 : {
9199 1 : CPLError(CE_Failure, CPLE_FileIO, "Cannot create %s directory",
9200 : pszFilename);
9201 1 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll
9202 : // deadlock with GDALDataset own mutex.
9203 1 : delete poDS;
9204 1 : CPLAcquireMutex(hNCMutex, 1000.0);
9205 1 : return nullptr;
9206 : }
9207 :
9208 1 : return poDS;
9209 : }
9210 : // Create the dataset.
9211 386 : CPLString osFilenameForNCCreate(pszFilename);
9212 : #if defined(_WIN32) && !defined(NETCDF_USES_UTF8)
9213 : if (CPLTestBool(CPLGetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")))
9214 : {
9215 : char *pszTemp =
9216 : CPLRecode(osFilenameForNCCreate, CPL_ENC_UTF8, "CP_ACP");
9217 : osFilenameForNCCreate = pszTemp;
9218 : CPLFree(pszTemp);
9219 : }
9220 : #endif
9221 :
9222 : #if defined(_WIN32)
9223 : {
9224 : // Works around bug of msys2 netCDF 4.9.0 package where nc_create()
9225 : // crashes
9226 : VSIStatBuf sStat;
9227 : const std::string osDirname =
9228 : CPLGetDirnameSafe(osFilenameForNCCreate.c_str());
9229 : if (VSIStat(osDirname.c_str(), &sStat) != 0)
9230 : {
9231 : CPLError(CE_Failure, CPLE_OpenFailed,
9232 : "Unable to create netCDF file %s: non existing output "
9233 : "directory",
9234 : pszFilename);
9235 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll
9236 : // deadlock with GDALDataset own mutex.
9237 : delete poDS;
9238 : CPLAcquireMutex(hNCMutex, 1000.0);
9239 : return nullptr;
9240 : }
9241 : }
9242 : #endif
9243 :
9244 : int status =
9245 193 : nc_create(osFilenameForNCCreate, poDS->nCreateMode, &(poDS->cdfid));
9246 :
9247 : // Put into define mode.
9248 193 : poDS->SetDefineMode(true);
9249 :
9250 193 : if (status != NC_NOERR)
9251 : {
9252 30 : CPLError(CE_Failure, CPLE_OpenFailed,
9253 : "Unable to create netCDF file %s (Error code %d): %s .",
9254 : pszFilename, status, nc_strerror(status));
9255 30 : CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll deadlock
9256 : // with GDALDataset own mutex.
9257 30 : delete poDS;
9258 30 : CPLAcquireMutex(hNCMutex, 1000.0);
9259 30 : return nullptr;
9260 : }
9261 :
9262 : // Define dimensions.
9263 163 : if (nXSize > 0 && nYSize > 0)
9264 : {
9265 110 : poDS->papszDimName.AddString(NCDF_DIMNAME_X);
9266 : status =
9267 110 : nc_def_dim(poDS->cdfid, NCDF_DIMNAME_X, nXSize, &(poDS->nXDimID));
9268 110 : NCDF_ERR(status);
9269 110 : CPLDebug("GDAL_netCDF", "status nc_def_dim(%d, %s, %d, -) got id %d",
9270 : poDS->cdfid, NCDF_DIMNAME_X, nXSize, poDS->nXDimID);
9271 :
9272 110 : poDS->papszDimName.AddString(NCDF_DIMNAME_Y);
9273 : status =
9274 110 : nc_def_dim(poDS->cdfid, NCDF_DIMNAME_Y, nYSize, &(poDS->nYDimID));
9275 110 : NCDF_ERR(status);
9276 110 : CPLDebug("GDAL_netCDF", "status nc_def_dim(%d, %s, %d, -) got id %d",
9277 : poDS->cdfid, NCDF_DIMNAME_Y, nYSize, poDS->nYDimID);
9278 : }
9279 :
9280 163 : return poDS;
9281 : }
9282 :
9283 : /************************************************************************/
9284 : /* Create() */
9285 : /************************************************************************/
9286 :
9287 126 : GDALDataset *netCDFDataset::Create(const char *pszFilename, int nXSize,
9288 : int nYSize, int nBandsIn, GDALDataType eType,
9289 : char **papszOptions)
9290 : {
9291 126 : CPLDebug("GDAL_netCDF", "\n=====\nnetCDFDataset::Create(%s, ...)",
9292 : pszFilename);
9293 :
9294 : const char *legacyCreationOp =
9295 126 : CSLFetchNameValueDef(papszOptions, "GEOMETRY_ENCODING", "CF_1.8");
9296 252 : std::string legacyCreationOp_s = std::string(legacyCreationOp);
9297 :
9298 : // Check legacy creation op FIRST
9299 :
9300 126 : bool legacyCreateMode = false;
9301 :
9302 126 : if (nXSize != 0 || nYSize != 0 || nBandsIn != 0)
9303 : {
9304 56 : legacyCreateMode = true;
9305 : }
9306 70 : else if (legacyCreationOp_s == "CF_1.8")
9307 : {
9308 54 : legacyCreateMode = false;
9309 : }
9310 :
9311 16 : else if (legacyCreationOp_s == "WKT")
9312 : {
9313 16 : legacyCreateMode = true;
9314 : }
9315 :
9316 : else
9317 : {
9318 0 : CPLError(
9319 : CE_Failure, CPLE_NotSupported,
9320 : "Dataset creation option GEOMETRY_ENCODING=%s is not supported.",
9321 : legacyCreationOp_s.c_str());
9322 0 : return nullptr;
9323 : }
9324 :
9325 252 : CPLStringList aosOptions(CSLDuplicate(papszOptions));
9326 238 : if (aosOptions.FetchNameValue("FORMAT") == nullptr &&
9327 112 : (eType == GDT_UInt16 || eType == GDT_UInt32 || eType == GDT_UInt64 ||
9328 : eType == GDT_Int64))
9329 : {
9330 10 : CPLDebug("netCDF", "Selecting FORMAT=NC4 due to data type");
9331 10 : aosOptions.SetNameValue("FORMAT", "NC4");
9332 : }
9333 :
9334 252 : CPLStringList aosBandNames;
9335 126 : if (const char *pszBandNames = aosOptions.FetchNameValue("BAND_NAMES"))
9336 : {
9337 : aosBandNames =
9338 2 : CSLTokenizeString2(pszBandNames, ",", CSLT_HONOURSTRINGS);
9339 :
9340 2 : if (aosBandNames.Count() != nBandsIn)
9341 : {
9342 1 : CPLError(CE_Failure, CPLE_OpenFailed,
9343 : "Attempted to create netCDF with %d bands but %d names "
9344 : "provided in BAND_NAMES.",
9345 : nBandsIn, aosBandNames.Count());
9346 :
9347 1 : return nullptr;
9348 : }
9349 : }
9350 :
9351 250 : CPLMutexHolderD(&hNCMutex);
9352 :
9353 125 : auto poDS = netCDFDataset::CreateLL(pszFilename, nXSize, nYSize, nBandsIn,
9354 : aosOptions.List());
9355 :
9356 125 : if (!poDS)
9357 19 : return nullptr;
9358 :
9359 106 : if (!legacyCreateMode)
9360 : {
9361 37 : poDS->bSGSupport = true;
9362 37 : poDS->vcdf.enableFullVirtualMode();
9363 : }
9364 :
9365 : else
9366 : {
9367 69 : poDS->bSGSupport = false;
9368 : }
9369 :
9370 : // Should we write signed or unsigned byte?
9371 : // TODO should this only be done in Create()
9372 106 : poDS->bSignedData = true;
9373 106 : const char *pszValue = CSLFetchNameValueDef(papszOptions, "PIXELTYPE", "");
9374 106 : if (eType == GDT_Byte && !EQUAL(pszValue, "SIGNEDBYTE"))
9375 15 : poDS->bSignedData = false;
9376 :
9377 : // Add Conventions, GDAL info and history.
9378 106 : if (poDS->cdfid >= 0)
9379 : {
9380 : const char *CF_Vector_Conv =
9381 173 : poDS->bSGSupport ||
9382 : // Use of variable length strings require CF-1.8
9383 68 : EQUAL(aosOptions.FetchNameValueDef("FORMAT", ""), "NC4")
9384 : ? NCDF_CONVENTIONS_CF_V1_8
9385 173 : : NCDF_CONVENTIONS_CF_V1_6;
9386 105 : poDS->bWriteGDALVersion = CPLTestBool(
9387 : CSLFetchNameValueDef(papszOptions, "WRITE_GDAL_VERSION", "YES"));
9388 105 : poDS->bWriteGDALHistory = CPLTestBool(
9389 : CSLFetchNameValueDef(papszOptions, "WRITE_GDAL_HISTORY", "YES"));
9390 105 : NCDFAddGDALHistory(poDS->cdfid, pszFilename, poDS->bWriteGDALVersion,
9391 105 : poDS->bWriteGDALHistory, "", "Create",
9392 : (nBandsIn == 0) ? CF_Vector_Conv
9393 : : GDAL_DEFAULT_NCDF_CONVENTIONS);
9394 : }
9395 :
9396 : // Define bands.
9397 197 : for (int iBand = 1; iBand <= nBandsIn; iBand++)
9398 : {
9399 : const char *pszBandName =
9400 91 : aosBandNames.empty() ? nullptr : aosBandNames[iBand - 1];
9401 :
9402 91 : poDS->SetBand(iBand, new netCDFRasterBand(
9403 91 : netCDFRasterBand::CONSTRUCTOR_CREATE(), poDS,
9404 91 : eType, iBand, poDS->bSignedData, pszBandName));
9405 : }
9406 :
9407 106 : CPLDebug("GDAL_netCDF", "netCDFDataset::Create(%s, ...) done", pszFilename);
9408 : // Return same dataset.
9409 106 : return poDS;
9410 : }
9411 :
9412 : template <class T>
9413 89 : static CPLErr NCDFCopyBand(GDALRasterBand *poSrcBand, GDALRasterBand *poDstBand,
9414 : int nXSize, int nYSize, GDALProgressFunc pfnProgress,
9415 : void *pProgressData)
9416 : {
9417 89 : GDALDataType eDT = poSrcBand->GetRasterDataType();
9418 89 : CPLErr eErr = CE_None;
9419 89 : T *patScanline = static_cast<T *>(CPLMalloc(nXSize * sizeof(T)));
9420 :
9421 2686 : for (int iLine = 0; iLine < nYSize && eErr == CE_None; iLine++)
9422 : {
9423 2597 : eErr = poSrcBand->RasterIO(GF_Read, 0, iLine, nXSize, 1, patScanline,
9424 : nXSize, 1, eDT, 0, 0, nullptr);
9425 2597 : if (eErr != CE_None)
9426 : {
9427 0 : CPLDebug(
9428 : "GDAL_netCDF",
9429 : "NCDFCopyBand(), poSrcBand->RasterIO() returned error code %d",
9430 : eErr);
9431 : }
9432 : else
9433 : {
9434 2597 : eErr =
9435 : poDstBand->RasterIO(GF_Write, 0, iLine, nXSize, 1, patScanline,
9436 : nXSize, 1, eDT, 0, 0, nullptr);
9437 2597 : if (eErr != CE_None)
9438 0 : CPLDebug("GDAL_netCDF",
9439 : "NCDFCopyBand(), poDstBand->RasterIO() returned error "
9440 : "code %d",
9441 : eErr);
9442 : }
9443 :
9444 2597 : if (nYSize > 10 && (iLine % (nYSize / 10) == 1))
9445 : {
9446 257 : if (!pfnProgress(1.0 * iLine / nYSize, nullptr, pProgressData))
9447 : {
9448 0 : eErr = CE_Failure;
9449 0 : CPLError(CE_Failure, CPLE_UserInterrupt,
9450 : "User terminated CreateCopy()");
9451 : }
9452 : }
9453 : }
9454 :
9455 89 : CPLFree(patScanline);
9456 :
9457 89 : pfnProgress(1.0, nullptr, pProgressData);
9458 :
9459 89 : return eErr;
9460 : }
9461 :
9462 : /************************************************************************/
9463 : /* CreateCopy() */
9464 : /************************************************************************/
9465 :
9466 : GDALDataset *
9467 80 : netCDFDataset::CreateCopy(const char *pszFilename, GDALDataset *poSrcDS,
9468 : CPL_UNUSED int bStrict, char **papszOptions,
9469 : GDALProgressFunc pfnProgress, void *pProgressData)
9470 : {
9471 160 : CPLMutexHolderD(&hNCMutex);
9472 :
9473 80 : CPLDebug("GDAL_netCDF", "\n=====\nnetCDFDataset::CreateCopy(%s, ...)",
9474 : pszFilename);
9475 :
9476 80 : if (poSrcDS->GetRootGroup())
9477 : {
9478 5 : auto poDrv = GDALDriver::FromHandle(GDALGetDriverByName("netCDF"));
9479 5 : if (poDrv)
9480 : {
9481 5 : return poDrv->DefaultCreateCopy(pszFilename, poSrcDS, bStrict,
9482 : papszOptions, pfnProgress,
9483 5 : pProgressData);
9484 : }
9485 : }
9486 :
9487 75 : const int nBands = poSrcDS->GetRasterCount();
9488 75 : const int nXSize = poSrcDS->GetRasterXSize();
9489 75 : const int nYSize = poSrcDS->GetRasterYSize();
9490 75 : const char *pszWKT = poSrcDS->GetProjectionRef();
9491 :
9492 : // Check input bands for errors.
9493 75 : if (nBands == 0)
9494 : {
9495 1 : CPLError(CE_Failure, CPLE_NotSupported,
9496 : "NetCDF driver does not support "
9497 : "source dataset with zero band.");
9498 1 : return nullptr;
9499 : }
9500 :
9501 74 : GDALDataType eDT = GDT_Unknown;
9502 74 : GDALRasterBand *poSrcBand = nullptr;
9503 177 : for (int iBand = 1; iBand <= nBands; iBand++)
9504 : {
9505 107 : poSrcBand = poSrcDS->GetRasterBand(iBand);
9506 107 : eDT = poSrcBand->GetRasterDataType();
9507 107 : if (eDT == GDT_Unknown || GDALDataTypeIsComplex(eDT))
9508 : {
9509 4 : CPLError(CE_Failure, CPLE_NotSupported,
9510 : "NetCDF driver does not support source dataset with band "
9511 : "of complex type.");
9512 4 : return nullptr;
9513 : }
9514 : }
9515 :
9516 140 : CPLStringList aosBandNames;
9517 70 : if (const char *pszBandNames =
9518 70 : CSLFetchNameValue(papszOptions, "BAND_NAMES"))
9519 : {
9520 : aosBandNames =
9521 2 : CSLTokenizeString2(pszBandNames, ",", CSLT_HONOURSTRINGS);
9522 :
9523 2 : if (aosBandNames.Count() != nBands)
9524 : {
9525 1 : CPLError(CE_Failure, CPLE_OpenFailed,
9526 : "Attempted to create netCDF with %d bands but %d names "
9527 : "provided in BAND_NAMES.",
9528 : nBands, aosBandNames.Count());
9529 :
9530 1 : return nullptr;
9531 : }
9532 : }
9533 :
9534 69 : if (!pfnProgress(0.0, nullptr, pProgressData))
9535 0 : return nullptr;
9536 :
9537 : // Same as in Create().
9538 138 : CPLStringList aosOptions(CSLDuplicate(papszOptions));
9539 129 : if (aosOptions.FetchNameValue("FORMAT") == nullptr &&
9540 60 : (eDT == GDT_UInt16 || eDT == GDT_UInt32 || eDT == GDT_UInt64 ||
9541 : eDT == GDT_Int64))
9542 : {
9543 6 : CPLDebug("netCDF", "Selecting FORMAT=NC4 due to data type");
9544 6 : aosOptions.SetNameValue("FORMAT", "NC4");
9545 : }
9546 69 : netCDFDataset *poDS = netCDFDataset::CreateLL(pszFilename, nXSize, nYSize,
9547 : nBands, aosOptions.List());
9548 69 : if (!poDS)
9549 13 : return nullptr;
9550 :
9551 : // Copy global metadata.
9552 : // Add Conventions, GDAL info and history.
9553 56 : CopyMetadata(poSrcDS, nullptr, nullptr, poDS->cdfid, NC_GLOBAL, nullptr);
9554 56 : const bool bWriteGDALVersion = CPLTestBool(
9555 : CSLFetchNameValueDef(papszOptions, "WRITE_GDAL_VERSION", "YES"));
9556 56 : const bool bWriteGDALHistory = CPLTestBool(
9557 : CSLFetchNameValueDef(papszOptions, "WRITE_GDAL_HISTORY", "YES"));
9558 56 : NCDFAddGDALHistory(
9559 : poDS->cdfid, pszFilename, bWriteGDALVersion, bWriteGDALHistory,
9560 56 : poSrcDS->GetMetadataItem("NC_GLOBAL#history"), "CreateCopy",
9561 56 : poSrcDS->GetMetadataItem("NC_GLOBAL#Conventions"));
9562 :
9563 56 : pfnProgress(0.1, nullptr, pProgressData);
9564 :
9565 : // Check for extra dimensions.
9566 56 : int nDim = 2;
9567 : char **papszExtraDimNames =
9568 56 : NCDFTokenizeArray(poSrcDS->GetMetadataItem("NETCDF_DIM_EXTRA", ""));
9569 56 : char **papszExtraDimValues = nullptr;
9570 :
9571 56 : if (papszExtraDimNames != nullptr && CSLCount(papszExtraDimNames) > 0)
9572 : {
9573 5 : size_t nDimSizeTot = 1;
9574 : // first make sure dimensions lengths compatible with band count
9575 : // for( int i=0; i<CSLCount(papszExtraDimNames ); i++ ) {
9576 13 : for (int i = CSLCount(papszExtraDimNames) - 1; i >= 0; i--)
9577 : {
9578 : char szTemp[NC_MAX_NAME + 32 + 1];
9579 8 : snprintf(szTemp, sizeof(szTemp), "NETCDF_DIM_%s_DEF",
9580 8 : papszExtraDimNames[i]);
9581 : papszExtraDimValues =
9582 8 : NCDFTokenizeArray(poSrcDS->GetMetadataItem(szTemp, ""));
9583 8 : const size_t nDimSize = atol(papszExtraDimValues[0]);
9584 8 : CSLDestroy(papszExtraDimValues);
9585 8 : nDimSizeTot *= nDimSize;
9586 : }
9587 5 : if (nDimSizeTot == (size_t)nBands)
9588 : {
9589 5 : nDim = 2 + CSLCount(papszExtraDimNames);
9590 : }
9591 : else
9592 : {
9593 : // if nBands != #bands computed raise a warning
9594 : // just issue a debug message, because it was probably intentional
9595 0 : CPLDebug("GDAL_netCDF",
9596 : "Warning: Number of bands (%d) is not compatible with "
9597 : "dimensions "
9598 : "(total=%ld names=%s)",
9599 : nBands, (long)nDimSizeTot,
9600 0 : poSrcDS->GetMetadataItem("NETCDF_DIM_EXTRA", ""));
9601 0 : CSLDestroy(papszExtraDimNames);
9602 0 : papszExtraDimNames = nullptr;
9603 : }
9604 : }
9605 :
9606 56 : int *panDimIds = static_cast<int *>(CPLCalloc(nDim, sizeof(int)));
9607 56 : int *panBandDimPos = static_cast<int *>(CPLCalloc(nDim, sizeof(int)));
9608 :
9609 : nc_type nVarType;
9610 56 : int *panBandZLev = nullptr;
9611 56 : int *panDimVarIds = nullptr;
9612 :
9613 56 : if (nDim > 2)
9614 : {
9615 5 : panBandZLev = static_cast<int *>(CPLCalloc(nDim - 2, sizeof(int)));
9616 5 : panDimVarIds = static_cast<int *>(CPLCalloc(nDim - 2, sizeof(int)));
9617 :
9618 : // Define all dims.
9619 13 : for (int i = CSLCount(papszExtraDimNames) - 1; i >= 0; i--)
9620 : {
9621 8 : poDS->papszDimName.AddString(papszExtraDimNames[i]);
9622 : char szTemp[NC_MAX_NAME + 32 + 1];
9623 8 : snprintf(szTemp, sizeof(szTemp), "NETCDF_DIM_%s_DEF",
9624 8 : papszExtraDimNames[i]);
9625 : papszExtraDimValues =
9626 8 : NCDFTokenizeArray(poSrcDS->GetMetadataItem(szTemp, ""));
9627 8 : const int nDimSize = papszExtraDimValues && papszExtraDimValues[0]
9628 16 : ? atoi(papszExtraDimValues[0])
9629 : : 0;
9630 : // nc_type is an enum in netcdf-3, needs casting.
9631 8 : nVarType = static_cast<nc_type>(papszExtraDimValues &&
9632 8 : papszExtraDimValues[0] &&
9633 8 : papszExtraDimValues[1]
9634 8 : ? atol(papszExtraDimValues[1])
9635 : : 0);
9636 8 : CSLDestroy(papszExtraDimValues);
9637 8 : panBandZLev[i] = nDimSize;
9638 8 : panBandDimPos[i + 2] = i; // Save Position of ZDim.
9639 :
9640 : // Define dim.
9641 16 : int status = nc_def_dim(poDS->cdfid, papszExtraDimNames[i],
9642 8 : nDimSize, &(panDimIds[i]));
9643 8 : NCDF_ERR(status);
9644 :
9645 : // Define dim var.
9646 8 : int anDim[1] = {panDimIds[i]};
9647 16 : status = nc_def_var(poDS->cdfid, papszExtraDimNames[i], nVarType, 1,
9648 8 : anDim, &(panDimVarIds[i]));
9649 8 : NCDF_ERR(status);
9650 :
9651 : // Add dim metadata, using global var# items.
9652 8 : snprintf(szTemp, sizeof(szTemp), "%s#", papszExtraDimNames[i]);
9653 8 : CopyMetadata(poSrcDS, nullptr, nullptr, poDS->cdfid,
9654 8 : panDimVarIds[i], szTemp);
9655 : }
9656 : }
9657 :
9658 : // Copy GeoTransform and Projection.
9659 :
9660 : // Copy geolocation info.
9661 56 : char **papszGeolocationInfo = poSrcDS->GetMetadata("GEOLOCATION");
9662 56 : if (papszGeolocationInfo != nullptr)
9663 5 : poDS->GDALPamDataset::SetMetadata(papszGeolocationInfo, "GEOLOCATION");
9664 :
9665 : // Copy geotransform.
9666 56 : bool bGotGeoTransform = false;
9667 : double adfGeoTransform[6];
9668 56 : CPLErr eErr = poSrcDS->GetGeoTransform(adfGeoTransform);
9669 56 : if (eErr == CE_None)
9670 : {
9671 38 : poDS->SetGeoTransform(adfGeoTransform);
9672 : // Disable AddProjectionVars() from being called.
9673 38 : bGotGeoTransform = true;
9674 38 : poDS->m_bHasGeoTransform = false;
9675 : }
9676 :
9677 : // Copy projection.
9678 56 : void *pScaledProgress = nullptr;
9679 56 : if (bGotGeoTransform || (pszWKT && pszWKT[0] != 0))
9680 : {
9681 39 : poDS->SetProjection(pszWKT ? pszWKT : "");
9682 :
9683 : // Now we can call AddProjectionVars() directly.
9684 39 : poDS->m_bHasGeoTransform = bGotGeoTransform;
9685 39 : poDS->AddProjectionVars(true, nullptr, nullptr);
9686 : pScaledProgress =
9687 39 : GDALCreateScaledProgress(0.1, 0.25, pfnProgress, pProgressData);
9688 39 : poDS->AddProjectionVars(false, GDALScaledProgress, pScaledProgress);
9689 39 : GDALDestroyScaledProgress(pScaledProgress);
9690 : }
9691 : else
9692 : {
9693 17 : poDS->bBottomUp =
9694 17 : CPL_TO_BOOL(CSLFetchBoolean(papszOptions, "WRITE_BOTTOMUP", TRUE));
9695 17 : if (papszGeolocationInfo)
9696 : {
9697 4 : poDS->AddProjectionVars(true, nullptr, nullptr);
9698 4 : poDS->AddProjectionVars(false, nullptr, nullptr);
9699 : }
9700 : }
9701 :
9702 : // Save X,Y dim positions.
9703 56 : panDimIds[nDim - 1] = poDS->nXDimID;
9704 56 : panBandDimPos[0] = nDim - 1;
9705 56 : panDimIds[nDim - 2] = poDS->nYDimID;
9706 56 : panBandDimPos[1] = nDim - 2;
9707 :
9708 : // Write extra dim values - after projection for optimization.
9709 56 : if (nDim > 2)
9710 : {
9711 : // Make sure we are in data mode.
9712 5 : static_cast<netCDFDataset *>(poDS)->SetDefineMode(false);
9713 13 : for (int i = CSLCount(papszExtraDimNames) - 1; i >= 0; i--)
9714 : {
9715 : char szTemp[NC_MAX_NAME + 32 + 1];
9716 8 : snprintf(szTemp, sizeof(szTemp), "NETCDF_DIM_%s_VALUES",
9717 8 : papszExtraDimNames[i]);
9718 8 : if (poSrcDS->GetMetadataItem(szTemp) != nullptr)
9719 : {
9720 8 : NCDFPut1DVar(poDS->cdfid, panDimVarIds[i],
9721 8 : poSrcDS->GetMetadataItem(szTemp));
9722 : }
9723 : }
9724 : }
9725 :
9726 56 : pfnProgress(0.25, nullptr, pProgressData);
9727 :
9728 : // Define Bands.
9729 56 : netCDFRasterBand *poBand = nullptr;
9730 56 : int nBandID = -1;
9731 :
9732 145 : for (int iBand = 1; iBand <= nBands; iBand++)
9733 : {
9734 89 : CPLDebug("GDAL_netCDF", "creating band # %d/%d nDim = %d", iBand,
9735 : nBands, nDim);
9736 :
9737 89 : poSrcBand = poSrcDS->GetRasterBand(iBand);
9738 89 : eDT = poSrcBand->GetRasterDataType();
9739 :
9740 : // Get var name from NETCDF_VARNAME.
9741 : const char *pszNETCDF_VARNAME =
9742 89 : poSrcBand->GetMetadataItem("NETCDF_VARNAME");
9743 : char szBandName[NC_MAX_NAME + 1];
9744 89 : if (!aosBandNames.empty())
9745 : {
9746 2 : snprintf(szBandName, sizeof(szBandName), "%s",
9747 : aosBandNames[iBand - 1]);
9748 : }
9749 87 : else if (pszNETCDF_VARNAME)
9750 : {
9751 32 : if (nBands > 1 && papszExtraDimNames == nullptr)
9752 0 : snprintf(szBandName, sizeof(szBandName), "%s%d",
9753 : pszNETCDF_VARNAME, iBand);
9754 : else
9755 32 : snprintf(szBandName, sizeof(szBandName), "%s",
9756 : pszNETCDF_VARNAME);
9757 : }
9758 : else
9759 : {
9760 55 : szBandName[0] = '\0';
9761 : }
9762 :
9763 : // Get long_name from <var>#long_name.
9764 89 : const char *pszLongName = "";
9765 89 : if (pszNETCDF_VARNAME)
9766 : {
9767 : pszLongName =
9768 64 : poSrcDS->GetMetadataItem(std::string(pszNETCDF_VARNAME)
9769 32 : .append("#")
9770 32 : .append(CF_LNG_NAME)
9771 32 : .c_str());
9772 32 : if (!pszLongName)
9773 25 : pszLongName = "";
9774 : }
9775 :
9776 89 : constexpr bool bSignedData = false;
9777 :
9778 89 : if (nDim > 2)
9779 27 : poBand = new netCDFRasterBand(
9780 27 : netCDFRasterBand::CONSTRUCTOR_CREATE(), poDS, eDT, iBand,
9781 : bSignedData, szBandName, pszLongName, nBandID, nDim, iBand - 1,
9782 27 : panBandZLev, panBandDimPos, panDimIds);
9783 : else
9784 62 : poBand = new netCDFRasterBand(
9785 62 : netCDFRasterBand::CONSTRUCTOR_CREATE(), poDS, eDT, iBand,
9786 62 : bSignedData, szBandName, pszLongName);
9787 :
9788 89 : poDS->SetBand(iBand, poBand);
9789 :
9790 : // Set nodata value, if any.
9791 89 : GDALCopyNoDataValue(poBand, poSrcBand);
9792 :
9793 : // Copy Metadata for band.
9794 89 : CopyMetadata(nullptr, poSrcDS->GetRasterBand(iBand), poBand,
9795 : poDS->cdfid, poBand->nZId);
9796 :
9797 : // If more than 2D pass the first band's netcdf var ID to subsequent
9798 : // bands.
9799 89 : if (nDim > 2)
9800 27 : nBandID = poBand->nZId;
9801 : }
9802 :
9803 : // Write projection variable to band variable.
9804 56 : poDS->AddGridMappingRef();
9805 :
9806 56 : pfnProgress(0.5, nullptr, pProgressData);
9807 :
9808 : // Write bands.
9809 :
9810 : // Make sure we are in data mode.
9811 56 : poDS->SetDefineMode(false);
9812 :
9813 56 : double dfTemp = 0.5;
9814 :
9815 56 : eErr = CE_None;
9816 :
9817 145 : for (int iBand = 1; iBand <= nBands && eErr == CE_None; iBand++)
9818 : {
9819 89 : const double dfTemp2 = dfTemp + 0.4 / nBands;
9820 89 : pScaledProgress = GDALCreateScaledProgress(dfTemp, dfTemp2, pfnProgress,
9821 : pProgressData);
9822 89 : dfTemp = dfTemp2;
9823 :
9824 89 : CPLDebug("GDAL_netCDF", "copying band data # %d/%d ", iBand, nBands);
9825 :
9826 89 : poSrcBand = poSrcDS->GetRasterBand(iBand);
9827 89 : eDT = poSrcBand->GetRasterDataType();
9828 :
9829 89 : GDALRasterBand *poDstBand = poDS->GetRasterBand(iBand);
9830 :
9831 : // Copy band data.
9832 89 : if (eDT == GDT_Byte)
9833 : {
9834 49 : CPLDebug("GDAL_netCDF", "GByte Band#%d", iBand);
9835 49 : eErr = NCDFCopyBand<GByte>(poSrcBand, poDstBand, nXSize, nYSize,
9836 : GDALScaledProgress, pScaledProgress);
9837 : }
9838 40 : else if (eDT == GDT_Int8)
9839 : {
9840 1 : CPLDebug("GDAL_netCDF", "GInt8 Band#%d", iBand);
9841 1 : eErr = NCDFCopyBand<GInt8>(poSrcBand, poDstBand, nXSize, nYSize,
9842 : GDALScaledProgress, pScaledProgress);
9843 : }
9844 39 : else if (eDT == GDT_UInt16)
9845 : {
9846 2 : CPLDebug("GDAL_netCDF", "GUInt16 Band#%d", iBand);
9847 2 : eErr = NCDFCopyBand<GInt16>(poSrcBand, poDstBand, nXSize, nYSize,
9848 : GDALScaledProgress, pScaledProgress);
9849 : }
9850 37 : else if (eDT == GDT_Int16)
9851 : {
9852 5 : CPLDebug("GDAL_netCDF", "GInt16 Band#%d", iBand);
9853 5 : eErr = NCDFCopyBand<GUInt16>(poSrcBand, poDstBand, nXSize, nYSize,
9854 : GDALScaledProgress, pScaledProgress);
9855 : }
9856 32 : else if (eDT == GDT_UInt32)
9857 : {
9858 2 : CPLDebug("GDAL_netCDF", "GUInt32 Band#%d", iBand);
9859 2 : eErr = NCDFCopyBand<GUInt32>(poSrcBand, poDstBand, nXSize, nYSize,
9860 : GDALScaledProgress, pScaledProgress);
9861 : }
9862 30 : else if (eDT == GDT_Int32)
9863 : {
9864 18 : CPLDebug("GDAL_netCDF", "GInt32 Band#%d", iBand);
9865 18 : eErr = NCDFCopyBand<GInt32>(poSrcBand, poDstBand, nXSize, nYSize,
9866 : GDALScaledProgress, pScaledProgress);
9867 : }
9868 12 : else if (eDT == GDT_UInt64)
9869 : {
9870 2 : CPLDebug("GDAL_netCDF", "GUInt64 Band#%d", iBand);
9871 2 : eErr = NCDFCopyBand<std::uint64_t>(poSrcBand, poDstBand, nXSize,
9872 : nYSize, GDALScaledProgress,
9873 : pScaledProgress);
9874 : }
9875 10 : else if (eDT == GDT_Int64)
9876 : {
9877 2 : CPLDebug("GDAL_netCDF", "GInt64 Band#%d", iBand);
9878 : eErr =
9879 2 : NCDFCopyBand<std::int64_t>(poSrcBand, poDstBand, nXSize, nYSize,
9880 : GDALScaledProgress, pScaledProgress);
9881 : }
9882 8 : else if (eDT == GDT_Float32)
9883 : {
9884 6 : CPLDebug("GDAL_netCDF", "float Band#%d", iBand);
9885 6 : eErr = NCDFCopyBand<float>(poSrcBand, poDstBand, nXSize, nYSize,
9886 : GDALScaledProgress, pScaledProgress);
9887 : }
9888 2 : else if (eDT == GDT_Float64)
9889 : {
9890 2 : CPLDebug("GDAL_netCDF", "double Band#%d", iBand);
9891 2 : eErr = NCDFCopyBand<double>(poSrcBand, poDstBand, nXSize, nYSize,
9892 : GDALScaledProgress, pScaledProgress);
9893 : }
9894 : else
9895 : {
9896 0 : CPLError(CE_Failure, CPLE_NotSupported,
9897 : "The NetCDF driver does not support GDAL data type %d",
9898 : eDT);
9899 : }
9900 :
9901 89 : GDALDestroyScaledProgress(pScaledProgress);
9902 : }
9903 :
9904 56 : delete (poDS);
9905 :
9906 56 : CPLFree(panDimIds);
9907 56 : CPLFree(panBandDimPos);
9908 56 : CPLFree(panBandZLev);
9909 56 : CPLFree(panDimVarIds);
9910 56 : if (papszExtraDimNames)
9911 5 : CSLDestroy(papszExtraDimNames);
9912 :
9913 56 : if (eErr != CE_None)
9914 0 : return nullptr;
9915 :
9916 56 : pfnProgress(0.95, nullptr, pProgressData);
9917 :
9918 : // Re-open dataset so we can return it.
9919 112 : CPLStringList aosOpenOptions;
9920 56 : aosOpenOptions.AddString("VARIABLES_AS_BANDS=YES");
9921 56 : GDALOpenInfo oOpenInfo(pszFilename, GA_Update);
9922 56 : oOpenInfo.nOpenFlags = GDAL_OF_RASTER | GDAL_OF_UPDATE;
9923 56 : oOpenInfo.papszOpenOptions = aosOpenOptions.List();
9924 56 : auto poRetDS = Open(&oOpenInfo);
9925 :
9926 : // PAM cloning is disabled. See bug #4244.
9927 : // if( poDS )
9928 : // poDS->CloneInfo(poSrcDS, GCIF_PAM_DEFAULT);
9929 :
9930 56 : pfnProgress(1.0, nullptr, pProgressData);
9931 :
9932 56 : return poRetDS;
9933 : }
9934 :
9935 : // Note: some logic depends on bIsProjected and bIsGeoGraphic.
9936 : // May not be known when Create() is called, see AddProjectionVars().
9937 252 : void netCDFDataset::ProcessCreationOptions()
9938 : {
9939 : const char *pszConfig =
9940 252 : CSLFetchNameValue(papszCreationOptions, "CONFIG_FILE");
9941 252 : if (pszConfig != nullptr)
9942 : {
9943 4 : if (oWriterConfig.Parse(pszConfig))
9944 : {
9945 : // Override dataset creation options from the config file
9946 2 : std::map<CPLString, CPLString>::iterator oIter;
9947 3 : for (oIter = oWriterConfig.m_oDatasetCreationOptions.begin();
9948 3 : oIter != oWriterConfig.m_oDatasetCreationOptions.end();
9949 1 : ++oIter)
9950 : {
9951 2 : papszCreationOptions = CSLSetNameValue(
9952 2 : papszCreationOptions, oIter->first, oIter->second);
9953 : }
9954 : }
9955 : }
9956 :
9957 : // File format.
9958 252 : eFormat = NCDF_FORMAT_NC;
9959 252 : const char *pszValue = CSLFetchNameValue(papszCreationOptions, "FORMAT");
9960 252 : if (pszValue != nullptr)
9961 : {
9962 93 : if (EQUAL(pszValue, "NC"))
9963 : {
9964 3 : eFormat = NCDF_FORMAT_NC;
9965 : }
9966 : #ifdef NETCDF_HAS_NC2
9967 90 : else if (EQUAL(pszValue, "NC2"))
9968 : {
9969 1 : eFormat = NCDF_FORMAT_NC2;
9970 : }
9971 : #endif
9972 89 : else if (EQUAL(pszValue, "NC4"))
9973 : {
9974 85 : eFormat = NCDF_FORMAT_NC4;
9975 : }
9976 4 : else if (EQUAL(pszValue, "NC4C"))
9977 : {
9978 4 : eFormat = NCDF_FORMAT_NC4C;
9979 : }
9980 : else
9981 : {
9982 0 : CPLError(CE_Failure, CPLE_NotSupported,
9983 : "FORMAT=%s in not supported, using the default NC format.",
9984 : pszValue);
9985 : }
9986 : }
9987 :
9988 : // COMPRESS option.
9989 252 : pszValue = CSLFetchNameValue(papszCreationOptions, "COMPRESS");
9990 252 : if (pszValue != nullptr)
9991 : {
9992 2 : if (EQUAL(pszValue, "NONE"))
9993 : {
9994 1 : eCompress = NCDF_COMPRESS_NONE;
9995 : }
9996 1 : else if (EQUAL(pszValue, "DEFLATE"))
9997 : {
9998 1 : eCompress = NCDF_COMPRESS_DEFLATE;
9999 1 : if (!((eFormat == NCDF_FORMAT_NC4) ||
10000 1 : (eFormat == NCDF_FORMAT_NC4C)))
10001 : {
10002 0 : CPLError(CE_Warning, CPLE_IllegalArg,
10003 : "NOTICE: Format set to NC4C because compression is "
10004 : "set to DEFLATE.");
10005 0 : eFormat = NCDF_FORMAT_NC4C;
10006 : }
10007 : }
10008 : else
10009 : {
10010 0 : CPLError(CE_Failure, CPLE_NotSupported,
10011 : "COMPRESS=%s is not supported.", pszValue);
10012 : }
10013 : }
10014 :
10015 : // ZLEVEL option.
10016 252 : pszValue = CSLFetchNameValue(papszCreationOptions, "ZLEVEL");
10017 252 : if (pszValue != nullptr)
10018 : {
10019 1 : nZLevel = atoi(pszValue);
10020 1 : if (!(nZLevel >= 1 && nZLevel <= 9))
10021 : {
10022 0 : CPLError(CE_Warning, CPLE_IllegalArg,
10023 : "ZLEVEL=%s value not recognised, ignoring.", pszValue);
10024 0 : nZLevel = NCDF_DEFLATE_LEVEL;
10025 : }
10026 : }
10027 :
10028 : // CHUNKING option.
10029 252 : bChunking =
10030 252 : CPL_TO_BOOL(CSLFetchBoolean(papszCreationOptions, "CHUNKING", TRUE));
10031 :
10032 : // MULTIPLE_LAYERS option.
10033 : const char *pszMultipleLayerBehavior =
10034 252 : CSLFetchNameValueDef(papszCreationOptions, "MULTIPLE_LAYERS", "NO");
10035 504 : const char *pszGeometryEnc = CSLFetchNameValueDef(
10036 252 : papszCreationOptions, "GEOMETRY_ENCODING", "CF_1.8");
10037 252 : if (EQUAL(pszMultipleLayerBehavior, "NO") ||
10038 3 : EQUAL(pszGeometryEnc, "CF_1.8"))
10039 : {
10040 249 : eMultipleLayerBehavior = SINGLE_LAYER;
10041 : }
10042 3 : else if (EQUAL(pszMultipleLayerBehavior, "SEPARATE_FILES"))
10043 : {
10044 2 : eMultipleLayerBehavior = SEPARATE_FILES;
10045 : }
10046 1 : else if (EQUAL(pszMultipleLayerBehavior, "SEPARATE_GROUPS"))
10047 : {
10048 1 : if (eFormat == NCDF_FORMAT_NC4)
10049 : {
10050 1 : eMultipleLayerBehavior = SEPARATE_GROUPS;
10051 : }
10052 : else
10053 : {
10054 0 : CPLError(CE_Warning, CPLE_IllegalArg,
10055 : "MULTIPLE_LAYERS=%s is recognised only with FORMAT=NC4",
10056 : pszMultipleLayerBehavior);
10057 : }
10058 : }
10059 : else
10060 : {
10061 0 : CPLError(CE_Warning, CPLE_IllegalArg,
10062 : "MULTIPLE_LAYERS=%s not recognised", pszMultipleLayerBehavior);
10063 : }
10064 :
10065 : // Set nCreateMode based on eFormat.
10066 252 : switch (eFormat)
10067 : {
10068 : #ifdef NETCDF_HAS_NC2
10069 1 : case NCDF_FORMAT_NC2:
10070 1 : nCreateMode = NC_CLOBBER | NC_64BIT_OFFSET;
10071 1 : break;
10072 : #endif
10073 85 : case NCDF_FORMAT_NC4:
10074 85 : nCreateMode = NC_CLOBBER | NC_NETCDF4;
10075 85 : break;
10076 4 : case NCDF_FORMAT_NC4C:
10077 4 : nCreateMode = NC_CLOBBER | NC_NETCDF4 | NC_CLASSIC_MODEL;
10078 4 : break;
10079 162 : case NCDF_FORMAT_NC:
10080 : default:
10081 162 : nCreateMode = NC_CLOBBER;
10082 162 : break;
10083 : }
10084 :
10085 252 : CPLDebug("GDAL_netCDF", "file options: format=%d compress=%d zlevel=%d",
10086 252 : eFormat, eCompress, nZLevel);
10087 252 : }
10088 :
10089 274 : int netCDFDataset::DefVarDeflate(int nVarId, bool bChunkingArg)
10090 : {
10091 274 : if (eCompress == NCDF_COMPRESS_DEFLATE)
10092 : {
10093 : // Must set chunk size to avoid huge performance hit (set
10094 : // bChunkingArg=TRUE)
10095 : // perhaps another solution it to change the chunk cache?
10096 : // http://www.unidata.ucar.edu/software/netcdf/docs/netcdf.html#Chunk-Cache
10097 : // TODO: make sure this is okay.
10098 1 : CPLDebug("GDAL_netCDF", "DefVarDeflate(%d, %d) nZlevel=%d", nVarId,
10099 : static_cast<int>(bChunkingArg), nZLevel);
10100 :
10101 1 : int status = nc_def_var_deflate(cdfid, nVarId, 1, 1, nZLevel);
10102 1 : NCDF_ERR(status);
10103 :
10104 1 : if (status == NC_NOERR && bChunkingArg && bChunking)
10105 : {
10106 : // set chunking to be 1 for all dims, except X dim
10107 : // size_t chunksize[] = { 1, (size_t)nRasterXSize };
10108 : size_t chunksize[MAX_NC_DIMS];
10109 : int nd;
10110 1 : nc_inq_varndims(cdfid, nVarId, &nd);
10111 1 : chunksize[0] = (size_t)1;
10112 1 : chunksize[1] = (size_t)1;
10113 1 : for (int i = 2; i < nd; i++)
10114 0 : chunksize[i] = (size_t)1;
10115 1 : chunksize[nd - 1] = (size_t)nRasterXSize;
10116 :
10117 : // Config options just for testing purposes
10118 : const char *pszBlockXSize =
10119 1 : CPLGetConfigOption("BLOCKXSIZE", nullptr);
10120 1 : if (pszBlockXSize)
10121 0 : chunksize[nd - 1] = (size_t)atoi(pszBlockXSize);
10122 :
10123 : const char *pszBlockYSize =
10124 1 : CPLGetConfigOption("BLOCKYSIZE", nullptr);
10125 1 : if (nd >= 2 && pszBlockYSize)
10126 0 : chunksize[nd - 2] = (size_t)atoi(pszBlockYSize);
10127 :
10128 1 : CPLDebug("GDAL_netCDF",
10129 : "DefVarDeflate() chunksize={%ld, %ld} chunkX=%ld nd=%d",
10130 1 : (long)chunksize[0], (long)chunksize[1],
10131 1 : (long)chunksize[nd - 1], nd);
10132 : #ifdef NCDF_DEBUG
10133 : for (int i = 0; i < nd; i++)
10134 : CPLDebug("GDAL_netCDF", "DefVarDeflate() chunk[%d]=%ld", i,
10135 : chunksize[i]);
10136 : #endif
10137 :
10138 1 : status = nc_def_var_chunking(cdfid, nVarId, NC_CHUNKED, chunksize);
10139 1 : NCDF_ERR(status);
10140 : }
10141 : else
10142 : {
10143 0 : CPLDebug("GDAL_netCDF", "chunksize not set");
10144 : }
10145 1 : return status;
10146 : }
10147 273 : return NC_NOERR;
10148 : }
10149 :
10150 : /************************************************************************/
10151 : /* NCDFUnloadDriver() */
10152 : /************************************************************************/
10153 :
10154 8 : static void NCDFUnloadDriver(CPL_UNUSED GDALDriver *poDriver)
10155 : {
10156 8 : if (hNCMutex != nullptr)
10157 4 : CPLDestroyMutex(hNCMutex);
10158 8 : hNCMutex = nullptr;
10159 8 : }
10160 :
10161 : /************************************************************************/
10162 : /* GDALRegister_netCDF() */
10163 : /************************************************************************/
10164 :
10165 : class GDALnetCDFDriver final : public GDALDriver
10166 : {
10167 : public:
10168 14 : GDALnetCDFDriver() = default;
10169 :
10170 1131 : const char *GetMetadataItem(const char *pszName,
10171 : const char *pszDomain) override
10172 : {
10173 1131 : if (EQUAL(pszName, GDAL_DCAP_VIRTUALIO))
10174 : {
10175 13 : InitializeDCAPVirtualIO();
10176 : }
10177 1131 : return GDALDriver::GetMetadataItem(pszName, pszDomain);
10178 : }
10179 :
10180 84 : char **GetMetadata(const char *pszDomain) override
10181 : {
10182 84 : InitializeDCAPVirtualIO();
10183 84 : return GDALDriver::GetMetadata(pszDomain);
10184 : }
10185 :
10186 : private:
10187 : bool m_bInitialized = false;
10188 :
10189 97 : void InitializeDCAPVirtualIO()
10190 : {
10191 97 : if (!m_bInitialized)
10192 : {
10193 11 : m_bInitialized = true;
10194 :
10195 : #ifdef ENABLE_UFFD
10196 11 : if (CPLIsUserFaultMappingSupported())
10197 : {
10198 11 : SetMetadataItem(GDAL_DCAP_VIRTUALIO, "YES");
10199 : }
10200 : #endif
10201 : }
10202 97 : }
10203 : };
10204 :
10205 14 : void GDALRegister_netCDF()
10206 :
10207 : {
10208 14 : if (!GDAL_CHECK_VERSION("netCDF driver"))
10209 0 : return;
10210 :
10211 14 : if (GDALGetDriverByName(DRIVER_NAME) != nullptr)
10212 0 : return;
10213 :
10214 14 : GDALDriver *poDriver = new GDALnetCDFDriver();
10215 14 : netCDFDriverSetCommonMetadata(poDriver);
10216 :
10217 14 : poDriver->SetMetadataItem("NETCDF_CONVENTIONS",
10218 14 : GDAL_DEFAULT_NCDF_CONVENTIONS);
10219 14 : poDriver->SetMetadataItem("NETCDF_VERSION", nc_inq_libvers());
10220 :
10221 : // Set pfns and register driver.
10222 14 : poDriver->pfnOpen = netCDFDataset::Open;
10223 14 : poDriver->pfnCreateCopy = netCDFDataset::CreateCopy;
10224 14 : poDriver->pfnCreate = netCDFDataset::Create;
10225 14 : poDriver->pfnCreateMultiDimensional = netCDFDataset::CreateMultiDimensional;
10226 14 : poDriver->pfnUnloadDriver = NCDFUnloadDriver;
10227 :
10228 14 : GetGDALDriverManager()->RegisterDriver(poDriver);
10229 : }
10230 :
10231 : /************************************************************************/
10232 : /* New functions */
10233 : /************************************************************************/
10234 :
10235 : /* Test for GDAL version string >= target */
10236 238 : static bool NCDFIsGDALVersionGTE(const char *pszVersion, int nTarget)
10237 : {
10238 :
10239 : // Valid strings are "GDAL 1.9dev, released 2011/01/18" and "GDAL 1.8.1 ".
10240 238 : if (pszVersion == nullptr || EQUAL(pszVersion, ""))
10241 0 : return false;
10242 238 : else if (!STARTS_WITH_CI(pszVersion, "GDAL "))
10243 0 : return false;
10244 : // 2.0dev of 2011/12/29 has been later renamed as 1.10dev.
10245 238 : else if (EQUAL("GDAL 2.0dev, released 2011/12/29", pszVersion))
10246 0 : return nTarget <= GDAL_COMPUTE_VERSION(1, 10, 0);
10247 238 : else if (STARTS_WITH_CI(pszVersion, "GDAL 1.9dev"))
10248 2 : return nTarget <= 1900;
10249 236 : else if (STARTS_WITH_CI(pszVersion, "GDAL 1.8dev"))
10250 0 : return nTarget <= 1800;
10251 :
10252 236 : char **papszTokens = CSLTokenizeString2(pszVersion + 5, ".", 0);
10253 :
10254 236 : int nVersions[] = {0, 0, 0, 0};
10255 944 : for (int iToken = 0; papszTokens && iToken < 4 && papszTokens[iToken];
10256 : iToken++)
10257 : {
10258 708 : nVersions[iToken] = atoi(papszTokens[iToken]);
10259 708 : if (nVersions[iToken] < 0)
10260 0 : nVersions[iToken] = 0;
10261 708 : else if (nVersions[iToken] > 99)
10262 0 : nVersions[iToken] = 99;
10263 : }
10264 :
10265 236 : int nVersion = 0;
10266 236 : if (nVersions[0] > 1 || nVersions[1] >= 10)
10267 236 : nVersion =
10268 236 : GDAL_COMPUTE_VERSION(nVersions[0], nVersions[1], nVersions[2]);
10269 : else
10270 0 : nVersion = nVersions[0] * 1000 + nVersions[1] * 100 +
10271 0 : nVersions[2] * 10 + nVersions[3];
10272 :
10273 236 : CSLDestroy(papszTokens);
10274 236 : return nTarget <= nVersion;
10275 : }
10276 :
10277 : // Add Conventions, GDAL version and history.
10278 165 : static void NCDFAddGDALHistory(int fpImage, const char *pszFilename,
10279 : bool bWriteGDALVersion, bool bWriteGDALHistory,
10280 : const char *pszOldHist,
10281 : const char *pszFunctionName,
10282 : const char *pszCFVersion)
10283 : {
10284 165 : if (pszCFVersion == nullptr)
10285 : {
10286 40 : pszCFVersion = GDAL_DEFAULT_NCDF_CONVENTIONS;
10287 : }
10288 165 : int status = nc_put_att_text(fpImage, NC_GLOBAL, "Conventions",
10289 : strlen(pszCFVersion), pszCFVersion);
10290 165 : NCDF_ERR(status);
10291 :
10292 165 : if (bWriteGDALVersion)
10293 : {
10294 163 : const char *pszNCDF_GDAL = GDALVersionInfo("--version");
10295 163 : status = nc_put_att_text(fpImage, NC_GLOBAL, "GDAL",
10296 : strlen(pszNCDF_GDAL), pszNCDF_GDAL);
10297 163 : NCDF_ERR(status);
10298 : }
10299 :
10300 165 : if (bWriteGDALHistory)
10301 : {
10302 : // Add history.
10303 326 : CPLString osTmp;
10304 : #ifdef GDAL_SET_CMD_LINE_DEFINED_TMP
10305 : if (!EQUAL(GDALGetCmdLine(), ""))
10306 : osTmp = GDALGetCmdLine();
10307 : else
10308 : osTmp =
10309 : CPLSPrintf("GDAL %s( %s, ... )", pszFunctionName, pszFilename);
10310 : #else
10311 163 : osTmp = CPLSPrintf("GDAL %s( %s, ... )", pszFunctionName, pszFilename);
10312 : #endif
10313 :
10314 163 : NCDFAddHistory(fpImage, osTmp.c_str(), pszOldHist);
10315 : }
10316 2 : else if (pszOldHist != nullptr)
10317 : {
10318 0 : status = nc_put_att_text(fpImage, NC_GLOBAL, "history",
10319 : strlen(pszOldHist), pszOldHist);
10320 0 : NCDF_ERR(status);
10321 : }
10322 165 : }
10323 :
10324 : // Code taken from cdo and libcdi, used for writing the history attribute.
10325 :
10326 : // void cdoDefHistory(int fileID, char *histstring)
10327 163 : static void NCDFAddHistory(int fpImage, const char *pszAddHist,
10328 : const char *pszOldHist)
10329 : {
10330 : // Check pszOldHist - as if there was no previous history, it will be
10331 : // a null pointer - if so set as empty.
10332 163 : if (nullptr == pszOldHist)
10333 : {
10334 51 : pszOldHist = "";
10335 : }
10336 :
10337 : char strtime[32];
10338 163 : strtime[0] = '\0';
10339 :
10340 163 : time_t tp = time(nullptr);
10341 163 : if (tp != -1)
10342 : {
10343 : struct tm ltime;
10344 163 : VSILocalTime(&tp, <ime);
10345 163 : (void)strftime(strtime, sizeof(strtime),
10346 : "%a %b %d %H:%M:%S %Y: ", <ime);
10347 : }
10348 :
10349 : // status = nc_get_att_text(fpImage, NC_GLOBAL,
10350 : // "history", pszOldHist);
10351 : // printf("status: %d pszOldHist: [%s]\n",status,pszOldHist);
10352 :
10353 163 : size_t nNewHistSize =
10354 163 : strlen(pszOldHist) + strlen(strtime) + strlen(pszAddHist) + 1 + 1;
10355 : char *pszNewHist =
10356 163 : static_cast<char *>(CPLMalloc(nNewHistSize * sizeof(char)));
10357 :
10358 163 : strcpy(pszNewHist, strtime);
10359 163 : strcat(pszNewHist, pszAddHist);
10360 :
10361 : // int disableHistory = FALSE;
10362 : // if( !disableHistory )
10363 : {
10364 163 : if (!EQUAL(pszOldHist, ""))
10365 3 : strcat(pszNewHist, "\n");
10366 163 : strcat(pszNewHist, pszOldHist);
10367 : }
10368 :
10369 163 : const int status = nc_put_att_text(fpImage, NC_GLOBAL, "history",
10370 : strlen(pszNewHist), pszNewHist);
10371 163 : NCDF_ERR(status);
10372 :
10373 163 : CPLFree(pszNewHist);
10374 163 : }
10375 :
10376 5954 : static CPLErr NCDFSafeStrcat(char **ppszDest, const char *pszSrc,
10377 : size_t *nDestSize)
10378 : {
10379 : /* Reallocate the data string until the content fits */
10380 5954 : while (*nDestSize < (strlen(*ppszDest) + strlen(pszSrc) + 1))
10381 : {
10382 394 : (*nDestSize) *= 2;
10383 394 : *ppszDest = static_cast<char *>(
10384 394 : CPLRealloc(reinterpret_cast<void *>(*ppszDest), *nDestSize));
10385 : #ifdef NCDF_DEBUG
10386 : CPLDebug("GDAL_netCDF", "NCDFSafeStrcat() resized str from %ld to %ld",
10387 : (*nDestSize) / 2, *nDestSize);
10388 : #endif
10389 : }
10390 5560 : strcat(*ppszDest, pszSrc);
10391 :
10392 5560 : return CE_None;
10393 : }
10394 :
10395 : /* helper function for NCDFGetAttr() */
10396 : /* if pdfValue != nullptr, sets *pdfValue to first value returned */
10397 : /* if ppszValue != nullptr, sets *ppszValue with all attribute values */
10398 : /* *ppszValue is the responsibility of the caller and must be freed */
10399 62466 : static CPLErr NCDFGetAttr1(int nCdfId, int nVarId, const char *pszAttrName,
10400 : double *pdfValue, char **ppszValue)
10401 : {
10402 62466 : nc_type nAttrType = NC_NAT;
10403 62466 : size_t nAttrLen = 0;
10404 :
10405 62466 : if (ppszValue)
10406 61320 : *ppszValue = nullptr;
10407 :
10408 62466 : int status = nc_inq_att(nCdfId, nVarId, pszAttrName, &nAttrType, &nAttrLen);
10409 62466 : if (status != NC_NOERR)
10410 33685 : return CE_Failure;
10411 :
10412 : #ifdef NCDF_DEBUG
10413 : CPLDebug("GDAL_netCDF", "NCDFGetAttr1(%s) len=%ld type=%d", pszAttrName,
10414 : nAttrLen, nAttrType);
10415 : #endif
10416 28781 : if (nAttrLen == 0 && nAttrType != NC_CHAR)
10417 1 : return CE_Failure;
10418 :
10419 : /* Allocate guaranteed minimum size (use 10 or 20 if not a string) */
10420 28780 : size_t nAttrValueSize = nAttrLen + 1;
10421 28780 : if (nAttrType != NC_CHAR && nAttrValueSize < 10)
10422 3101 : nAttrValueSize = 10;
10423 28780 : if (nAttrType == NC_DOUBLE && nAttrValueSize < 20)
10424 1515 : nAttrValueSize = 20;
10425 28780 : if (nAttrType == NC_INT64 && nAttrValueSize < 20)
10426 20 : nAttrValueSize = 22;
10427 : char *pszAttrValue =
10428 28780 : static_cast<char *>(CPLCalloc(nAttrValueSize, sizeof(char)));
10429 28780 : *pszAttrValue = '\0';
10430 :
10431 28780 : if (nAttrLen > 1 && nAttrType != NC_CHAR)
10432 566 : NCDFSafeStrcat(&pszAttrValue, "{", &nAttrValueSize);
10433 :
10434 28780 : double dfValue = 0.0;
10435 28780 : size_t m = 0;
10436 : char szTemp[256];
10437 28780 : bool bSetDoubleFromStr = false;
10438 :
10439 28780 : switch (nAttrType)
10440 : {
10441 25677 : case NC_CHAR:
10442 25677 : CPL_IGNORE_RET_VAL(
10443 25677 : nc_get_att_text(nCdfId, nVarId, pszAttrName, pszAttrValue));
10444 25677 : pszAttrValue[nAttrLen] = '\0';
10445 25677 : bSetDoubleFromStr = true;
10446 25677 : dfValue = 0.0;
10447 25677 : break;
10448 90 : case NC_BYTE:
10449 : {
10450 : signed char *pscTemp = static_cast<signed char *>(
10451 90 : CPLCalloc(nAttrLen, sizeof(signed char)));
10452 90 : nc_get_att_schar(nCdfId, nVarId, pszAttrName, pscTemp);
10453 90 : dfValue = static_cast<double>(pscTemp[0]);
10454 90 : if (nAttrLen > 1)
10455 : {
10456 20 : for (m = 0; m < nAttrLen - 1; m++)
10457 : {
10458 11 : snprintf(szTemp, sizeof(szTemp), "%d,", pscTemp[m]);
10459 11 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10460 : }
10461 : }
10462 90 : snprintf(szTemp, sizeof(szTemp), "%d", pscTemp[m]);
10463 90 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10464 90 : CPLFree(pscTemp);
10465 90 : break;
10466 : }
10467 469 : case NC_SHORT:
10468 : {
10469 : short *psTemp =
10470 469 : static_cast<short *>(CPLCalloc(nAttrLen, sizeof(short)));
10471 469 : nc_get_att_short(nCdfId, nVarId, pszAttrName, psTemp);
10472 469 : dfValue = static_cast<double>(psTemp[0]);
10473 469 : if (nAttrLen > 1)
10474 : {
10475 736 : for (m = 0; m < nAttrLen - 1; m++)
10476 : {
10477 368 : snprintf(szTemp, sizeof(szTemp), "%d,", psTemp[m]);
10478 368 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10479 : }
10480 : }
10481 469 : snprintf(szTemp, sizeof(szTemp), "%d", psTemp[m]);
10482 469 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10483 469 : CPLFree(psTemp);
10484 469 : break;
10485 : }
10486 524 : case NC_INT:
10487 : {
10488 524 : int *pnTemp = static_cast<int *>(CPLCalloc(nAttrLen, sizeof(int)));
10489 524 : nc_get_att_int(nCdfId, nVarId, pszAttrName, pnTemp);
10490 524 : dfValue = static_cast<double>(pnTemp[0]);
10491 524 : if (nAttrLen > 1)
10492 : {
10493 214 : for (m = 0; m < nAttrLen - 1; m++)
10494 : {
10495 137 : snprintf(szTemp, sizeof(szTemp), "%d,", pnTemp[m]);
10496 137 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10497 : }
10498 : }
10499 524 : snprintf(szTemp, sizeof(szTemp), "%d", pnTemp[m]);
10500 524 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10501 524 : CPLFree(pnTemp);
10502 524 : break;
10503 : }
10504 391 : case NC_FLOAT:
10505 : {
10506 : float *pfTemp =
10507 391 : static_cast<float *>(CPLCalloc(nAttrLen, sizeof(float)));
10508 391 : nc_get_att_float(nCdfId, nVarId, pszAttrName, pfTemp);
10509 391 : dfValue = static_cast<double>(pfTemp[0]);
10510 391 : if (nAttrLen > 1)
10511 : {
10512 56 : for (m = 0; m < nAttrLen - 1; m++)
10513 : {
10514 28 : CPLsnprintf(szTemp, sizeof(szTemp), "%.8g,", pfTemp[m]);
10515 28 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10516 : }
10517 : }
10518 391 : CPLsnprintf(szTemp, sizeof(szTemp), "%.8g", pfTemp[m]);
10519 391 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10520 391 : CPLFree(pfTemp);
10521 391 : break;
10522 : }
10523 1515 : case NC_DOUBLE:
10524 : {
10525 : double *pdfTemp =
10526 1515 : static_cast<double *>(CPLCalloc(nAttrLen, sizeof(double)));
10527 1515 : nc_get_att_double(nCdfId, nVarId, pszAttrName, pdfTemp);
10528 1515 : dfValue = pdfTemp[0];
10529 1515 : if (nAttrLen > 1)
10530 : {
10531 162 : for (m = 0; m < nAttrLen - 1; m++)
10532 : {
10533 88 : CPLsnprintf(szTemp, sizeof(szTemp), "%.16g,", pdfTemp[m]);
10534 88 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10535 : }
10536 : }
10537 1515 : CPLsnprintf(szTemp, sizeof(szTemp), "%.16g", pdfTemp[m]);
10538 1515 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10539 1515 : CPLFree(pdfTemp);
10540 1515 : break;
10541 : }
10542 8 : case NC_STRING:
10543 : {
10544 : char **ppszTemp =
10545 8 : static_cast<char **>(CPLCalloc(nAttrLen, sizeof(char *)));
10546 8 : nc_get_att_string(nCdfId, nVarId, pszAttrName, ppszTemp);
10547 8 : bSetDoubleFromStr = true;
10548 8 : dfValue = 0.0;
10549 8 : if (nAttrLen > 1)
10550 : {
10551 15 : for (m = 0; m < nAttrLen - 1; m++)
10552 : {
10553 10 : NCDFSafeStrcat(&pszAttrValue,
10554 10 : ppszTemp[m] ? ppszTemp[m] : "{NULL}",
10555 : &nAttrValueSize);
10556 10 : NCDFSafeStrcat(&pszAttrValue, ",", &nAttrValueSize);
10557 : }
10558 : }
10559 8 : NCDFSafeStrcat(&pszAttrValue, ppszTemp[m] ? ppszTemp[m] : "{NULL}",
10560 : &nAttrValueSize);
10561 8 : nc_free_string(nAttrLen, ppszTemp);
10562 8 : CPLFree(ppszTemp);
10563 8 : break;
10564 : }
10565 26 : case NC_UBYTE:
10566 : {
10567 : unsigned char *pucTemp = static_cast<unsigned char *>(
10568 26 : CPLCalloc(nAttrLen, sizeof(unsigned char)));
10569 26 : nc_get_att_uchar(nCdfId, nVarId, pszAttrName, pucTemp);
10570 26 : dfValue = static_cast<double>(pucTemp[0]);
10571 26 : if (nAttrLen > 1)
10572 : {
10573 0 : for (m = 0; m < nAttrLen - 1; m++)
10574 : {
10575 0 : CPLsnprintf(szTemp, sizeof(szTemp), "%u,", pucTemp[m]);
10576 0 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10577 : }
10578 : }
10579 26 : CPLsnprintf(szTemp, sizeof(szTemp), "%u", pucTemp[m]);
10580 26 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10581 26 : CPLFree(pucTemp);
10582 26 : break;
10583 : }
10584 24 : case NC_USHORT:
10585 : {
10586 : unsigned short *pusTemp;
10587 : pusTemp = static_cast<unsigned short *>(
10588 24 : CPLCalloc(nAttrLen, sizeof(unsigned short)));
10589 24 : nc_get_att_ushort(nCdfId, nVarId, pszAttrName, pusTemp);
10590 24 : dfValue = static_cast<double>(pusTemp[0]);
10591 24 : if (nAttrLen > 1)
10592 : {
10593 10 : for (m = 0; m < nAttrLen - 1; m++)
10594 : {
10595 5 : CPLsnprintf(szTemp, sizeof(szTemp), "%u,", pusTemp[m]);
10596 5 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10597 : }
10598 : }
10599 24 : CPLsnprintf(szTemp, sizeof(szTemp), "%u", pusTemp[m]);
10600 24 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10601 24 : CPLFree(pusTemp);
10602 24 : break;
10603 : }
10604 16 : case NC_UINT:
10605 : {
10606 : unsigned int *punTemp =
10607 16 : static_cast<unsigned int *>(CPLCalloc(nAttrLen, sizeof(int)));
10608 16 : nc_get_att_uint(nCdfId, nVarId, pszAttrName, punTemp);
10609 16 : dfValue = static_cast<double>(punTemp[0]);
10610 16 : if (nAttrLen > 1)
10611 : {
10612 0 : for (m = 0; m < nAttrLen - 1; m++)
10613 : {
10614 0 : CPLsnprintf(szTemp, sizeof(szTemp), "%u,", punTemp[m]);
10615 0 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10616 : }
10617 : }
10618 16 : CPLsnprintf(szTemp, sizeof(szTemp), "%u", punTemp[m]);
10619 16 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10620 16 : CPLFree(punTemp);
10621 16 : break;
10622 : }
10623 20 : case NC_INT64:
10624 : {
10625 : GIntBig *panTemp =
10626 20 : static_cast<GIntBig *>(CPLCalloc(nAttrLen, sizeof(GIntBig)));
10627 20 : nc_get_att_longlong(nCdfId, nVarId, pszAttrName, panTemp);
10628 20 : dfValue = static_cast<double>(panTemp[0]);
10629 20 : if (nAttrLen > 1)
10630 : {
10631 0 : for (m = 0; m < nAttrLen - 1; m++)
10632 : {
10633 0 : CPLsnprintf(szTemp, sizeof(szTemp), CPL_FRMT_GIB ",",
10634 0 : panTemp[m]);
10635 0 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10636 : }
10637 : }
10638 20 : CPLsnprintf(szTemp, sizeof(szTemp), CPL_FRMT_GIB, panTemp[m]);
10639 20 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10640 20 : CPLFree(panTemp);
10641 20 : break;
10642 : }
10643 20 : case NC_UINT64:
10644 : {
10645 : GUIntBig *panTemp =
10646 20 : static_cast<GUIntBig *>(CPLCalloc(nAttrLen, sizeof(GUIntBig)));
10647 20 : nc_get_att_ulonglong(nCdfId, nVarId, pszAttrName, panTemp);
10648 20 : dfValue = static_cast<double>(panTemp[0]);
10649 20 : if (nAttrLen > 1)
10650 : {
10651 0 : for (m = 0; m < nAttrLen - 1; m++)
10652 : {
10653 0 : CPLsnprintf(szTemp, sizeof(szTemp), CPL_FRMT_GUIB ",",
10654 0 : panTemp[m]);
10655 0 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10656 : }
10657 : }
10658 20 : CPLsnprintf(szTemp, sizeof(szTemp), CPL_FRMT_GUIB, panTemp[m]);
10659 20 : NCDFSafeStrcat(&pszAttrValue, szTemp, &nAttrValueSize);
10660 20 : CPLFree(panTemp);
10661 20 : break;
10662 : }
10663 0 : default:
10664 0 : CPLDebug("GDAL_netCDF",
10665 : "NCDFGetAttr unsupported type %d for attribute %s",
10666 : nAttrType, pszAttrName);
10667 0 : break;
10668 : }
10669 :
10670 28780 : if (nAttrLen > 1 && nAttrType != NC_CHAR)
10671 566 : NCDFSafeStrcat(&pszAttrValue, "}", &nAttrValueSize);
10672 :
10673 28780 : if (bSetDoubleFromStr)
10674 : {
10675 25685 : if (CPLGetValueType(pszAttrValue) == CPL_VALUE_STRING)
10676 : {
10677 25503 : if (ppszValue == nullptr && pdfValue != nullptr)
10678 : {
10679 1 : CPLFree(pszAttrValue);
10680 1 : return CE_Failure;
10681 : }
10682 : }
10683 25684 : dfValue = CPLAtof(pszAttrValue);
10684 : }
10685 :
10686 : /* set return values */
10687 28779 : if (ppszValue)
10688 28467 : *ppszValue = pszAttrValue;
10689 : else
10690 312 : CPLFree(pszAttrValue);
10691 :
10692 28779 : if (pdfValue)
10693 312 : *pdfValue = dfValue;
10694 :
10695 28779 : return CE_None;
10696 : }
10697 :
10698 : /* sets pdfValue to first value found */
10699 1146 : CPLErr NCDFGetAttr(int nCdfId, int nVarId, const char *pszAttrName,
10700 : double *pdfValue)
10701 : {
10702 1146 : return NCDFGetAttr1(nCdfId, nVarId, pszAttrName, pdfValue, nullptr);
10703 : }
10704 :
10705 : /* pszValue is the responsibility of the caller and must be freed */
10706 61320 : CPLErr NCDFGetAttr(int nCdfId, int nVarId, const char *pszAttrName,
10707 : char **pszValue)
10708 : {
10709 61320 : return NCDFGetAttr1(nCdfId, nVarId, pszAttrName, nullptr, pszValue);
10710 : }
10711 :
10712 : /* By default write NC_CHAR, but detect for int/float/double and */
10713 : /* NC4 string arrays */
10714 105 : static CPLErr NCDFPutAttr(int nCdfId, int nVarId, const char *pszAttrName,
10715 : const char *pszValue)
10716 : {
10717 105 : int status = 0;
10718 105 : char *pszTemp = nullptr;
10719 :
10720 : /* get the attribute values as tokens */
10721 105 : char **papszValues = NCDFTokenizeArray(pszValue);
10722 105 : if (papszValues == nullptr)
10723 0 : return CE_Failure;
10724 :
10725 105 : size_t nAttrLen = CSLCount(papszValues);
10726 :
10727 : /* first detect type */
10728 105 : nc_type nAttrType = NC_CHAR;
10729 105 : nc_type nTmpAttrType = NC_CHAR;
10730 223 : for (size_t i = 0; i < nAttrLen; i++)
10731 : {
10732 118 : nTmpAttrType = NC_CHAR;
10733 118 : bool bFoundType = false;
10734 118 : errno = 0;
10735 118 : int nValue = static_cast<int>(strtol(papszValues[i], &pszTemp, 10));
10736 : /* test for int */
10737 : /* TODO test for Byte and short - can this be done safely? */
10738 118 : if (errno == 0 && papszValues[i] != pszTemp && *pszTemp == 0)
10739 : {
10740 : char szTemp[256];
10741 19 : CPLsnprintf(szTemp, sizeof(szTemp), "%d", nValue);
10742 19 : if (EQUAL(szTemp, papszValues[i]))
10743 : {
10744 19 : bFoundType = true;
10745 19 : nTmpAttrType = NC_INT;
10746 : }
10747 : else
10748 : {
10749 : unsigned int unValue = static_cast<unsigned int>(
10750 0 : strtoul(papszValues[i], &pszTemp, 10));
10751 0 : CPLsnprintf(szTemp, sizeof(szTemp), "%u", unValue);
10752 0 : if (EQUAL(szTemp, papszValues[i]))
10753 : {
10754 0 : bFoundType = true;
10755 0 : nTmpAttrType = NC_UINT;
10756 : }
10757 : }
10758 : }
10759 118 : if (!bFoundType)
10760 : {
10761 : /* test for double */
10762 99 : errno = 0;
10763 99 : double dfValue = CPLStrtod(papszValues[i], &pszTemp);
10764 99 : if ((errno == 0) && (papszValues[i] != pszTemp) && (*pszTemp == 0))
10765 : {
10766 : // Test for float instead of double.
10767 : // strtof() is C89, which is not available in MSVC.
10768 : // See if we loose precision if we cast to float and write to
10769 : // char*.
10770 14 : float fValue = float(dfValue);
10771 : char szTemp[256];
10772 14 : CPLsnprintf(szTemp, sizeof(szTemp), "%.8g", fValue);
10773 14 : if (EQUAL(szTemp, papszValues[i]))
10774 8 : nTmpAttrType = NC_FLOAT;
10775 : else
10776 6 : nTmpAttrType = NC_DOUBLE;
10777 : }
10778 : }
10779 118 : if ((nTmpAttrType <= NC_DOUBLE && nAttrType <= NC_DOUBLE &&
10780 98 : nTmpAttrType > nAttrType) ||
10781 98 : (nTmpAttrType == NC_UINT && nAttrType < NC_FLOAT) ||
10782 5 : (nTmpAttrType >= NC_FLOAT && nAttrType == NC_UINT))
10783 20 : nAttrType = nTmpAttrType;
10784 : }
10785 :
10786 : #ifdef DEBUG
10787 105 : if (EQUAL(pszAttrName, "DEBUG_EMPTY_DOUBLE_ATTR"))
10788 : {
10789 0 : nAttrType = NC_DOUBLE;
10790 0 : nAttrLen = 0;
10791 : }
10792 : #endif
10793 :
10794 : /* now write the data */
10795 105 : if (nAttrType == NC_CHAR)
10796 : {
10797 85 : int nTmpFormat = 0;
10798 85 : if (nAttrLen > 1)
10799 : {
10800 0 : status = nc_inq_format(nCdfId, &nTmpFormat);
10801 0 : NCDF_ERR(status);
10802 : }
10803 85 : if (nAttrLen > 1 && nTmpFormat == NCDF_FORMAT_NC4)
10804 0 : status = nc_put_att_string(nCdfId, nVarId, pszAttrName, nAttrLen,
10805 : const_cast<const char **>(papszValues));
10806 : else
10807 85 : status = nc_put_att_text(nCdfId, nVarId, pszAttrName,
10808 : strlen(pszValue), pszValue);
10809 85 : NCDF_ERR(status);
10810 : }
10811 : else
10812 : {
10813 20 : switch (nAttrType)
10814 : {
10815 11 : case NC_INT:
10816 : {
10817 : int *pnTemp =
10818 11 : static_cast<int *>(CPLCalloc(nAttrLen, sizeof(int)));
10819 30 : for (size_t i = 0; i < nAttrLen; i++)
10820 : {
10821 19 : pnTemp[i] =
10822 19 : static_cast<int>(strtol(papszValues[i], &pszTemp, 10));
10823 : }
10824 11 : status = nc_put_att_int(nCdfId, nVarId, pszAttrName, NC_INT,
10825 : nAttrLen, pnTemp);
10826 11 : NCDF_ERR(status);
10827 11 : CPLFree(pnTemp);
10828 11 : break;
10829 : }
10830 0 : case NC_UINT:
10831 : {
10832 : unsigned int *punTemp = static_cast<unsigned int *>(
10833 0 : CPLCalloc(nAttrLen, sizeof(unsigned int)));
10834 0 : for (size_t i = 0; i < nAttrLen; i++)
10835 : {
10836 0 : punTemp[i] = static_cast<unsigned int>(
10837 0 : strtol(papszValues[i], &pszTemp, 10));
10838 : }
10839 0 : status = nc_put_att_uint(nCdfId, nVarId, pszAttrName, NC_UINT,
10840 : nAttrLen, punTemp);
10841 0 : NCDF_ERR(status);
10842 0 : CPLFree(punTemp);
10843 0 : break;
10844 : }
10845 6 : case NC_FLOAT:
10846 : {
10847 : float *pfTemp =
10848 6 : static_cast<float *>(CPLCalloc(nAttrLen, sizeof(float)));
10849 14 : for (size_t i = 0; i < nAttrLen; i++)
10850 : {
10851 8 : pfTemp[i] =
10852 8 : static_cast<float>(CPLStrtod(papszValues[i], &pszTemp));
10853 : }
10854 6 : status = nc_put_att_float(nCdfId, nVarId, pszAttrName, NC_FLOAT,
10855 : nAttrLen, pfTemp);
10856 6 : NCDF_ERR(status);
10857 6 : CPLFree(pfTemp);
10858 6 : break;
10859 : }
10860 3 : case NC_DOUBLE:
10861 : {
10862 : double *pdfTemp =
10863 3 : static_cast<double *>(CPLCalloc(nAttrLen, sizeof(double)));
10864 9 : for (size_t i = 0; i < nAttrLen; i++)
10865 : {
10866 6 : pdfTemp[i] = CPLStrtod(papszValues[i], &pszTemp);
10867 : }
10868 3 : status = nc_put_att_double(nCdfId, nVarId, pszAttrName,
10869 : NC_DOUBLE, nAttrLen, pdfTemp);
10870 3 : NCDF_ERR(status);
10871 3 : CPLFree(pdfTemp);
10872 3 : break;
10873 : }
10874 0 : default:
10875 0 : if (papszValues)
10876 0 : CSLDestroy(papszValues);
10877 0 : return CE_Failure;
10878 : break;
10879 : }
10880 : }
10881 :
10882 105 : if (papszValues)
10883 105 : CSLDestroy(papszValues);
10884 :
10885 105 : return CE_None;
10886 : }
10887 :
10888 76 : static CPLErr NCDFGet1DVar(int nCdfId, int nVarId, char **pszValue)
10889 : {
10890 : /* get var information */
10891 76 : int nVarDimId = -1;
10892 76 : int status = nc_inq_varndims(nCdfId, nVarId, &nVarDimId);
10893 76 : if (status != NC_NOERR || nVarDimId != 1)
10894 0 : return CE_Failure;
10895 :
10896 76 : status = nc_inq_vardimid(nCdfId, nVarId, &nVarDimId);
10897 76 : if (status != NC_NOERR)
10898 0 : return CE_Failure;
10899 :
10900 76 : nc_type nVarType = NC_NAT;
10901 76 : status = nc_inq_vartype(nCdfId, nVarId, &nVarType);
10902 76 : if (status != NC_NOERR)
10903 0 : return CE_Failure;
10904 :
10905 76 : size_t nVarLen = 0;
10906 76 : status = nc_inq_dimlen(nCdfId, nVarDimId, &nVarLen);
10907 76 : if (status != NC_NOERR)
10908 0 : return CE_Failure;
10909 :
10910 76 : size_t start[1] = {0};
10911 76 : size_t count[1] = {nVarLen};
10912 :
10913 : /* Allocate guaranteed minimum size */
10914 76 : size_t nVarValueSize = NCDF_MAX_STR_LEN;
10915 : char *pszVarValue =
10916 76 : static_cast<char *>(CPLCalloc(nVarValueSize, sizeof(char)));
10917 76 : *pszVarValue = '\0';
10918 :
10919 76 : if (nVarLen == 0)
10920 : {
10921 : /* set return values */
10922 1 : *pszValue = pszVarValue;
10923 :
10924 1 : return CE_None;
10925 : }
10926 :
10927 75 : if (nVarLen > 1 && nVarType != NC_CHAR)
10928 40 : NCDFSafeStrcat(&pszVarValue, "{", &nVarValueSize);
10929 :
10930 75 : switch (nVarType)
10931 : {
10932 0 : case NC_CHAR:
10933 0 : nc_get_vara_text(nCdfId, nVarId, start, count, pszVarValue);
10934 0 : pszVarValue[nVarLen] = '\0';
10935 0 : break;
10936 0 : case NC_BYTE:
10937 : {
10938 : signed char *pscTemp = static_cast<signed char *>(
10939 0 : CPLCalloc(nVarLen, sizeof(signed char)));
10940 0 : nc_get_vara_schar(nCdfId, nVarId, start, count, pscTemp);
10941 : char szTemp[256];
10942 0 : size_t m = 0;
10943 0 : for (; m < nVarLen - 1; m++)
10944 : {
10945 0 : snprintf(szTemp, sizeof(szTemp), "%d,", pscTemp[m]);
10946 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
10947 : }
10948 0 : snprintf(szTemp, sizeof(szTemp), "%d", pscTemp[m]);
10949 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
10950 0 : CPLFree(pscTemp);
10951 0 : break;
10952 : }
10953 0 : case NC_SHORT:
10954 : {
10955 : short *psTemp =
10956 0 : static_cast<short *>(CPLCalloc(nVarLen, sizeof(short)));
10957 0 : nc_get_vara_short(nCdfId, nVarId, start, count, psTemp);
10958 : char szTemp[256];
10959 0 : size_t m = 0;
10960 0 : for (; m < nVarLen - 1; m++)
10961 : {
10962 0 : snprintf(szTemp, sizeof(szTemp), "%d,", psTemp[m]);
10963 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
10964 : }
10965 0 : snprintf(szTemp, sizeof(szTemp), "%d", psTemp[m]);
10966 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
10967 0 : CPLFree(psTemp);
10968 0 : break;
10969 : }
10970 19 : case NC_INT:
10971 : {
10972 19 : int *pnTemp = static_cast<int *>(CPLCalloc(nVarLen, sizeof(int)));
10973 19 : nc_get_vara_int(nCdfId, nVarId, start, count, pnTemp);
10974 : char szTemp[256];
10975 19 : size_t m = 0;
10976 36 : for (; m < nVarLen - 1; m++)
10977 : {
10978 17 : snprintf(szTemp, sizeof(szTemp), "%d,", pnTemp[m]);
10979 17 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
10980 : }
10981 19 : snprintf(szTemp, sizeof(szTemp), "%d", pnTemp[m]);
10982 19 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
10983 19 : CPLFree(pnTemp);
10984 19 : break;
10985 : }
10986 8 : case NC_FLOAT:
10987 : {
10988 : float *pfTemp =
10989 8 : static_cast<float *>(CPLCalloc(nVarLen, sizeof(float)));
10990 8 : nc_get_vara_float(nCdfId, nVarId, start, count, pfTemp);
10991 : char szTemp[256];
10992 8 : size_t m = 0;
10993 325 : for (; m < nVarLen - 1; m++)
10994 : {
10995 317 : CPLsnprintf(szTemp, sizeof(szTemp), "%.8g,", pfTemp[m]);
10996 317 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
10997 : }
10998 8 : CPLsnprintf(szTemp, sizeof(szTemp), "%.8g", pfTemp[m]);
10999 8 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11000 8 : CPLFree(pfTemp);
11001 8 : break;
11002 : }
11003 47 : case NC_DOUBLE:
11004 : {
11005 : double *pdfTemp =
11006 47 : static_cast<double *>(CPLCalloc(nVarLen, sizeof(double)));
11007 47 : nc_get_vara_double(nCdfId, nVarId, start, count, pdfTemp);
11008 : char szTemp[256];
11009 47 : size_t m = 0;
11010 225 : for (; m < nVarLen - 1; m++)
11011 : {
11012 178 : CPLsnprintf(szTemp, sizeof(szTemp), "%.16g,", pdfTemp[m]);
11013 178 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11014 : }
11015 47 : CPLsnprintf(szTemp, sizeof(szTemp), "%.16g", pdfTemp[m]);
11016 47 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11017 47 : CPLFree(pdfTemp);
11018 47 : break;
11019 : }
11020 0 : case NC_STRING:
11021 : {
11022 : char **ppszTemp =
11023 0 : static_cast<char **>(CPLCalloc(nVarLen, sizeof(char *)));
11024 0 : nc_get_vara_string(nCdfId, nVarId, start, count, ppszTemp);
11025 0 : size_t m = 0;
11026 0 : for (; m < nVarLen - 1; m++)
11027 : {
11028 0 : NCDFSafeStrcat(&pszVarValue, ppszTemp[m], &nVarValueSize);
11029 0 : NCDFSafeStrcat(&pszVarValue, ",", &nVarValueSize);
11030 : }
11031 0 : NCDFSafeStrcat(&pszVarValue, ppszTemp[m], &nVarValueSize);
11032 0 : nc_free_string(nVarLen, ppszTemp);
11033 0 : CPLFree(ppszTemp);
11034 0 : break;
11035 : }
11036 0 : case NC_UBYTE:
11037 : {
11038 : unsigned char *pucTemp;
11039 : pucTemp = static_cast<unsigned char *>(
11040 0 : CPLCalloc(nVarLen, sizeof(unsigned char)));
11041 0 : nc_get_vara_uchar(nCdfId, nVarId, start, count, pucTemp);
11042 : char szTemp[256];
11043 0 : size_t m = 0;
11044 0 : for (; m < nVarLen - 1; m++)
11045 : {
11046 0 : CPLsnprintf(szTemp, sizeof(szTemp), "%u,", pucTemp[m]);
11047 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11048 : }
11049 0 : CPLsnprintf(szTemp, sizeof(szTemp), "%u", pucTemp[m]);
11050 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11051 0 : CPLFree(pucTemp);
11052 0 : break;
11053 : }
11054 0 : case NC_USHORT:
11055 : {
11056 : unsigned short *pusTemp;
11057 : pusTemp = static_cast<unsigned short *>(
11058 0 : CPLCalloc(nVarLen, sizeof(unsigned short)));
11059 0 : nc_get_vara_ushort(nCdfId, nVarId, start, count, pusTemp);
11060 : char szTemp[256];
11061 0 : size_t m = 0;
11062 0 : for (; m < nVarLen - 1; m++)
11063 : {
11064 0 : CPLsnprintf(szTemp, sizeof(szTemp), "%u,", pusTemp[m]);
11065 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11066 : }
11067 0 : CPLsnprintf(szTemp, sizeof(szTemp), "%u", pusTemp[m]);
11068 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11069 0 : CPLFree(pusTemp);
11070 0 : break;
11071 : }
11072 0 : case NC_UINT:
11073 : {
11074 : unsigned int *punTemp;
11075 : punTemp = static_cast<unsigned int *>(
11076 0 : CPLCalloc(nVarLen, sizeof(unsigned int)));
11077 0 : nc_get_vara_uint(nCdfId, nVarId, start, count, punTemp);
11078 : char szTemp[256];
11079 0 : size_t m = 0;
11080 0 : for (; m < nVarLen - 1; m++)
11081 : {
11082 0 : CPLsnprintf(szTemp, sizeof(szTemp), "%u,", punTemp[m]);
11083 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11084 : }
11085 0 : CPLsnprintf(szTemp, sizeof(szTemp), "%u", punTemp[m]);
11086 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11087 0 : CPLFree(punTemp);
11088 0 : break;
11089 : }
11090 1 : case NC_INT64:
11091 : {
11092 : long long *pnTemp =
11093 1 : static_cast<long long *>(CPLCalloc(nVarLen, sizeof(long long)));
11094 1 : nc_get_vara_longlong(nCdfId, nVarId, start, count, pnTemp);
11095 : char szTemp[256];
11096 1 : size_t m = 0;
11097 2 : for (; m < nVarLen - 1; m++)
11098 : {
11099 1 : snprintf(szTemp, sizeof(szTemp), CPL_FRMT_GIB ",", pnTemp[m]);
11100 1 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11101 : }
11102 1 : snprintf(szTemp, sizeof(szTemp), CPL_FRMT_GIB, pnTemp[m]);
11103 1 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11104 1 : CPLFree(pnTemp);
11105 1 : break;
11106 : }
11107 0 : case NC_UINT64:
11108 : {
11109 : unsigned long long *pnTemp = static_cast<unsigned long long *>(
11110 0 : CPLCalloc(nVarLen, sizeof(unsigned long long)));
11111 0 : nc_get_vara_ulonglong(nCdfId, nVarId, start, count, pnTemp);
11112 : char szTemp[256];
11113 0 : size_t m = 0;
11114 0 : for (; m < nVarLen - 1; m++)
11115 : {
11116 0 : snprintf(szTemp, sizeof(szTemp), CPL_FRMT_GUIB ",", pnTemp[m]);
11117 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11118 : }
11119 0 : snprintf(szTemp, sizeof(szTemp), CPL_FRMT_GUIB, pnTemp[m]);
11120 0 : NCDFSafeStrcat(&pszVarValue, szTemp, &nVarValueSize);
11121 0 : CPLFree(pnTemp);
11122 0 : break;
11123 : }
11124 0 : default:
11125 0 : CPLDebug("GDAL_netCDF", "NCDFGetVar1D unsupported type %d",
11126 : nVarType);
11127 0 : CPLFree(pszVarValue);
11128 0 : pszVarValue = nullptr;
11129 0 : break;
11130 : }
11131 :
11132 75 : if (pszVarValue != nullptr && nVarLen > 1 && nVarType != NC_CHAR)
11133 40 : NCDFSafeStrcat(&pszVarValue, "}", &nVarValueSize);
11134 :
11135 : /* set return values */
11136 75 : *pszValue = pszVarValue;
11137 :
11138 75 : return CE_None;
11139 : }
11140 :
11141 8 : static CPLErr NCDFPut1DVar(int nCdfId, int nVarId, const char *pszValue)
11142 : {
11143 8 : if (EQUAL(pszValue, ""))
11144 0 : return CE_Failure;
11145 :
11146 : /* get var information */
11147 8 : int nVarDimId = -1;
11148 8 : int status = nc_inq_varndims(nCdfId, nVarId, &nVarDimId);
11149 8 : if (status != NC_NOERR || nVarDimId != 1)
11150 0 : return CE_Failure;
11151 :
11152 8 : status = nc_inq_vardimid(nCdfId, nVarId, &nVarDimId);
11153 8 : if (status != NC_NOERR)
11154 0 : return CE_Failure;
11155 :
11156 8 : nc_type nVarType = NC_CHAR;
11157 8 : status = nc_inq_vartype(nCdfId, nVarId, &nVarType);
11158 8 : if (status != NC_NOERR)
11159 0 : return CE_Failure;
11160 :
11161 8 : size_t nVarLen = 0;
11162 8 : status = nc_inq_dimlen(nCdfId, nVarDimId, &nVarLen);
11163 8 : if (status != NC_NOERR)
11164 0 : return CE_Failure;
11165 :
11166 8 : size_t start[1] = {0};
11167 8 : size_t count[1] = {nVarLen};
11168 :
11169 : /* get the values as tokens */
11170 8 : char **papszValues = NCDFTokenizeArray(pszValue);
11171 8 : if (papszValues == nullptr)
11172 0 : return CE_Failure;
11173 :
11174 8 : nVarLen = CSLCount(papszValues);
11175 :
11176 : /* now write the data */
11177 8 : if (nVarType == NC_CHAR)
11178 : {
11179 0 : status = nc_put_vara_text(nCdfId, nVarId, start, count, pszValue);
11180 0 : NCDF_ERR(status);
11181 : }
11182 : else
11183 : {
11184 8 : switch (nVarType)
11185 : {
11186 0 : case NC_BYTE:
11187 : {
11188 : signed char *pscTemp = static_cast<signed char *>(
11189 0 : CPLCalloc(nVarLen, sizeof(signed char)));
11190 0 : for (size_t i = 0; i < nVarLen; i++)
11191 : {
11192 0 : char *pszTemp = nullptr;
11193 0 : pscTemp[i] = static_cast<signed char>(
11194 0 : strtol(papszValues[i], &pszTemp, 10));
11195 : }
11196 : status =
11197 0 : nc_put_vara_schar(nCdfId, nVarId, start, count, pscTemp);
11198 0 : NCDF_ERR(status);
11199 0 : CPLFree(pscTemp);
11200 0 : break;
11201 : }
11202 0 : case NC_SHORT:
11203 : {
11204 : short *psTemp =
11205 0 : static_cast<short *>(CPLCalloc(nVarLen, sizeof(short)));
11206 0 : for (size_t i = 0; i < nVarLen; i++)
11207 : {
11208 0 : char *pszTemp = nullptr;
11209 0 : psTemp[i] = static_cast<short>(
11210 0 : strtol(papszValues[i], &pszTemp, 10));
11211 : }
11212 : status =
11213 0 : nc_put_vara_short(nCdfId, nVarId, start, count, psTemp);
11214 0 : NCDF_ERR(status);
11215 0 : CPLFree(psTemp);
11216 0 : break;
11217 : }
11218 3 : case NC_INT:
11219 : {
11220 : int *pnTemp =
11221 3 : static_cast<int *>(CPLCalloc(nVarLen, sizeof(int)));
11222 11 : for (size_t i = 0; i < nVarLen; i++)
11223 : {
11224 8 : char *pszTemp = nullptr;
11225 8 : pnTemp[i] =
11226 8 : static_cast<int>(strtol(papszValues[i], &pszTemp, 10));
11227 : }
11228 3 : status = nc_put_vara_int(nCdfId, nVarId, start, count, pnTemp);
11229 3 : NCDF_ERR(status);
11230 3 : CPLFree(pnTemp);
11231 3 : break;
11232 : }
11233 0 : case NC_FLOAT:
11234 : {
11235 : float *pfTemp =
11236 0 : static_cast<float *>(CPLCalloc(nVarLen, sizeof(float)));
11237 0 : for (size_t i = 0; i < nVarLen; i++)
11238 : {
11239 0 : char *pszTemp = nullptr;
11240 0 : pfTemp[i] =
11241 0 : static_cast<float>(CPLStrtod(papszValues[i], &pszTemp));
11242 : }
11243 : status =
11244 0 : nc_put_vara_float(nCdfId, nVarId, start, count, pfTemp);
11245 0 : NCDF_ERR(status);
11246 0 : CPLFree(pfTemp);
11247 0 : break;
11248 : }
11249 5 : case NC_DOUBLE:
11250 : {
11251 : double *pdfTemp =
11252 5 : static_cast<double *>(CPLCalloc(nVarLen, sizeof(double)));
11253 19 : for (size_t i = 0; i < nVarLen; i++)
11254 : {
11255 14 : char *pszTemp = nullptr;
11256 14 : pdfTemp[i] = CPLStrtod(papszValues[i], &pszTemp);
11257 : }
11258 : status =
11259 5 : nc_put_vara_double(nCdfId, nVarId, start, count, pdfTemp);
11260 5 : NCDF_ERR(status);
11261 5 : CPLFree(pdfTemp);
11262 5 : break;
11263 : }
11264 0 : default:
11265 : {
11266 0 : int nTmpFormat = 0;
11267 0 : status = nc_inq_format(nCdfId, &nTmpFormat);
11268 0 : NCDF_ERR(status);
11269 0 : if (nTmpFormat == NCDF_FORMAT_NC4)
11270 : {
11271 0 : switch (nVarType)
11272 : {
11273 0 : case NC_STRING:
11274 : {
11275 : status =
11276 0 : nc_put_vara_string(nCdfId, nVarId, start, count,
11277 : (const char **)papszValues);
11278 0 : NCDF_ERR(status);
11279 0 : break;
11280 : }
11281 0 : case NC_UBYTE:
11282 : {
11283 : unsigned char *pucTemp =
11284 : static_cast<unsigned char *>(
11285 0 : CPLCalloc(nVarLen, sizeof(unsigned char)));
11286 0 : for (size_t i = 0; i < nVarLen; i++)
11287 : {
11288 0 : char *pszTemp = nullptr;
11289 0 : pucTemp[i] = static_cast<unsigned char>(
11290 0 : strtoul(papszValues[i], &pszTemp, 10));
11291 : }
11292 0 : status = nc_put_vara_uchar(nCdfId, nVarId, start,
11293 : count, pucTemp);
11294 0 : NCDF_ERR(status);
11295 0 : CPLFree(pucTemp);
11296 0 : break;
11297 : }
11298 0 : case NC_USHORT:
11299 : {
11300 : unsigned short *pusTemp =
11301 : static_cast<unsigned short *>(
11302 0 : CPLCalloc(nVarLen, sizeof(unsigned short)));
11303 0 : for (size_t i = 0; i < nVarLen; i++)
11304 : {
11305 0 : char *pszTemp = nullptr;
11306 0 : pusTemp[i] = static_cast<unsigned short>(
11307 0 : strtoul(papszValues[i], &pszTemp, 10));
11308 : }
11309 0 : status = nc_put_vara_ushort(nCdfId, nVarId, start,
11310 : count, pusTemp);
11311 0 : NCDF_ERR(status);
11312 0 : CPLFree(pusTemp);
11313 0 : break;
11314 : }
11315 0 : case NC_UINT:
11316 : {
11317 : unsigned int *punTemp = static_cast<unsigned int *>(
11318 0 : CPLCalloc(nVarLen, sizeof(unsigned int)));
11319 0 : for (size_t i = 0; i < nVarLen; i++)
11320 : {
11321 0 : char *pszTemp = nullptr;
11322 0 : punTemp[i] = static_cast<unsigned int>(
11323 0 : strtoul(papszValues[i], &pszTemp, 10));
11324 : }
11325 0 : status = nc_put_vara_uint(nCdfId, nVarId, start,
11326 : count, punTemp);
11327 0 : NCDF_ERR(status);
11328 0 : CPLFree(punTemp);
11329 0 : break;
11330 : }
11331 0 : default:
11332 0 : if (papszValues)
11333 0 : CSLDestroy(papszValues);
11334 0 : return CE_Failure;
11335 : break;
11336 : }
11337 : }
11338 0 : break;
11339 : }
11340 : }
11341 : }
11342 :
11343 8 : if (papszValues)
11344 8 : CSLDestroy(papszValues);
11345 :
11346 8 : return CE_None;
11347 : }
11348 :
11349 : /************************************************************************/
11350 : /* GetDefaultNoDataValue() */
11351 : /************************************************************************/
11352 :
11353 188 : double NCDFGetDefaultNoDataValue(int nCdfId, int nVarId, int nVarType,
11354 : bool &bGotNoData)
11355 :
11356 : {
11357 188 : int nNoFill = 0;
11358 188 : double dfNoData = 0.0;
11359 :
11360 188 : switch (nVarType)
11361 : {
11362 0 : case NC_CHAR:
11363 : case NC_BYTE:
11364 : case NC_UBYTE:
11365 : // Don't do default fill-values for bytes, too risky.
11366 : // This function should not be called in those cases.
11367 0 : CPLAssert(false);
11368 : break;
11369 24 : case NC_SHORT:
11370 : {
11371 24 : short nFillVal = 0;
11372 24 : if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) ==
11373 : NC_NOERR)
11374 : {
11375 24 : if (!nNoFill)
11376 : {
11377 23 : bGotNoData = true;
11378 23 : dfNoData = nFillVal;
11379 : }
11380 : }
11381 : else
11382 0 : dfNoData = NC_FILL_SHORT;
11383 24 : break;
11384 : }
11385 26 : case NC_INT:
11386 : {
11387 26 : int nFillVal = 0;
11388 26 : if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) ==
11389 : NC_NOERR)
11390 : {
11391 26 : if (!nNoFill)
11392 : {
11393 25 : bGotNoData = true;
11394 25 : dfNoData = nFillVal;
11395 : }
11396 : }
11397 : else
11398 0 : dfNoData = NC_FILL_INT;
11399 26 : break;
11400 : }
11401 71 : case NC_FLOAT:
11402 : {
11403 71 : float fFillVal = 0;
11404 71 : if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &fFillVal) ==
11405 : NC_NOERR)
11406 : {
11407 71 : if (!nNoFill)
11408 : {
11409 67 : bGotNoData = true;
11410 67 : dfNoData = fFillVal;
11411 : }
11412 : }
11413 : else
11414 0 : dfNoData = NC_FILL_FLOAT;
11415 71 : break;
11416 : }
11417 34 : case NC_DOUBLE:
11418 : {
11419 34 : if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &dfNoData) ==
11420 : NC_NOERR)
11421 : {
11422 34 : if (!nNoFill)
11423 : {
11424 34 : bGotNoData = true;
11425 : }
11426 : }
11427 : else
11428 0 : dfNoData = NC_FILL_DOUBLE;
11429 34 : break;
11430 : }
11431 7 : case NC_USHORT:
11432 : {
11433 7 : unsigned short nFillVal = 0;
11434 7 : if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) ==
11435 : NC_NOERR)
11436 : {
11437 7 : if (!nNoFill)
11438 : {
11439 7 : bGotNoData = true;
11440 7 : dfNoData = nFillVal;
11441 : }
11442 : }
11443 : else
11444 0 : dfNoData = NC_FILL_USHORT;
11445 7 : break;
11446 : }
11447 7 : case NC_UINT:
11448 : {
11449 7 : unsigned int nFillVal = 0;
11450 7 : if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) ==
11451 : NC_NOERR)
11452 : {
11453 7 : if (!nNoFill)
11454 : {
11455 7 : bGotNoData = true;
11456 7 : dfNoData = nFillVal;
11457 : }
11458 : }
11459 : else
11460 0 : dfNoData = NC_FILL_UINT;
11461 7 : break;
11462 : }
11463 19 : default:
11464 19 : dfNoData = 0.0;
11465 19 : break;
11466 : }
11467 :
11468 188 : return dfNoData;
11469 : }
11470 :
11471 : /************************************************************************/
11472 : /* NCDFGetDefaultNoDataValueAsInt64() */
11473 : /************************************************************************/
11474 :
11475 2 : int64_t NCDFGetDefaultNoDataValueAsInt64(int nCdfId, int nVarId,
11476 : bool &bGotNoData)
11477 :
11478 : {
11479 2 : int nNoFill = 0;
11480 2 : long long nFillVal = 0;
11481 2 : if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) == NC_NOERR)
11482 : {
11483 2 : if (!nNoFill)
11484 : {
11485 2 : bGotNoData = true;
11486 2 : return static_cast<int64_t>(nFillVal);
11487 : }
11488 : }
11489 : else
11490 0 : return static_cast<int64_t>(NC_FILL_INT64);
11491 0 : return 0;
11492 : }
11493 :
11494 : /************************************************************************/
11495 : /* NCDFGetDefaultNoDataValueAsUInt64() */
11496 : /************************************************************************/
11497 :
11498 1 : uint64_t NCDFGetDefaultNoDataValueAsUInt64(int nCdfId, int nVarId,
11499 : bool &bGotNoData)
11500 :
11501 : {
11502 1 : int nNoFill = 0;
11503 1 : unsigned long long nFillVal = 0;
11504 1 : if (nc_inq_var_fill(nCdfId, nVarId, &nNoFill, &nFillVal) == NC_NOERR)
11505 : {
11506 1 : if (!nNoFill)
11507 : {
11508 1 : bGotNoData = true;
11509 1 : return static_cast<uint64_t>(nFillVal);
11510 : }
11511 : }
11512 : else
11513 0 : return static_cast<uint64_t>(NC_FILL_UINT64);
11514 0 : return 0;
11515 : }
11516 :
11517 10984 : static int NCDFDoesVarContainAttribVal(int nCdfId,
11518 : const char *const *papszAttribNames,
11519 : const char *const *papszAttribValues,
11520 : int nVarId, const char *pszVarName,
11521 : bool bStrict = true)
11522 : {
11523 10984 : if (nVarId == -1 && pszVarName != nullptr)
11524 8059 : NCDFResolveVar(nCdfId, pszVarName, &nCdfId, &nVarId);
11525 :
11526 10984 : if (nVarId == -1)
11527 878 : return -1;
11528 :
11529 10106 : bool bFound = false;
11530 47164 : for (int i = 0; !bFound && papszAttribNames != nullptr &&
11531 44934 : papszAttribNames[i] != nullptr;
11532 : i++)
11533 : {
11534 37058 : char *pszTemp = nullptr;
11535 37058 : if (NCDFGetAttr(nCdfId, nVarId, papszAttribNames[i], &pszTemp) ==
11536 53164 : CE_None &&
11537 16106 : pszTemp != nullptr)
11538 : {
11539 16106 : if (bStrict)
11540 : {
11541 16106 : if (EQUAL(pszTemp, papszAttribValues[i]))
11542 2230 : bFound = true;
11543 : }
11544 : else
11545 : {
11546 0 : if (EQUALN(pszTemp, papszAttribValues[i],
11547 : strlen(papszAttribValues[i])))
11548 0 : bFound = true;
11549 : }
11550 16106 : CPLFree(pszTemp);
11551 : }
11552 : }
11553 10106 : return bFound;
11554 : }
11555 :
11556 1952 : static int NCDFDoesVarContainAttribVal2(int nCdfId, const char *papszAttribName,
11557 : const char *const *papszAttribValues,
11558 : int nVarId, const char *pszVarName,
11559 : int bStrict = true)
11560 : {
11561 1952 : if (nVarId == -1 && pszVarName != nullptr)
11562 1569 : NCDFResolveVar(nCdfId, pszVarName, &nCdfId, &nVarId);
11563 :
11564 1952 : if (nVarId == -1)
11565 0 : return -1;
11566 :
11567 1952 : bool bFound = false;
11568 1952 : char *pszTemp = nullptr;
11569 2331 : if (NCDFGetAttr(nCdfId, nVarId, papszAttribName, &pszTemp) != CE_None ||
11570 379 : pszTemp == nullptr)
11571 1573 : return FALSE;
11572 :
11573 7703 : for (int i = 0; !bFound && i < CSLCount(papszAttribValues); i++)
11574 : {
11575 7324 : if (bStrict)
11576 : {
11577 7296 : if (EQUAL(pszTemp, papszAttribValues[i]))
11578 31 : bFound = true;
11579 : }
11580 : else
11581 : {
11582 28 : if (EQUALN(pszTemp, papszAttribValues[i],
11583 : strlen(papszAttribValues[i])))
11584 0 : bFound = true;
11585 : }
11586 : }
11587 :
11588 379 : CPLFree(pszTemp);
11589 :
11590 379 : return bFound;
11591 : }
11592 :
11593 876 : static bool NCDFEqual(const char *papszName, const char *const *papszValues)
11594 : {
11595 876 : if (papszName == nullptr || EQUAL(papszName, ""))
11596 0 : return false;
11597 :
11598 2392 : for (int i = 0; papszValues && papszValues[i]; ++i)
11599 : {
11600 1636 : if (EQUAL(papszName, papszValues[i]))
11601 120 : return true;
11602 : }
11603 :
11604 756 : return false;
11605 : }
11606 :
11607 : // Test that a variable is longitude/latitude coordinate,
11608 : // following CF 4.1 and 4.2.
11609 3743 : bool NCDFIsVarLongitude(int nCdfId, int nVarId, const char *pszVarName)
11610 : {
11611 : // Check for matching attributes.
11612 3743 : int bVal = NCDFDoesVarContainAttribVal(nCdfId, papszCFLongitudeAttribNames,
11613 : papszCFLongitudeAttribValues, nVarId,
11614 : pszVarName);
11615 : // If not found using attributes then check using var name
11616 : // unless GDAL_NETCDF_VERIFY_DIMS=STRICT.
11617 3743 : if (bVal == -1)
11618 : {
11619 280 : if (!EQUAL(CPLGetConfigOption("GDAL_NETCDF_VERIFY_DIMS", "YES"),
11620 : "STRICT"))
11621 280 : bVal = NCDFEqual(pszVarName, papszCFLongitudeVarNames);
11622 : else
11623 0 : bVal = FALSE;
11624 : }
11625 3463 : else if (bVal)
11626 : {
11627 : // Check that the units is not 'm' or '1'. See #6759
11628 784 : char *pszTemp = nullptr;
11629 1161 : if (NCDFGetAttr(nCdfId, nVarId, "units", &pszTemp) == CE_None &&
11630 377 : pszTemp != nullptr)
11631 : {
11632 377 : if (EQUAL(pszTemp, "m") || EQUAL(pszTemp, "1"))
11633 97 : bVal = false;
11634 377 : CPLFree(pszTemp);
11635 : }
11636 : }
11637 :
11638 3743 : return CPL_TO_BOOL(bVal);
11639 : }
11640 :
11641 2148 : bool NCDFIsVarLatitude(int nCdfId, int nVarId, const char *pszVarName)
11642 : {
11643 2148 : int bVal = NCDFDoesVarContainAttribVal(nCdfId, papszCFLatitudeAttribNames,
11644 : papszCFLatitudeAttribValues, nVarId,
11645 : pszVarName);
11646 2148 : if (bVal == -1)
11647 : {
11648 163 : if (!EQUAL(CPLGetConfigOption("GDAL_NETCDF_VERIFY_DIMS", "YES"),
11649 : "STRICT"))
11650 163 : bVal = NCDFEqual(pszVarName, papszCFLatitudeVarNames);
11651 : else
11652 0 : bVal = FALSE;
11653 : }
11654 1985 : else if (bVal)
11655 : {
11656 : // Check that the units is not 'm' or '1'. See #6759
11657 540 : char *pszTemp = nullptr;
11658 681 : if (NCDFGetAttr(nCdfId, nVarId, "units", &pszTemp) == CE_None &&
11659 141 : pszTemp != nullptr)
11660 : {
11661 141 : if (EQUAL(pszTemp, "m") || EQUAL(pszTemp, "1"))
11662 36 : bVal = false;
11663 141 : CPLFree(pszTemp);
11664 : }
11665 : }
11666 :
11667 2148 : return CPL_TO_BOOL(bVal);
11668 : }
11669 :
11670 2267 : bool NCDFIsVarProjectionX(int nCdfId, int nVarId, const char *pszVarName)
11671 : {
11672 2267 : int bVal = NCDFDoesVarContainAttribVal(
11673 : nCdfId, papszCFProjectionXAttribNames, papszCFProjectionXAttribValues,
11674 : nVarId, pszVarName);
11675 2267 : if (bVal == -1)
11676 : {
11677 274 : if (!EQUAL(CPLGetConfigOption("GDAL_NETCDF_VERIFY_DIMS", "YES"),
11678 : "STRICT"))
11679 274 : bVal = NCDFEqual(pszVarName, papszCFProjectionXVarNames);
11680 : else
11681 0 : bVal = FALSE;
11682 : }
11683 1993 : else if (bVal)
11684 : {
11685 : // Check that the units is not '1'
11686 364 : char *pszTemp = nullptr;
11687 518 : if (NCDFGetAttr(nCdfId, nVarId, "units", &pszTemp) == CE_None &&
11688 154 : pszTemp != nullptr)
11689 : {
11690 154 : if (EQUAL(pszTemp, "1"))
11691 5 : bVal = false;
11692 154 : CPLFree(pszTemp);
11693 : }
11694 : }
11695 :
11696 2267 : return CPL_TO_BOOL(bVal);
11697 : }
11698 :
11699 1607 : bool NCDFIsVarProjectionY(int nCdfId, int nVarId, const char *pszVarName)
11700 : {
11701 1607 : int bVal = NCDFDoesVarContainAttribVal(
11702 : nCdfId, papszCFProjectionYAttribNames, papszCFProjectionYAttribValues,
11703 : nVarId, pszVarName);
11704 1607 : if (bVal == -1)
11705 : {
11706 159 : if (!EQUAL(CPLGetConfigOption("GDAL_NETCDF_VERIFY_DIMS", "YES"),
11707 : "STRICT"))
11708 159 : bVal = NCDFEqual(pszVarName, papszCFProjectionYVarNames);
11709 : else
11710 0 : bVal = FALSE;
11711 : }
11712 1448 : else if (bVal)
11713 : {
11714 : // Check that the units is not '1'
11715 363 : char *pszTemp = nullptr;
11716 516 : if (NCDFGetAttr(nCdfId, nVarId, "units", &pszTemp) == CE_None &&
11717 153 : pszTemp != nullptr)
11718 : {
11719 153 : if (EQUAL(pszTemp, "1"))
11720 5 : bVal = false;
11721 153 : CPLFree(pszTemp);
11722 : }
11723 : }
11724 :
11725 1607 : return CPL_TO_BOOL(bVal);
11726 : }
11727 :
11728 : /* test that a variable is a vertical coordinate, following CF 4.3 */
11729 1017 : bool NCDFIsVarVerticalCoord(int nCdfId, int nVarId, const char *pszVarName)
11730 : {
11731 : /* check for matching attributes */
11732 1017 : if (NCDFDoesVarContainAttribVal(nCdfId, papszCFVerticalAttribNames,
11733 : papszCFVerticalAttribValues, nVarId,
11734 1017 : pszVarName))
11735 72 : return true;
11736 : /* check for matching units */
11737 945 : else if (NCDFDoesVarContainAttribVal2(nCdfId, CF_UNITS,
11738 : papszCFVerticalUnitsValues, nVarId,
11739 945 : pszVarName))
11740 31 : return true;
11741 : /* check for matching standard name */
11742 914 : else if (NCDFDoesVarContainAttribVal2(nCdfId, CF_STD_NAME,
11743 : papszCFVerticalStandardNameValues,
11744 914 : nVarId, pszVarName))
11745 0 : return true;
11746 : else
11747 914 : return false;
11748 : }
11749 :
11750 : /* test that a variable is a time coordinate, following CF 4.4 */
11751 202 : bool NCDFIsVarTimeCoord(int nCdfId, int nVarId, const char *pszVarName)
11752 : {
11753 : /* check for matching attributes */
11754 202 : if (NCDFDoesVarContainAttribVal(nCdfId, papszCFTimeAttribNames,
11755 : papszCFTimeAttribValues, nVarId,
11756 202 : pszVarName))
11757 109 : return true;
11758 : /* check for matching units */
11759 93 : else if (NCDFDoesVarContainAttribVal2(nCdfId, CF_UNITS,
11760 : papszCFTimeUnitsValues, nVarId,
11761 93 : pszVarName, false))
11762 0 : return true;
11763 : else
11764 93 : return false;
11765 : }
11766 :
11767 : // Parse a string, and return as a string list.
11768 : // If it an array of the form {a,b}, then tokenize it.
11769 : // Otherwise, return a copy.
11770 185 : static char **NCDFTokenizeArray(const char *pszValue)
11771 : {
11772 185 : if (pszValue == nullptr || EQUAL(pszValue, ""))
11773 51 : return nullptr;
11774 :
11775 134 : char **papszValues = nullptr;
11776 134 : const int nLen = static_cast<int>(strlen(pszValue));
11777 :
11778 134 : if (pszValue[0] == '{' && nLen > 2 && pszValue[nLen - 1] == '}')
11779 : {
11780 41 : char *pszTemp = static_cast<char *>(CPLMalloc((nLen - 2) + 1));
11781 41 : strncpy(pszTemp, pszValue + 1, nLen - 2);
11782 41 : pszTemp[nLen - 2] = '\0';
11783 41 : papszValues = CSLTokenizeString2(pszTemp, ",", CSLT_ALLOWEMPTYTOKENS);
11784 41 : CPLFree(pszTemp);
11785 : }
11786 : else
11787 : {
11788 93 : papszValues = reinterpret_cast<char **>(CPLCalloc(2, sizeof(char *)));
11789 93 : papszValues[0] = CPLStrdup(pszValue);
11790 93 : papszValues[1] = nullptr;
11791 : }
11792 :
11793 134 : return papszValues;
11794 : }
11795 :
11796 : // Open a NetCDF subdataset from full path /group1/group2/.../groupn/var.
11797 : // Leading slash is optional.
11798 407 : static CPLErr NCDFOpenSubDataset(int nCdfId, const char *pszSubdatasetName,
11799 : int *pnGroupId, int *pnVarId)
11800 : {
11801 407 : *pnGroupId = -1;
11802 407 : *pnVarId = -1;
11803 :
11804 : // Open group.
11805 : char *pszGroupFullName =
11806 407 : CPLStrdup(CPLGetPathSafe(pszSubdatasetName).c_str());
11807 : // Add a leading slash if needed.
11808 407 : if (pszGroupFullName[0] != '/')
11809 : {
11810 391 : char *old = pszGroupFullName;
11811 391 : pszGroupFullName = CPLStrdup(CPLSPrintf("/%s", pszGroupFullName));
11812 391 : CPLFree(old);
11813 : }
11814 : // Detect root group.
11815 407 : if (EQUAL(pszGroupFullName, "/"))
11816 : {
11817 391 : *pnGroupId = nCdfId;
11818 391 : CPLFree(pszGroupFullName);
11819 : }
11820 : else
11821 : {
11822 16 : int status = nc_inq_grp_full_ncid(nCdfId, pszGroupFullName, pnGroupId);
11823 16 : CPLFree(pszGroupFullName);
11824 16 : NCDF_ERR_RET(status);
11825 : }
11826 :
11827 : // Open var.
11828 407 : const char *pszVarName = CPLGetFilename(pszSubdatasetName);
11829 407 : NCDF_ERR_RET(nc_inq_varid(*pnGroupId, pszVarName, pnVarId));
11830 :
11831 407 : return CE_None;
11832 : }
11833 :
11834 : // Get all dimensions visible from a given NetCDF (or group) ID and any of
11835 : // its parents.
11836 348 : static CPLErr NCDFGetVisibleDims(int nGroupId, int *pnDims, int **ppanDimIds)
11837 : {
11838 348 : int nDims = 0;
11839 348 : int *panDimIds = nullptr;
11840 348 : NCDF_ERR_RET(nc_inq_dimids(nGroupId, &nDims, nullptr, true));
11841 :
11842 348 : panDimIds = static_cast<int *>(CPLMalloc(nDims * sizeof(int)));
11843 :
11844 348 : int status = nc_inq_dimids(nGroupId, nullptr, panDimIds, true);
11845 348 : if (status != NC_NOERR)
11846 0 : CPLFree(panDimIds);
11847 348 : NCDF_ERR_RET(status);
11848 :
11849 348 : *pnDims = nDims;
11850 348 : *ppanDimIds = panDimIds;
11851 :
11852 348 : return CE_None;
11853 : }
11854 :
11855 : // Get direct sub-groups IDs of a given NetCDF (or group) ID.
11856 : // Consider only direct children, does not get children of children.
11857 3032 : static CPLErr NCDFGetSubGroups(int nGroupId, int *pnSubGroups,
11858 : int **ppanSubGroupIds)
11859 : {
11860 3032 : *pnSubGroups = 0;
11861 3032 : *ppanSubGroupIds = nullptr;
11862 :
11863 : int nSubGroups;
11864 3032 : NCDF_ERR_RET(nc_inq_grps(nGroupId, &nSubGroups, nullptr));
11865 : int *panSubGroupIds =
11866 3032 : static_cast<int *>(CPLMalloc(nSubGroups * sizeof(int)));
11867 3032 : NCDF_ERR_RET(nc_inq_grps(nGroupId, nullptr, panSubGroupIds));
11868 3032 : *pnSubGroups = nSubGroups;
11869 3032 : *ppanSubGroupIds = panSubGroupIds;
11870 :
11871 3032 : return CE_None;
11872 : }
11873 :
11874 : // Get the full name of a given NetCDF (or group) ID
11875 : // (e.g. /group1/group2/.../groupn).
11876 : // bNC3Compat remove the leading slash for top-level variables for
11877 : // backward compatibility (top-level variables are the ones in the root group).
11878 15172 : static CPLErr NCDFGetGroupFullName(int nGroupId, char **ppszFullName,
11879 : bool bNC3Compat)
11880 : {
11881 15172 : *ppszFullName = nullptr;
11882 :
11883 : size_t nFullNameLen;
11884 15172 : NCDF_ERR_RET(nc_inq_grpname_len(nGroupId, &nFullNameLen));
11885 15172 : *ppszFullName =
11886 15172 : static_cast<char *>(CPLMalloc((nFullNameLen + 1) * sizeof(char)));
11887 15172 : int status = nc_inq_grpname_full(nGroupId, &nFullNameLen, *ppszFullName);
11888 15172 : if (status != NC_NOERR)
11889 : {
11890 0 : CPLFree(*ppszFullName);
11891 0 : *ppszFullName = nullptr;
11892 0 : NCDF_ERR_RET(status);
11893 : }
11894 :
11895 15172 : if (bNC3Compat && EQUAL(*ppszFullName, "/"))
11896 7825 : (*ppszFullName)[0] = '\0';
11897 :
11898 15172 : return CE_None;
11899 : }
11900 :
11901 7159 : CPLString NCDFGetGroupFullName(int nGroupId)
11902 : {
11903 7159 : char *pszFullname = nullptr;
11904 7159 : NCDFGetGroupFullName(nGroupId, &pszFullname, false);
11905 7159 : CPLString osRet(pszFullname ? pszFullname : "");
11906 7159 : CPLFree(pszFullname);
11907 14318 : return osRet;
11908 : }
11909 :
11910 : // Get the full name of a given NetCDF variable ID
11911 : // (e.g. /group1/group2/.../groupn/var).
11912 : // Handle also NC_GLOBAL as nVarId.
11913 : // bNC3Compat remove the leading slash for top-level variables for
11914 : // backward compatibility (top-level variables are the ones in the root group).
11915 7964 : static CPLErr NCDFGetVarFullName(int nGroupId, int nVarId, char **ppszFullName,
11916 : bool bNC3Compat)
11917 : {
11918 7964 : *ppszFullName = nullptr;
11919 7964 : char *pszGroupFullName = nullptr;
11920 7964 : ERR_RET(NCDFGetGroupFullName(nGroupId, &pszGroupFullName, bNC3Compat));
11921 : char szVarName[NC_MAX_NAME + 1];
11922 7964 : if (nVarId == NC_GLOBAL)
11923 : {
11924 1080 : strcpy(szVarName, "NC_GLOBAL");
11925 : }
11926 : else
11927 : {
11928 6884 : int status = nc_inq_varname(nGroupId, nVarId, szVarName);
11929 6884 : if (status != NC_NOERR)
11930 : {
11931 0 : CPLFree(pszGroupFullName);
11932 0 : NCDF_ERR_RET(status);
11933 : }
11934 : }
11935 7964 : const char *pszSep = "/";
11936 7964 : if (EQUAL(pszGroupFullName, "/") || EQUAL(pszGroupFullName, ""))
11937 7778 : pszSep = "";
11938 7964 : *ppszFullName =
11939 7964 : CPLStrdup(CPLSPrintf("%s%s%s", pszGroupFullName, pszSep, szVarName));
11940 7964 : CPLFree(pszGroupFullName);
11941 7964 : return CE_None;
11942 : }
11943 :
11944 : // Get the NetCDF root group ID of a given group ID.
11945 0 : static CPLErr NCDFGetRootGroup(int nStartGroupId, int *pnRootGroupId)
11946 : {
11947 0 : *pnRootGroupId = -1;
11948 : // Recurse on parent group.
11949 : int nParentGroupId;
11950 0 : int status = nc_inq_grp_parent(nStartGroupId, &nParentGroupId);
11951 0 : if (status == NC_NOERR)
11952 0 : return NCDFGetRootGroup(nParentGroupId, pnRootGroupId);
11953 0 : else if (status != NC_ENOGRP)
11954 0 : NCDF_ERR_RET(status);
11955 : else // No more parent group.
11956 : {
11957 0 : *pnRootGroupId = nStartGroupId;
11958 : }
11959 :
11960 0 : return CE_None;
11961 : }
11962 :
11963 : // Implementation of NCDFResolveVar/Att.
11964 13094 : static CPLErr NCDFResolveElem(int nStartGroupId, const char *pszVar,
11965 : const char *pszAtt, int *pnGroupId, int *pnId,
11966 : bool bMandatory)
11967 : {
11968 13094 : if (!pszVar && !pszAtt)
11969 : {
11970 0 : CPLError(CE_Failure, CPLE_IllegalArg,
11971 : "pszVar and pszAtt NCDFResolveElem() args are both null.");
11972 0 : return CE_Failure;
11973 : }
11974 :
11975 : enum
11976 : {
11977 : NCRM_PARENT,
11978 : NCRM_WIDTH_WISE
11979 13094 : } eNCResolveMode = NCRM_PARENT;
11980 :
11981 26188 : std::queue<int> aoQueueGroupIdsToVisit;
11982 13094 : aoQueueGroupIdsToVisit.push(nStartGroupId);
11983 :
11984 14760 : while (!aoQueueGroupIdsToVisit.empty())
11985 : {
11986 : // Get the first group of the FIFO queue.
11987 13241 : *pnGroupId = aoQueueGroupIdsToVisit.front();
11988 13241 : aoQueueGroupIdsToVisit.pop();
11989 :
11990 : // Look if this group contains the searched element.
11991 : int status;
11992 13241 : if (pszVar)
11993 13025 : status = nc_inq_varid(*pnGroupId, pszVar, pnId);
11994 : else // pszAtt != nullptr.
11995 216 : status = nc_inq_attid(*pnGroupId, NC_GLOBAL, pszAtt, pnId);
11996 :
11997 13241 : if (status == NC_NOERR)
11998 : {
11999 11575 : return CE_None;
12000 : }
12001 1666 : else if ((pszVar && status != NC_ENOTVAR) ||
12002 213 : (pszAtt && status != NC_ENOTATT))
12003 : {
12004 0 : NCDF_ERR(status);
12005 : }
12006 : // Element not found, in NC4 case we must search in other groups
12007 : // following the CF logic.
12008 :
12009 : // The first resolve mode consists to search on parent groups.
12010 1666 : if (eNCResolveMode == NCRM_PARENT)
12011 : {
12012 1566 : int nParentGroupId = -1;
12013 1566 : int status2 = nc_inq_grp_parent(*pnGroupId, &nParentGroupId);
12014 1566 : if (status2 == NC_NOERR)
12015 45 : aoQueueGroupIdsToVisit.push(nParentGroupId);
12016 1521 : else if (status2 != NC_ENOGRP)
12017 0 : NCDF_ERR(status2);
12018 1521 : else if (pszVar)
12019 : // When resolving a variable, if there is no more
12020 : // parent group then we switch to width-wise search mode
12021 : // starting from the latest found parent group.
12022 1311 : eNCResolveMode = NCRM_WIDTH_WISE;
12023 : }
12024 :
12025 : // The second resolve mode is a width-wise search.
12026 1666 : if (eNCResolveMode == NCRM_WIDTH_WISE)
12027 : {
12028 : // Enqueue all direct sub-groups.
12029 1411 : int nSubGroups = 0;
12030 1411 : int *panSubGroupIds = nullptr;
12031 1411 : NCDFGetSubGroups(*pnGroupId, &nSubGroups, &panSubGroupIds);
12032 1513 : for (int i = 0; i < nSubGroups; i++)
12033 102 : aoQueueGroupIdsToVisit.push(panSubGroupIds[i]);
12034 1411 : CPLFree(panSubGroupIds);
12035 : }
12036 : }
12037 :
12038 1519 : if (bMandatory)
12039 : {
12040 0 : char *pszStartGroupFullName = nullptr;
12041 0 : NCDFGetGroupFullName(nStartGroupId, &pszStartGroupFullName);
12042 0 : CPLError(CE_Failure, CPLE_AppDefined,
12043 : "Cannot resolve mandatory %s %s from group %s",
12044 : (pszVar ? pszVar : pszAtt),
12045 : (pszVar ? "variable" : "attribute"),
12046 0 : (pszStartGroupFullName ? pszStartGroupFullName : ""));
12047 0 : CPLFree(pszStartGroupFullName);
12048 : }
12049 :
12050 1519 : *pnGroupId = -1;
12051 1519 : *pnId = -1;
12052 1519 : return CE_Failure;
12053 : }
12054 :
12055 : // Resolve a variable name from a given starting group following the CF logic:
12056 : // - if var name is an absolute path then directly open it
12057 : // - first search in the starting group and its parent groups
12058 : // - then if there is no more parent group we switch to a width-wise search
12059 : // mode starting from the latest found parent group.
12060 : // The full CF logic is described here:
12061 : // https://github.com/diwg/cf2/blob/master/group/cf2-group.adoc#scope
12062 : // If bMandatory then print an error if resolving fails.
12063 : // TODO: implement support of relative paths.
12064 : // TODO: to follow strictly the CF logic, when searching for a coordinate
12065 : // variable, we must stop the parent search mode once the corresponding
12066 : // dimension is found and start the width-wise search from this group.
12067 : // TODO: to follow strictly the CF logic, when searching in width-wise mode
12068 : // we should skip every groups already visited during the parent
12069 : // search mode (but revisiting them should have no impact so we could
12070 : // let as it is if it is simpler...)
12071 : // TODO: CF specifies that the width-wise search order is "left-to-right" so
12072 : // maybe we must sort sibling groups alphabetically? but maybe not
12073 : // necessary if nc_inq_grps() already sort them?
12074 12881 : CPLErr NCDFResolveVar(int nStartGroupId, const char *pszVar, int *pnGroupId,
12075 : int *pnVarId, bool bMandatory)
12076 : {
12077 12881 : *pnGroupId = -1;
12078 12881 : *pnVarId = -1;
12079 12881 : int nGroupId = nStartGroupId, nVarId;
12080 12881 : if (pszVar[0] == '/')
12081 : {
12082 : // This is an absolute path: we can open the var directly.
12083 : int nRootGroupId;
12084 0 : ERR_RET(NCDFGetRootGroup(nStartGroupId, &nRootGroupId));
12085 0 : ERR_RET(NCDFOpenSubDataset(nRootGroupId, pszVar, &nGroupId, &nVarId));
12086 : }
12087 : else
12088 : {
12089 : // We have to search the variable following the CF logic.
12090 12881 : ERR_RET(NCDFResolveElem(nStartGroupId, pszVar, nullptr, &nGroupId,
12091 : &nVarId, bMandatory));
12092 : }
12093 11572 : *pnGroupId = nGroupId;
12094 11572 : *pnVarId = nVarId;
12095 11572 : return CE_None;
12096 : }
12097 :
12098 : // Like NCDFResolveVar but returns directly the var full name.
12099 1380 : static CPLErr NCDFResolveVarFullName(int nStartGroupId, const char *pszVar,
12100 : char **ppszFullName, bool bMandatory)
12101 : {
12102 1380 : *ppszFullName = nullptr;
12103 : int nGroupId, nVarId;
12104 1380 : ERR_RET(
12105 : NCDFResolveVar(nStartGroupId, pszVar, &nGroupId, &nVarId, bMandatory));
12106 1354 : return NCDFGetVarFullName(nGroupId, nVarId, ppszFullName);
12107 : }
12108 :
12109 : // Like NCDFResolveVar but resolves an attribute instead a variable and
12110 : // returns its integer value.
12111 : // Only GLOBAL attributes are supported for the moment.
12112 213 : static CPLErr NCDFResolveAttInt(int nStartGroupId, int nStartVarId,
12113 : const char *pszAtt, int *pnAtt, bool bMandatory)
12114 : {
12115 213 : int nGroupId = nStartGroupId, nAttId = nStartVarId;
12116 213 : ERR_RET(NCDFResolveElem(nStartGroupId, nullptr, pszAtt, &nGroupId, &nAttId,
12117 : bMandatory));
12118 3 : NCDF_ERR_RET(nc_get_att_int(nGroupId, NC_GLOBAL, pszAtt, pnAtt));
12119 3 : return CE_None;
12120 : }
12121 :
12122 : // Filter variables to keep only valid 2+D raster bands and vector fields in
12123 : // a given a NetCDF (or group) ID and its sub-groups.
12124 : // Coordinate or boundary variables are ignored.
12125 : // It also creates corresponding vector layers.
12126 519 : CPLErr netCDFDataset::FilterVars(
12127 : int nCdfId, bool bKeepRasters, bool bKeepVectors, char **papszIgnoreVars,
12128 : int *pnRasterVars, int *pnGroupId, int *pnVarId, int *pnIgnoredVars,
12129 : std::map<std::array<int, 3>, std::vector<std::pair<int, int>>>
12130 : &oMap2DDimsToGroupAndVar)
12131 : {
12132 519 : int nVars = 0;
12133 519 : int nRasterVars = 0;
12134 519 : NCDF_ERR(nc_inq(nCdfId, nullptr, &nVars, nullptr, nullptr));
12135 :
12136 1038 : std::vector<int> anPotentialVectorVarID;
12137 : // oMapDimIdToCount[x] = number of times dim x is the first dimension of
12138 : // potential vector variables
12139 1038 : std::map<int, int> oMapDimIdToCount;
12140 519 : int nVarXId = -1;
12141 519 : int nVarYId = -1;
12142 519 : int nVarZId = -1;
12143 519 : int nVarTimeId = -1;
12144 519 : int nVarTimeDimId = -1;
12145 519 : bool bIsVectorOnly = true;
12146 519 : int nProfileDimId = -1;
12147 519 : int nParentIndexVarID = -1;
12148 :
12149 3167 : for (int v = 0; v < nVars; v++)
12150 : {
12151 : int nVarDims;
12152 2648 : NCDF_ERR_RET(nc_inq_varndims(nCdfId, v, &nVarDims));
12153 : // Should we ignore this variable?
12154 : char szTemp[NC_MAX_NAME + 1];
12155 2648 : szTemp[0] = '\0';
12156 2648 : NCDF_ERR_RET(nc_inq_varname(nCdfId, v, szTemp));
12157 :
12158 2648 : if (strstr(szTemp, "_node_coordinates") ||
12159 2648 : strstr(szTemp, "_node_count"))
12160 : {
12161 : // Ignore CF-1.8 Simple Geometries helper variables
12162 69 : continue;
12163 : }
12164 :
12165 3863 : if (nVarDims == 1 && (NCDFIsVarLongitude(nCdfId, -1, szTemp) ||
12166 1284 : NCDFIsVarProjectionX(nCdfId, -1, szTemp)))
12167 : {
12168 354 : nVarXId = v;
12169 : }
12170 3155 : else if (nVarDims == 1 && (NCDFIsVarLatitude(nCdfId, -1, szTemp) ||
12171 930 : NCDFIsVarProjectionY(nCdfId, -1, szTemp)))
12172 : {
12173 354 : nVarYId = v;
12174 : }
12175 1871 : else if (nVarDims == 1 && NCDFIsVarVerticalCoord(nCdfId, -1, szTemp))
12176 : {
12177 78 : nVarZId = v;
12178 : }
12179 : else
12180 : {
12181 1793 : char *pszVarFullName = nullptr;
12182 1793 : CPLErr eErr = NCDFGetVarFullName(nCdfId, v, &pszVarFullName);
12183 1793 : if (eErr != CE_None)
12184 : {
12185 0 : CPLFree(pszVarFullName);
12186 0 : continue;
12187 : }
12188 : bool bIgnoreVar =
12189 1793 : (CSLFindString(papszIgnoreVars, pszVarFullName) != -1);
12190 1793 : CPLFree(pszVarFullName);
12191 1793 : if (bIgnoreVar)
12192 : {
12193 102 : if (nVarDims == 1 && NCDFIsVarTimeCoord(nCdfId, -1, szTemp))
12194 : {
12195 11 : nVarTimeId = v;
12196 11 : nc_inq_vardimid(nCdfId, v, &nVarTimeDimId);
12197 : }
12198 91 : else if (nVarDims > 1)
12199 : {
12200 87 : (*pnIgnoredVars)++;
12201 87 : CPLDebug("GDAL_netCDF", "variable #%d [%s] was ignored", v,
12202 : szTemp);
12203 : }
12204 : }
12205 : // Only accept 2+D vars.
12206 1691 : else if (nVarDims >= 2)
12207 : {
12208 676 : bool bRasterCandidate = true;
12209 : // Identify variables that might be vector variables
12210 676 : if (nVarDims == 2)
12211 : {
12212 605 : int anDimIds[2] = {-1, -1};
12213 605 : nc_inq_vardimid(nCdfId, v, anDimIds);
12214 :
12215 605 : nc_type vartype = NC_NAT;
12216 605 : nc_inq_vartype(nCdfId, v, &vartype);
12217 :
12218 : char szDimNameFirst[NC_MAX_NAME + 1];
12219 : char szDimNameSecond[NC_MAX_NAME + 1];
12220 605 : szDimNameFirst[0] = '\0';
12221 605 : szDimNameSecond[0] = '\0';
12222 1366 : if (vartype == NC_CHAR &&
12223 156 : nc_inq_dimname(nCdfId, anDimIds[0], szDimNameFirst) ==
12224 156 : NC_NOERR &&
12225 156 : nc_inq_dimname(nCdfId, anDimIds[1], szDimNameSecond) ==
12226 156 : NC_NOERR &&
12227 156 : !NCDFIsVarLongitude(nCdfId, -1, szDimNameSecond) &&
12228 156 : !NCDFIsVarProjectionX(nCdfId, -1, szDimNameSecond) &&
12229 917 : !NCDFIsVarLatitude(nCdfId, -1, szDimNameFirst) &&
12230 156 : !NCDFIsVarProjectionY(nCdfId, -1, szDimNameFirst))
12231 : {
12232 156 : anPotentialVectorVarID.push_back(v);
12233 156 : oMapDimIdToCount[anDimIds[0]]++;
12234 156 : if (strstr(szDimNameSecond, "_max_width"))
12235 : {
12236 127 : bRasterCandidate = false;
12237 : }
12238 : else
12239 : {
12240 29 : std::array<int, 3> oKey{anDimIds[0], anDimIds[1],
12241 29 : vartype};
12242 29 : oMap2DDimsToGroupAndVar[oKey].emplace_back(
12243 29 : std::pair(nCdfId, v));
12244 : }
12245 : }
12246 : else
12247 : {
12248 449 : std::array<int, 3> oKey{anDimIds[0], anDimIds[1],
12249 449 : vartype};
12250 449 : oMap2DDimsToGroupAndVar[oKey].emplace_back(
12251 449 : std::pair(nCdfId, v));
12252 449 : bIsVectorOnly = false;
12253 : }
12254 : }
12255 : else
12256 : {
12257 71 : bIsVectorOnly = false;
12258 : }
12259 676 : if (bKeepRasters && bRasterCandidate)
12260 : {
12261 520 : *pnGroupId = nCdfId;
12262 520 : *pnVarId = v;
12263 520 : nRasterVars++;
12264 : }
12265 : }
12266 1015 : else if (nVarDims == 1)
12267 : {
12268 725 : nc_type atttype = NC_NAT;
12269 725 : size_t attlen = 0;
12270 725 : if (nc_inq_att(nCdfId, v, "instance_dimension", &atttype,
12271 14 : &attlen) == NC_NOERR &&
12272 725 : atttype == NC_CHAR && attlen < NC_MAX_NAME)
12273 : {
12274 : char szInstanceDimension[NC_MAX_NAME + 1];
12275 14 : if (nc_get_att_text(nCdfId, v, "instance_dimension",
12276 14 : szInstanceDimension) == NC_NOERR)
12277 : {
12278 14 : szInstanceDimension[attlen] = 0;
12279 14 : int status = nc_inq_dimid(nCdfId, szInstanceDimension,
12280 : &nProfileDimId);
12281 14 : if (status == NC_NOERR)
12282 14 : nParentIndexVarID = v;
12283 : else
12284 0 : nProfileDimId = -1;
12285 14 : if (status == NC_EBADDIM)
12286 0 : CPLError(CE_Warning, CPLE_AppDefined,
12287 : "Attribute instance_dimension='%s' refers "
12288 : "to a non existing dimension",
12289 : szInstanceDimension);
12290 : else
12291 14 : NCDF_ERR(status);
12292 : }
12293 : }
12294 725 : if (v != nParentIndexVarID)
12295 : {
12296 711 : anPotentialVectorVarID.push_back(v);
12297 711 : int nDimId = -1;
12298 711 : nc_inq_vardimid(nCdfId, v, &nDimId);
12299 711 : oMapDimIdToCount[nDimId]++;
12300 : }
12301 : }
12302 : }
12303 : }
12304 :
12305 : // If we are opened in raster-only mode and that there are only 1D or 2D
12306 : // variables and that the 2D variables have no X/Y dim, and all
12307 : // variables refer to the same main dimension (or 2 dimensions for
12308 : // featureType=profile), then it is a pure vector dataset
12309 : CPLString osFeatureType(
12310 519 : CSLFetchNameValueDef(papszMetadata, "NC_GLOBAL#featureType", ""));
12311 408 : if (bKeepRasters && !bKeepVectors && bIsVectorOnly && nRasterVars > 0 &&
12312 927 : !anPotentialVectorVarID.empty() &&
12313 0 : (oMapDimIdToCount.size() == 1 ||
12314 0 : (EQUAL(osFeatureType, "profile") && oMapDimIdToCount.size() == 2 &&
12315 0 : nProfileDimId >= 0)))
12316 : {
12317 0 : anPotentialVectorVarID.resize(0);
12318 : }
12319 : else
12320 : {
12321 519 : *pnRasterVars += nRasterVars;
12322 : }
12323 :
12324 519 : if (!anPotentialVectorVarID.empty() && bKeepVectors)
12325 : {
12326 : // Take the dimension that is referenced the most times.
12327 64 : if (!(oMapDimIdToCount.size() == 1 ||
12328 27 : (EQUAL(osFeatureType, "profile") &&
12329 26 : oMapDimIdToCount.size() == 2 && nProfileDimId >= 0)))
12330 : {
12331 1 : CPLError(CE_Warning, CPLE_AppDefined,
12332 : "The dataset has several variables that could be "
12333 : "identified as vector fields, but not all share the same "
12334 : "primary dimension. Consequently they will be ignored.");
12335 : }
12336 : else
12337 : {
12338 50 : if (nVarTimeId >= 0 &&
12339 50 : oMapDimIdToCount.find(nVarTimeDimId) != oMapDimIdToCount.end())
12340 : {
12341 1 : anPotentialVectorVarID.push_back(nVarTimeId);
12342 : }
12343 49 : CreateGrpVectorLayers(nCdfId, osFeatureType, anPotentialVectorVarID,
12344 : oMapDimIdToCount, nVarXId, nVarYId, nVarZId,
12345 : nProfileDimId, nParentIndexVarID,
12346 : bKeepRasters);
12347 : }
12348 : }
12349 :
12350 : // Recurse on sub-groups.
12351 519 : int nSubGroups = 0;
12352 519 : int *panSubGroupIds = nullptr;
12353 519 : NCDFGetSubGroups(nCdfId, &nSubGroups, &panSubGroupIds);
12354 551 : for (int i = 0; i < nSubGroups; i++)
12355 : {
12356 32 : FilterVars(panSubGroupIds[i], bKeepRasters, bKeepVectors,
12357 : papszIgnoreVars, pnRasterVars, pnGroupId, pnVarId,
12358 : pnIgnoredVars, oMap2DDimsToGroupAndVar);
12359 : }
12360 519 : CPLFree(panSubGroupIds);
12361 :
12362 519 : return CE_None;
12363 : }
12364 :
12365 : // Create vector layers from given potentially identified vector variables
12366 : // resulting from the scanning of a NetCDF (or group) ID.
12367 49 : CPLErr netCDFDataset::CreateGrpVectorLayers(
12368 : int nCdfId, const CPLString &osFeatureType,
12369 : const std::vector<int> &anPotentialVectorVarID,
12370 : const std::map<int, int> &oMapDimIdToCount, int nVarXId, int nVarYId,
12371 : int nVarZId, int nProfileDimId, int nParentIndexVarID, bool bKeepRasters)
12372 : {
12373 49 : char *pszGroupName = nullptr;
12374 49 : NCDFGetGroupFullName(nCdfId, &pszGroupName);
12375 49 : if (pszGroupName == nullptr || pszGroupName[0] == '\0')
12376 : {
12377 47 : CPLFree(pszGroupName);
12378 47 : pszGroupName = CPLStrdup(CPLGetBasenameSafe(osFilename).c_str());
12379 : }
12380 49 : OGRwkbGeometryType eGType = wkbUnknown;
12381 : CPLString osLayerName = CSLFetchNameValueDef(
12382 98 : papszMetadata, "NC_GLOBAL#ogr_layer_name", pszGroupName);
12383 49 : CPLFree(pszGroupName);
12384 49 : papszMetadata =
12385 49 : CSLSetNameValue(papszMetadata, "NC_GLOBAL#ogr_layer_name", nullptr);
12386 :
12387 49 : if (EQUAL(osFeatureType, "point") || EQUAL(osFeatureType, "profile"))
12388 : {
12389 33 : papszMetadata =
12390 33 : CSLSetNameValue(papszMetadata, "NC_GLOBAL#featureType", nullptr);
12391 33 : eGType = wkbPoint;
12392 : }
12393 :
12394 : const char *pszLayerType =
12395 49 : CSLFetchNameValue(papszMetadata, "NC_GLOBAL#ogr_layer_type");
12396 49 : if (pszLayerType != nullptr)
12397 : {
12398 9 : eGType = OGRFromOGCGeomType(pszLayerType);
12399 9 : papszMetadata =
12400 9 : CSLSetNameValue(papszMetadata, "NC_GLOBAL#ogr_layer_type", nullptr);
12401 : }
12402 :
12403 : CPLString osGeometryField =
12404 98 : CSLFetchNameValueDef(papszMetadata, "NC_GLOBAL#ogr_geometry_field", "");
12405 49 : papszMetadata =
12406 49 : CSLSetNameValue(papszMetadata, "NC_GLOBAL#ogr_geometry_field", nullptr);
12407 :
12408 49 : int nFirstVarId = -1;
12409 49 : int nVectorDim = oMapDimIdToCount.rbegin()->first;
12410 49 : if (EQUAL(osFeatureType, "profile") && oMapDimIdToCount.size() == 2)
12411 : {
12412 13 : if (nVectorDim == nProfileDimId)
12413 0 : nVectorDim = oMapDimIdToCount.begin()->first;
12414 : }
12415 : else
12416 : {
12417 36 : nProfileDimId = -1;
12418 : }
12419 62 : for (size_t j = 0; j < anPotentialVectorVarID.size(); j++)
12420 : {
12421 62 : int anDimIds[2] = {-1, -1};
12422 62 : nc_inq_vardimid(nCdfId, anPotentialVectorVarID[j], anDimIds);
12423 62 : if (nVectorDim == anDimIds[0])
12424 : {
12425 49 : nFirstVarId = anPotentialVectorVarID[j];
12426 49 : break;
12427 : }
12428 : }
12429 :
12430 : // In case where coordinates are explicitly specified for one of the
12431 : // field/variable, use them in priority over the ones that might have been
12432 : // identified above.
12433 49 : char *pszCoordinates = nullptr;
12434 49 : if (NCDFGetAttr(nCdfId, nFirstVarId, "coordinates", &pszCoordinates) ==
12435 : CE_None)
12436 : {
12437 34 : char **papszTokens = NCDFTokenizeCoordinatesAttribute(pszCFCoordinates);
12438 34 : for (int i = 0; papszTokens != nullptr && papszTokens[i] != nullptr;
12439 : i++)
12440 : {
12441 0 : if (NCDFIsVarLongitude(nCdfId, -1, papszTokens[i]) ||
12442 0 : NCDFIsVarProjectionX(nCdfId, -1, papszTokens[i]))
12443 : {
12444 0 : nVarXId = -1;
12445 0 : CPL_IGNORE_RET_VAL(
12446 0 : nc_inq_varid(nCdfId, papszTokens[i], &nVarXId));
12447 : }
12448 0 : else if (NCDFIsVarLatitude(nCdfId, -1, papszTokens[i]) ||
12449 0 : NCDFIsVarProjectionY(nCdfId, -1, papszTokens[i]))
12450 : {
12451 0 : nVarYId = -1;
12452 0 : CPL_IGNORE_RET_VAL(
12453 0 : nc_inq_varid(nCdfId, papszTokens[i], &nVarYId));
12454 : }
12455 0 : else if (NCDFIsVarVerticalCoord(nCdfId, -1, papszTokens[i]))
12456 : {
12457 0 : nVarZId = -1;
12458 0 : CPL_IGNORE_RET_VAL(
12459 0 : nc_inq_varid(nCdfId, papszTokens[i], &nVarZId));
12460 : }
12461 : }
12462 34 : CSLDestroy(papszTokens);
12463 : }
12464 49 : CPLFree(pszCoordinates);
12465 :
12466 : // Check that the X,Y,Z vars share 1D and share the same dimension as
12467 : // attribute variables.
12468 49 : if (nVarXId >= 0 && nVarYId >= 0)
12469 : {
12470 38 : int nVarDimCount = -1;
12471 38 : int nVarDimId = -1;
12472 38 : if (nc_inq_varndims(nCdfId, nVarXId, &nVarDimCount) != NC_NOERR ||
12473 38 : nVarDimCount != 1 ||
12474 38 : nc_inq_vardimid(nCdfId, nVarXId, &nVarDimId) != NC_NOERR ||
12475 38 : nVarDimId != ((nProfileDimId >= 0) ? nProfileDimId : nVectorDim) ||
12476 35 : nc_inq_varndims(nCdfId, nVarYId, &nVarDimCount) != NC_NOERR ||
12477 35 : nVarDimCount != 1 ||
12478 111 : nc_inq_vardimid(nCdfId, nVarYId, &nVarDimId) != NC_NOERR ||
12479 35 : nVarDimId != ((nProfileDimId >= 0) ? nProfileDimId : nVectorDim))
12480 : {
12481 3 : nVarXId = nVarYId = -1;
12482 : }
12483 69 : else if (nVarZId >= 0 &&
12484 34 : (nc_inq_varndims(nCdfId, nVarZId, &nVarDimCount) != NC_NOERR ||
12485 34 : nVarDimCount != 1 ||
12486 34 : nc_inq_vardimid(nCdfId, nVarZId, &nVarDimId) != NC_NOERR ||
12487 34 : nVarDimId != nVectorDim))
12488 : {
12489 0 : nVarZId = -1;
12490 : }
12491 : }
12492 :
12493 49 : if (eGType == wkbUnknown && nVarXId >= 0 && nVarYId >= 0)
12494 : {
12495 2 : eGType = wkbPoint;
12496 : }
12497 49 : if (eGType == wkbPoint && nVarXId >= 0 && nVarYId >= 0 && nVarZId >= 0)
12498 : {
12499 34 : eGType = wkbPoint25D;
12500 : }
12501 49 : if (eGType == wkbUnknown && osGeometryField.empty())
12502 : {
12503 5 : eGType = wkbNone;
12504 : }
12505 :
12506 : // Read projection info
12507 49 : char **papszMetadataBackup = CSLDuplicate(papszMetadata);
12508 49 : ReadAttributes(nCdfId, nFirstVarId);
12509 49 : if (!this->bSGSupport)
12510 49 : SetProjectionFromVar(nCdfId, nFirstVarId, true);
12511 49 : const char *pszValue = FetchAttr(nCdfId, nFirstVarId, CF_GRD_MAPPING);
12512 49 : char *pszGridMapping = (pszValue ? CPLStrdup(pszValue) : nullptr);
12513 49 : CSLDestroy(papszMetadata);
12514 49 : papszMetadata = papszMetadataBackup;
12515 :
12516 49 : OGRSpatialReference *poSRS = nullptr;
12517 49 : if (!m_oSRS.IsEmpty())
12518 : {
12519 21 : poSRS = m_oSRS.Clone();
12520 : }
12521 : // Reset if there's a 2D raster
12522 49 : m_bHasProjection = false;
12523 49 : m_bHasGeoTransform = false;
12524 :
12525 49 : if (!bKeepRasters)
12526 : {
12527 : // Strip out uninteresting metadata.
12528 45 : papszMetadata =
12529 45 : CSLSetNameValue(papszMetadata, "NC_GLOBAL#Conventions", nullptr);
12530 45 : papszMetadata =
12531 45 : CSLSetNameValue(papszMetadata, "NC_GLOBAL#GDAL", nullptr);
12532 45 : papszMetadata =
12533 45 : CSLSetNameValue(papszMetadata, "NC_GLOBAL#history", nullptr);
12534 : }
12535 :
12536 : std::shared_ptr<netCDFLayer> poLayer(
12537 49 : new netCDFLayer(this, nCdfId, osLayerName, eGType, poSRS));
12538 49 : if (poSRS != nullptr)
12539 21 : poSRS->Release();
12540 49 : poLayer->SetRecordDimID(nVectorDim);
12541 49 : if (wkbFlatten(eGType) == wkbPoint && nVarXId >= 0 && nVarYId >= 0)
12542 : {
12543 35 : poLayer->SetXYZVars(nVarXId, nVarYId, nVarZId);
12544 : }
12545 14 : else if (!osGeometryField.empty())
12546 : {
12547 9 : poLayer->SetWKTGeometryField(osGeometryField);
12548 : }
12549 49 : if (pszGridMapping != nullptr)
12550 : {
12551 21 : poLayer->SetGridMapping(pszGridMapping);
12552 21 : CPLFree(pszGridMapping);
12553 : }
12554 49 : poLayer->SetProfile(nProfileDimId, nParentIndexVarID);
12555 :
12556 574 : for (size_t j = 0; j < anPotentialVectorVarID.size(); j++)
12557 : {
12558 525 : int anDimIds[2] = {-1, -1};
12559 525 : nc_inq_vardimid(nCdfId, anPotentialVectorVarID[j], anDimIds);
12560 525 : if (anDimIds[0] == nVectorDim ||
12561 24 : (nProfileDimId >= 0 && anDimIds[0] == nProfileDimId))
12562 : {
12563 : #ifdef NCDF_DEBUG
12564 : char szTemp2[NC_MAX_NAME + 1] = {};
12565 : CPL_IGNORE_RET_VAL(
12566 : nc_inq_varname(nCdfId, anPotentialVectorVarID[j], szTemp2));
12567 : CPLDebug("GDAL_netCDF", "Variable %s is a vector field", szTemp2);
12568 : #endif
12569 525 : poLayer->AddField(anPotentialVectorVarID[j]);
12570 : }
12571 : }
12572 :
12573 49 : if (poLayer->GetLayerDefn()->GetFieldCount() != 0 ||
12574 0 : poLayer->GetGeomType() != wkbNone)
12575 : {
12576 49 : papoLayers.push_back(poLayer);
12577 : }
12578 :
12579 98 : return CE_None;
12580 : }
12581 :
12582 : // Get all coordinate and boundary variables full names referenced in
12583 : // a given a NetCDF (or group) ID and its sub-groups.
12584 : // These variables are identified in other variable's
12585 : // "coordinates" and "bounds" attribute.
12586 : // Searching coordinate and boundary variables may need to explore
12587 : // parents groups (or other groups in case of reference given in form of an
12588 : // absolute path).
12589 : // See CF sections 5.2, 5.6 and 7.1
12590 520 : static CPLErr NCDFGetCoordAndBoundVarFullNames(int nCdfId, char ***ppapszVars)
12591 : {
12592 520 : int nVars = 0;
12593 520 : NCDF_ERR(nc_inq(nCdfId, nullptr, &nVars, nullptr, nullptr));
12594 :
12595 3182 : for (int v = 0; v < nVars; v++)
12596 : {
12597 2662 : char *pszTemp = nullptr;
12598 2662 : char **papszTokens = nullptr;
12599 2662 : if (NCDFGetAttr(nCdfId, v, "coordinates", &pszTemp) == CE_None)
12600 445 : papszTokens = NCDFTokenizeCoordinatesAttribute(pszTemp);
12601 2662 : CPLFree(pszTemp);
12602 2662 : pszTemp = nullptr;
12603 2662 : if (NCDFGetAttr(nCdfId, v, "bounds", &pszTemp) == CE_None &&
12604 2662 : pszTemp != nullptr && !EQUAL(pszTemp, ""))
12605 17 : papszTokens = CSLAddString(papszTokens, pszTemp);
12606 2662 : CPLFree(pszTemp);
12607 3948 : for (int i = 0; papszTokens != nullptr && papszTokens[i] != nullptr;
12608 : i++)
12609 : {
12610 1286 : char *pszVarFullName = nullptr;
12611 1286 : if (NCDFResolveVarFullName(nCdfId, papszTokens[i],
12612 1286 : &pszVarFullName) == CE_None)
12613 1260 : *ppapszVars = CSLAddString(*ppapszVars, pszVarFullName);
12614 1286 : CPLFree(pszVarFullName);
12615 : }
12616 2662 : CSLDestroy(papszTokens);
12617 : }
12618 :
12619 : // Recurse on sub-groups.
12620 : int nSubGroups;
12621 520 : int *panSubGroupIds = nullptr;
12622 520 : NCDFGetSubGroups(nCdfId, &nSubGroups, &panSubGroupIds);
12623 552 : for (int i = 0; i < nSubGroups; i++)
12624 : {
12625 32 : NCDFGetCoordAndBoundVarFullNames(panSubGroupIds[i], ppapszVars);
12626 : }
12627 520 : CPLFree(panSubGroupIds);
12628 :
12629 520 : return CE_None;
12630 : }
12631 :
12632 : // Check if give type is user defined
12633 900 : bool NCDFIsUserDefinedType(int /*ncid*/, int type)
12634 : {
12635 900 : return type >= NC_FIRSTUSERTYPEID;
12636 : }
12637 :
12638 558 : char **NCDFTokenizeCoordinatesAttribute(const char *pszCoordinates)
12639 : {
12640 : // CF conventions use space as the separator for variable names in the
12641 : // coordinates attribute, but some products such as
12642 : // https://sentinel.esa.int/web/sentinel/technical-guides/sentinel-3-synergy/products-algorithms/level-2-aod-algorithms-and-products/level-2-aod-products-description
12643 : // use comma.
12644 558 : return CSLTokenizeString2(pszCoordinates, ", ", 0);
12645 : }
|