Coverage Report

Created: 2026-07-16 06:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/PROJ/src/iso19111/io.cpp
Line
Count
Source
1
/******************************************************************************
2
 *
3
 * Project:  PROJ
4
 * Purpose:  ISO19111:2019 implementation
5
 * Author:   Even Rouault <even dot rouault at spatialys dot com>
6
 *
7
 ******************************************************************************
8
 * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com>
9
 *
10
 * Permission is hereby granted, free of charge, to any person obtaining a
11
 * copy of this software and associated documentation files (the "Software"),
12
 * to deal in the Software without restriction, including without limitation
13
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
14
 * and/or sell copies of the Software, and to permit persons to whom the
15
 * Software is furnished to do so, subject to the following conditions:
16
 *
17
 * The above copyright notice and this permission notice shall be included
18
 * in all copies or substantial portions of the Software.
19
 *
20
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
21
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
25
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
26
 * DEALINGS IN THE SOFTWARE.
27
 ****************************************************************************/
28
29
#ifndef FROM_PROJ_CPP
30
#define FROM_PROJ_CPP
31
#endif
32
33
#include <algorithm>
34
#include <cassert>
35
#include <cctype>
36
#include <cmath>
37
#include <cstring>
38
#include <limits>
39
#include <list>
40
#include <locale>
41
#include <map>
42
#include <set>
43
#include <sstream> // std::istringstream
44
#include <string>
45
#include <utility>
46
#include <vector>
47
48
#include "proj/common.hpp"
49
#include "proj/coordinateoperation.hpp"
50
#include "proj/coordinates.hpp"
51
#include "proj/coordinatesystem.hpp"
52
#include "proj/crs.hpp"
53
#include "proj/datum.hpp"
54
#include "proj/io.hpp"
55
#include "proj/metadata.hpp"
56
#include "proj/util.hpp"
57
58
#include "operation/coordinateoperation_internal.hpp"
59
#include "operation/esriparammappings.hpp"
60
#include "operation/oputils.hpp"
61
#include "operation/parammappings.hpp"
62
63
#include "proj/internal/coordinatesystem_internal.hpp"
64
#include "proj/internal/datum_internal.hpp"
65
#include "proj/internal/internal.hpp"
66
#include "proj/internal/io_internal.hpp"
67
68
#include "proj/internal/include_nlohmann_json.hpp"
69
70
#include "proj_constants.h"
71
72
#include "proj_json_streaming_writer.hpp"
73
#include "wkt1_parser.h"
74
#include "wkt2_parser.h"
75
76
// PROJ include order is sensitive
77
// clang-format off
78
#include "proj.h"
79
#include "proj_internal.h"
80
// clang-format on
81
82
using namespace NS_PROJ::common;
83
using namespace NS_PROJ::coordinates;
84
using namespace NS_PROJ::crs;
85
using namespace NS_PROJ::cs;
86
using namespace NS_PROJ::datum;
87
using namespace NS_PROJ::internal;
88
using namespace NS_PROJ::metadata;
89
using namespace NS_PROJ::operation;
90
using namespace NS_PROJ::util;
91
92
using json = nlohmann::json;
93
94
//! @cond Doxygen_Suppress
95
static const std::string emptyString{};
96
//! @endcond
97
98
#if 0
99
namespace dropbox{ namespace oxygen {
100
template<> nn<NS_PROJ::io::DatabaseContextPtr>::~nn() = default;
101
template<> nn<NS_PROJ::io::AuthorityFactoryPtr>::~nn() = default;
102
template<> nn<std::shared_ptr<NS_PROJ::io::IPROJStringExportable>>::~nn() = default;
103
template<> nn<std::unique_ptr<NS_PROJ::io::PROJStringFormatter, std::default_delete<NS_PROJ::io::PROJStringFormatter> > >::~nn() = default;
104
template<> nn<std::unique_ptr<NS_PROJ::io::WKTFormatter, std::default_delete<NS_PROJ::io::WKTFormatter> > >::~nn() = default;
105
template<> nn<std::unique_ptr<NS_PROJ::io::WKTNode, std::default_delete<NS_PROJ::io::WKTNode> > >::~nn() = default;
106
}}
107
#endif
108
109
NS_PROJ_START
110
namespace io {
111
112
//! @cond Doxygen_Suppress
113
const char *JSONFormatter::PROJJSON_v0_7 =
114
    "https://proj.org/schemas/v0.7/projjson.schema.json";
115
116
#define PROJJSON_DEFAULT_VERSION JSONFormatter::PROJJSON_v0_7
117
118
//! @endcond
119
120
// ---------------------------------------------------------------------------
121
122
//! @cond Doxygen_Suppress
123
13.7M
IWKTExportable::~IWKTExportable() = default;
124
125
// ---------------------------------------------------------------------------
126
127
0
std::string IWKTExportable::exportToWKT(WKTFormatter *formatter) const {
128
0
    _exportToWKT(formatter);
129
0
    return formatter->toString();
130
0
}
131
132
//! @endcond
133
134
// ---------------------------------------------------------------------------
135
136
//! @cond Doxygen_Suppress
137
struct WKTFormatter::Private {
138
    struct Params {
139
        WKTFormatter::Convention convention_ = WKTFormatter::Convention::WKT2;
140
        WKTFormatter::Version version_ = WKTFormatter::Version::WKT2;
141
        bool multiLine_ = true;
142
        bool strict_ = true;
143
        int indentWidth_ = 4;
144
        bool idOnTopLevelOnly_ = false;
145
        bool outputAxisOrder_ = false;
146
        bool primeMeridianOmittedIfGreenwich_ = false;
147
        bool ellipsoidUnitOmittedIfMetre_ = false;
148
        bool primeMeridianOrParameterUnitOmittedIfSameAsAxis_ = false;
149
        bool forceUNITKeyword_ = false;
150
        bool outputCSUnitOnlyOnceIfSame_ = false;
151
        bool primeMeridianInDegree_ = false;
152
        bool use2019Keywords_ = false;
153
        bool useESRIDialect_ = false;
154
        bool allowEllipsoidalHeightAsVerticalCRS_ = false;
155
        bool allowLINUNITNode_ = false;
156
        OutputAxisRule outputAxis_ = WKTFormatter::OutputAxisRule::YES;
157
    };
158
    Params params_{};
159
    DatabaseContextPtr dbContext_{};
160
161
    int indentLevel_ = 0;
162
    int level_ = 0;
163
    std::vector<bool> stackHasChild_{};
164
    std::vector<bool> stackHasId_{false};
165
    std::vector<bool> stackEmptyKeyword_{};
166
    std::vector<bool> stackDisableUsage_{};
167
    std::vector<bool> outputUnitStack_{true};
168
    std::vector<bool> outputIdStack_{true};
169
    std::vector<UnitOfMeasureNNPtr> axisLinearUnitStack_{
170
        util::nn_make_shared<UnitOfMeasure>(UnitOfMeasure::METRE)};
171
    std::vector<UnitOfMeasureNNPtr> axisAngularUnitStack_{
172
        util::nn_make_shared<UnitOfMeasure>(UnitOfMeasure::DEGREE)};
173
    bool abridgedTransformation_ = false;
174
    bool useDerivingConversion_ = false;
175
    std::vector<double> toWGS84Parameters_{};
176
    std::string hDatumExtension_{};
177
    std::string vDatumExtension_{};
178
    crs::GeographicCRSPtr geogCRSOfCompoundCRS_{};
179
    std::string result_{};
180
181
    // cppcheck-suppress functionStatic
182
    void addNewLine();
183
    void addIndentation();
184
    // cppcheck-suppress functionStatic
185
    void startNewChild();
186
};
187
//! @endcond
188
189
// ---------------------------------------------------------------------------
190
191
/** \brief Constructs a new formatter.
192
 *
193
 * A formatter can be used only once (its internal state is mutated)
194
 *
195
 * Its default behavior can be adjusted with the different setters.
196
 *
197
 * @param convention WKT flavor. Defaults to Convention::WKT2
198
 * @param dbContext Database context, to allow queries in it if needed.
199
 * This is used for example for WKT1_ESRI output to do name substitutions.
200
 *
201
 * @return new formatter.
202
 */
203
WKTFormatterNNPtr WKTFormatter::create(Convention convention,
204
                                       // cppcheck-suppress passedByValue
205
0
                                       DatabaseContextPtr dbContext) {
206
0
    auto ret = NN_NO_CHECK(WKTFormatter::make_unique<WKTFormatter>(convention));
207
0
    ret->d->dbContext_ = std::move(dbContext);
208
0
    return ret;
209
0
}
210
211
// ---------------------------------------------------------------------------
212
213
/** \brief Constructs a new formatter from another one.
214
 *
215
 * A formatter can be used only once (its internal state is mutated)
216
 *
217
 * Its default behavior can be adjusted with the different setters.
218
 *
219
 * @param other source formatter.
220
 * @return new formatter.
221
 */
222
0
WKTFormatterNNPtr WKTFormatter::create(const WKTFormatterNNPtr &other) {
223
0
    auto f = create(other->d->params_.convention_, other->d->dbContext_);
224
0
    f->d->params_ = other->d->params_;
225
0
    return f;
226
0
}
227
228
// ---------------------------------------------------------------------------
229
230
//! @cond Doxygen_Suppress
231
0
WKTFormatter::~WKTFormatter() = default;
232
//! @endcond
233
234
// ---------------------------------------------------------------------------
235
236
/** \brief Whether to use multi line output or not. */
237
0
WKTFormatter &WKTFormatter::setMultiLine(bool multiLine) noexcept {
238
0
    d->params_.multiLine_ = multiLine;
239
0
    return *this;
240
0
}
241
242
// ---------------------------------------------------------------------------
243
244
/** \brief Set number of spaces for each indentation level (defaults to 4).
245
 */
246
0
WKTFormatter &WKTFormatter::setIndentationWidth(int width) noexcept {
247
0
    d->params_.indentWidth_ = width;
248
0
    return *this;
249
0
}
250
251
// ---------------------------------------------------------------------------
252
253
/** \brief Set whether AXIS nodes should be output.
254
 */
255
WKTFormatter &
256
0
WKTFormatter::setOutputAxis(OutputAxisRule outputAxisIn) noexcept {
257
0
    d->params_.outputAxis_ = outputAxisIn;
258
0
    return *this;
259
0
}
260
261
// ---------------------------------------------------------------------------
262
263
/** \brief Set whether the formatter should operate on strict more or not.
264
 *
265
 * The default is strict mode, in which case a FormattingException can be
266
 * thrown.
267
 * In non-strict mode, a Geographic 3D CRS can be for example exported as
268
 * WKT1_GDAL with 3 axes, whereas this is normally not allowed.
269
 */
270
0
WKTFormatter &WKTFormatter::setStrict(bool strictIn) noexcept {
271
0
    d->params_.strict_ = strictIn;
272
0
    return *this;
273
0
}
274
275
// ---------------------------------------------------------------------------
276
277
/** \brief Returns whether the formatter is in strict mode. */
278
0
bool WKTFormatter::isStrict() const noexcept { return d->params_.strict_; }
279
280
// ---------------------------------------------------------------------------
281
282
/** \brief Set whether the formatter should export, in WKT1, a Geographic or
283
 * Projected 3D CRS as a compound CRS whose vertical part represents an
284
 * ellipsoidal height.
285
 */
286
WKTFormatter &
287
0
WKTFormatter::setAllowEllipsoidalHeightAsVerticalCRS(bool allow) noexcept {
288
0
    d->params_.allowEllipsoidalHeightAsVerticalCRS_ = allow;
289
0
    return *this;
290
0
}
291
292
// ---------------------------------------------------------------------------
293
294
/** \brief Return whether the formatter should export, in WKT1, a Geographic or
295
 * Projected 3D CRS as a compound CRS whose vertical part represents an
296
 * ellipsoidal height.
297
 */
298
0
bool WKTFormatter::isAllowedEllipsoidalHeightAsVerticalCRS() const noexcept {
299
0
    return d->params_.allowEllipsoidalHeightAsVerticalCRS_;
300
0
}
301
302
// ---------------------------------------------------------------------------
303
304
/** \brief Set whether the formatter should export, in WKT1_ESRI, a Geographic
305
 * 3D CRS with the relatively new (ArcGIS Pro >= 2.7) LINUNIT node.
306
 * Defaults to true.
307
 * @since PROJ 9.1
308
 */
309
0
WKTFormatter &WKTFormatter::setAllowLINUNITNode(bool allow) noexcept {
310
0
    d->params_.allowLINUNITNode_ = allow;
311
0
    return *this;
312
0
}
313
314
// ---------------------------------------------------------------------------
315
316
/** \brief Return whether the formatter should export, in WKT1_ESRI, a
317
 * Geographic 3D CRS with the relatively new (ArcGIS Pro >= 2.7) LINUNIT node.
318
 * Defaults to true.
319
 * @since PROJ 9.1
320
 */
321
0
bool WKTFormatter::isAllowedLINUNITNode() const noexcept {
322
0
    return d->params_.allowLINUNITNode_;
323
0
}
324
325
// ---------------------------------------------------------------------------
326
327
/** Returns the WKT string from the formatter. */
328
0
const std::string &WKTFormatter::toString() const {
329
0
    if (d->indentLevel_ > 0 || d->level_ > 0) {
330
        // For intermediary nodes, the formatter is in a inconsistent
331
        // state.
332
0
        throw FormattingException("toString() called on intermediate nodes");
333
0
    }
334
0
    if (d->axisLinearUnitStack_.size() != 1)
335
0
        throw FormattingException(
336
0
            "Unbalanced pushAxisLinearUnit() / popAxisLinearUnit()");
337
0
    if (d->axisAngularUnitStack_.size() != 1)
338
0
        throw FormattingException(
339
0
            "Unbalanced pushAxisAngularUnit() / popAxisAngularUnit()");
340
0
    if (d->outputIdStack_.size() != 1)
341
0
        throw FormattingException("Unbalanced pushOutputId() / popOutputId()");
342
0
    if (d->outputUnitStack_.size() != 1)
343
0
        throw FormattingException(
344
0
            "Unbalanced pushOutputUnit() / popOutputUnit()");
345
0
    if (d->stackHasId_.size() != 1)
346
0
        throw FormattingException("Unbalanced pushHasId() / popHasId()");
347
0
    if (!d->stackDisableUsage_.empty())
348
0
        throw FormattingException(
349
0
            "Unbalanced pushDisableUsage() / popDisableUsage()");
350
351
0
    return d->result_;
352
0
}
353
354
//! @cond Doxygen_Suppress
355
356
// ---------------------------------------------------------------------------
357
358
WKTFormatter::WKTFormatter(Convention convention)
359
0
    : d(std::make_unique<Private>()) {
360
0
    d->params_.convention_ = convention;
361
0
    switch (convention) {
362
0
    case Convention::WKT2_2019:
363
0
        d->params_.use2019Keywords_ = true;
364
0
        PROJ_FALLTHROUGH;
365
0
    case Convention::WKT2:
366
0
        d->params_.version_ = WKTFormatter::Version::WKT2;
367
0
        d->params_.outputAxisOrder_ = true;
368
0
        break;
369
370
0
    case Convention::WKT2_2019_SIMPLIFIED:
371
0
        d->params_.use2019Keywords_ = true;
372
0
        PROJ_FALLTHROUGH;
373
0
    case Convention::WKT2_SIMPLIFIED:
374
0
        d->params_.version_ = WKTFormatter::Version::WKT2;
375
0
        d->params_.idOnTopLevelOnly_ = true;
376
0
        d->params_.outputAxisOrder_ = false;
377
0
        d->params_.primeMeridianOmittedIfGreenwich_ = true;
378
0
        d->params_.ellipsoidUnitOmittedIfMetre_ = true;
379
0
        d->params_.primeMeridianOrParameterUnitOmittedIfSameAsAxis_ = true;
380
0
        d->params_.forceUNITKeyword_ = true;
381
0
        d->params_.outputCSUnitOnlyOnceIfSame_ = true;
382
0
        break;
383
384
0
    case Convention::WKT1_GDAL:
385
0
        d->params_.version_ = WKTFormatter::Version::WKT1;
386
0
        d->params_.outputAxisOrder_ = false;
387
0
        d->params_.forceUNITKeyword_ = true;
388
0
        d->params_.primeMeridianInDegree_ = true;
389
0
        d->params_.outputAxis_ =
390
0
            WKTFormatter::OutputAxisRule::WKT1_GDAL_EPSG_STYLE;
391
0
        break;
392
393
0
    case Convention::WKT1_ESRI:
394
0
        d->params_.version_ = WKTFormatter::Version::WKT1;
395
0
        d->params_.outputAxisOrder_ = false;
396
0
        d->params_.forceUNITKeyword_ = true;
397
0
        d->params_.primeMeridianInDegree_ = true;
398
0
        d->params_.useESRIDialect_ = true;
399
0
        d->params_.multiLine_ = false;
400
0
        d->params_.outputAxis_ = WKTFormatter::OutputAxisRule::NO;
401
0
        d->params_.allowLINUNITNode_ = true;
402
0
        break;
403
404
0
    default:
405
0
        assert(false);
406
0
        break;
407
0
    }
408
0
}
409
410
// ---------------------------------------------------------------------------
411
412
0
WKTFormatter &WKTFormatter::setOutputId(bool outputIdIn) {
413
0
    if (d->indentLevel_ != 0) {
414
0
        throw Exception(
415
0
            "setOutputId() shall only be called when the stack state is empty");
416
0
    }
417
0
    d->outputIdStack_[0] = outputIdIn;
418
0
    return *this;
419
0
}
420
421
// ---------------------------------------------------------------------------
422
423
0
void WKTFormatter::Private::addNewLine() { result_ += '\n'; }
424
425
// ---------------------------------------------------------------------------
426
427
0
void WKTFormatter::Private::addIndentation() {
428
0
    result_ += std::string(
429
0
        static_cast<size_t>(indentLevel_) * params_.indentWidth_, ' ');
430
0
}
431
432
// ---------------------------------------------------------------------------
433
434
0
void WKTFormatter::enter() {
435
0
    if (d->indentLevel_ == 0 && d->level_ == 0) {
436
0
        d->stackHasChild_.push_back(false);
437
0
    }
438
0
    ++d->level_;
439
0
}
440
441
// ---------------------------------------------------------------------------
442
443
0
void WKTFormatter::leave() {
444
0
    assert(d->level_ > 0);
445
0
    --d->level_;
446
0
    if (d->indentLevel_ == 0 && d->level_ == 0) {
447
0
        d->stackHasChild_.pop_back();
448
0
    }
449
0
}
450
451
// ---------------------------------------------------------------------------
452
453
0
bool WKTFormatter::isAtTopLevel() const {
454
0
    return d->level_ == 0 && d->indentLevel_ == 0;
455
0
}
456
457
// ---------------------------------------------------------------------------
458
459
0
void WKTFormatter::startNode(const std::string &keyword, bool hasId) {
460
0
    if (!d->stackHasChild_.empty()) {
461
0
        d->startNewChild();
462
0
    } else if (!d->result_.empty()) {
463
0
        d->result_ += ',';
464
0
        if (d->params_.multiLine_ && !keyword.empty()) {
465
0
            d->addNewLine();
466
0
        }
467
0
    }
468
469
0
    if (d->params_.multiLine_) {
470
0
        if ((d->indentLevel_ || d->level_) && !keyword.empty()) {
471
0
            if (!d->result_.empty()) {
472
0
                d->addNewLine();
473
0
            }
474
0
            d->addIndentation();
475
0
        }
476
0
    }
477
478
0
    if (!keyword.empty()) {
479
0
        d->result_ += keyword;
480
0
        d->result_ += '[';
481
0
    }
482
0
    d->indentLevel_++;
483
0
    d->stackHasChild_.push_back(false);
484
0
    d->stackEmptyKeyword_.push_back(keyword.empty());
485
486
    // Starting from a node that has a ID, we should emit ID nodes for :
487
    // - this node
488
    // - and for METHOD&PARAMETER nodes in WKT2, unless idOnTopLevelOnly_ is
489
    // set.
490
    // For WKT2, all other intermediate nodes shouldn't have ID ("not
491
    // recommended")
492
0
    if (!d->params_.idOnTopLevelOnly_ && d->indentLevel_ >= 2 &&
493
0
        d->params_.version_ == WKTFormatter::Version::WKT2 &&
494
0
        (keyword == WKTConstants::METHOD ||
495
0
         keyword == WKTConstants::PARAMETER)) {
496
0
        pushOutputId(d->outputIdStack_[0]);
497
0
    } else if (d->indentLevel_ >= 2 &&
498
0
               d->params_.version_ == WKTFormatter::Version::WKT2) {
499
0
        pushOutputId(d->outputIdStack_[0] && !d->stackHasId_.back());
500
0
    } else {
501
0
        pushOutputId(outputId());
502
0
    }
503
504
0
    d->stackHasId_.push_back(hasId || d->stackHasId_.back());
505
0
}
506
507
// ---------------------------------------------------------------------------
508
509
0
void WKTFormatter::endNode() {
510
0
    assert(d->indentLevel_ > 0);
511
0
    d->stackHasId_.pop_back();
512
0
    popOutputId();
513
0
    d->indentLevel_--;
514
0
    bool emptyKeyword = d->stackEmptyKeyword_.back();
515
0
    d->stackEmptyKeyword_.pop_back();
516
0
    d->stackHasChild_.pop_back();
517
0
    if (!emptyKeyword)
518
0
        d->result_ += ']';
519
0
}
520
521
// ---------------------------------------------------------------------------
522
523
0
WKTFormatter &WKTFormatter::simulCurNodeHasId() {
524
0
    d->stackHasId_.back() = true;
525
0
    return *this;
526
0
}
527
528
// ---------------------------------------------------------------------------
529
530
0
void WKTFormatter::Private::startNewChild() {
531
0
    assert(!stackHasChild_.empty());
532
0
    if (stackHasChild_.back()) {
533
0
        result_ += ',';
534
0
    }
535
0
    stackHasChild_.back() = true;
536
0
}
537
538
// ---------------------------------------------------------------------------
539
540
0
void WKTFormatter::addQuotedString(const char *str) {
541
0
    addQuotedString(std::string(str));
542
0
}
543
544
0
void WKTFormatter::addQuotedString(const std::string &str) {
545
0
    d->startNewChild();
546
0
    d->result_ += '"';
547
0
    d->result_ += replaceAll(str, "\"", "\"\"");
548
0
    d->result_ += '"';
549
0
}
550
551
// ---------------------------------------------------------------------------
552
553
0
void WKTFormatter::add(const std::string &str) {
554
0
    d->startNewChild();
555
0
    d->result_ += str;
556
0
}
557
558
// ---------------------------------------------------------------------------
559
560
0
void WKTFormatter::add(int number) {
561
0
    d->startNewChild();
562
0
    d->result_ += internal::toString(number);
563
0
}
564
565
// ---------------------------------------------------------------------------
566
567
#ifdef __MINGW32__
568
static std::string normalizeExponent(const std::string &in) {
569
    // mingw will output 1e-0xy instead of 1e-xy. Fix that
570
    auto pos = in.find("e-0");
571
    if (pos == std::string::npos) {
572
        return in;
573
    }
574
    if (pos + 4 < in.size() && isdigit(in[pos + 3]) && isdigit(in[pos + 4])) {
575
        return in.substr(0, pos + 2) + in.substr(pos + 3);
576
    }
577
    return in;
578
}
579
#else
580
1.00M
static inline std::string normalizeExponent(const std::string &in) {
581
1.00M
    return in;
582
1.00M
}
583
#endif
584
585
1.00M
static inline std::string normalizeSerializedString(const std::string &in) {
586
1.00M
    auto ret(normalizeExponent(in));
587
1.00M
    return ret;
588
1.00M
}
589
590
// ---------------------------------------------------------------------------
591
592
0
void WKTFormatter::add(double number, int precision) {
593
0
    d->startNewChild();
594
0
    if (number == 0.0) {
595
0
        if (d->params_.useESRIDialect_) {
596
0
            d->result_ += "0.0";
597
0
        } else {
598
0
            d->result_ += '0';
599
0
        }
600
0
    } else {
601
0
        std::string val(
602
0
            normalizeSerializedString(internal::toString(number, precision)));
603
0
        d->result_ += replaceAll(val, "e", "E");
604
0
        if (d->params_.useESRIDialect_ && val.find('.') == std::string::npos) {
605
0
            d->result_ += ".0";
606
0
        }
607
0
    }
608
0
}
609
610
// ---------------------------------------------------------------------------
611
612
0
void WKTFormatter::pushOutputUnit(bool outputUnitIn) {
613
0
    d->outputUnitStack_.push_back(outputUnitIn);
614
0
}
615
616
// ---------------------------------------------------------------------------
617
618
0
void WKTFormatter::popOutputUnit() { d->outputUnitStack_.pop_back(); }
619
620
// ---------------------------------------------------------------------------
621
622
0
bool WKTFormatter::outputUnit() const { return d->outputUnitStack_.back(); }
623
624
// ---------------------------------------------------------------------------
625
626
0
void WKTFormatter::pushOutputId(bool outputIdIn) {
627
0
    d->outputIdStack_.push_back(outputIdIn);
628
0
}
629
630
// ---------------------------------------------------------------------------
631
632
0
void WKTFormatter::popOutputId() { d->outputIdStack_.pop_back(); }
633
634
// ---------------------------------------------------------------------------
635
636
0
bool WKTFormatter::outputId() const {
637
0
    return !d->params_.useESRIDialect_ && d->outputIdStack_.back();
638
0
}
639
640
// ---------------------------------------------------------------------------
641
642
0
void WKTFormatter::pushHasId(bool hasId) { d->stackHasId_.push_back(hasId); }
643
644
// ---------------------------------------------------------------------------
645
646
0
void WKTFormatter::popHasId() { d->stackHasId_.pop_back(); }
647
648
// ---------------------------------------------------------------------------
649
650
0
void WKTFormatter::pushDisableUsage() { d->stackDisableUsage_.push_back(true); }
651
652
// ---------------------------------------------------------------------------
653
654
0
void WKTFormatter::popDisableUsage() { d->stackDisableUsage_.pop_back(); }
655
656
// ---------------------------------------------------------------------------
657
658
0
bool WKTFormatter::outputUsage() const {
659
0
    return outputId() && d->stackDisableUsage_.empty();
660
0
}
661
662
// ---------------------------------------------------------------------------
663
664
0
void WKTFormatter::pushAxisLinearUnit(const UnitOfMeasureNNPtr &unit) {
665
0
    d->axisLinearUnitStack_.push_back(unit);
666
0
}
667
// ---------------------------------------------------------------------------
668
669
0
void WKTFormatter::popAxisLinearUnit() { d->axisLinearUnitStack_.pop_back(); }
670
671
// ---------------------------------------------------------------------------
672
673
0
const UnitOfMeasureNNPtr &WKTFormatter::axisLinearUnit() const {
674
0
    return d->axisLinearUnitStack_.back();
675
0
}
676
677
// ---------------------------------------------------------------------------
678
679
0
void WKTFormatter::pushAxisAngularUnit(const UnitOfMeasureNNPtr &unit) {
680
0
    d->axisAngularUnitStack_.push_back(unit);
681
0
}
682
// ---------------------------------------------------------------------------
683
684
0
void WKTFormatter::popAxisAngularUnit() { d->axisAngularUnitStack_.pop_back(); }
685
686
// ---------------------------------------------------------------------------
687
688
0
const UnitOfMeasureNNPtr &WKTFormatter::axisAngularUnit() const {
689
0
    return d->axisAngularUnitStack_.back();
690
0
}
691
692
// ---------------------------------------------------------------------------
693
694
0
WKTFormatter::OutputAxisRule WKTFormatter::outputAxis() const {
695
0
    return d->params_.outputAxis_;
696
0
}
697
698
// ---------------------------------------------------------------------------
699
700
0
bool WKTFormatter::outputAxisOrder() const {
701
0
    return d->params_.outputAxisOrder_;
702
0
}
703
704
// ---------------------------------------------------------------------------
705
706
0
bool WKTFormatter::primeMeridianOmittedIfGreenwich() const {
707
0
    return d->params_.primeMeridianOmittedIfGreenwich_;
708
0
}
709
710
// ---------------------------------------------------------------------------
711
712
0
bool WKTFormatter::ellipsoidUnitOmittedIfMetre() const {
713
0
    return d->params_.ellipsoidUnitOmittedIfMetre_;
714
0
}
715
716
// ---------------------------------------------------------------------------
717
718
0
bool WKTFormatter::primeMeridianOrParameterUnitOmittedIfSameAsAxis() const {
719
0
    return d->params_.primeMeridianOrParameterUnitOmittedIfSameAsAxis_;
720
0
}
721
722
// ---------------------------------------------------------------------------
723
724
0
bool WKTFormatter::outputCSUnitOnlyOnceIfSame() const {
725
0
    return d->params_.outputCSUnitOnlyOnceIfSame_;
726
0
}
727
728
// ---------------------------------------------------------------------------
729
730
0
bool WKTFormatter::forceUNITKeyword() const {
731
0
    return d->params_.forceUNITKeyword_;
732
0
}
733
734
// ---------------------------------------------------------------------------
735
736
0
bool WKTFormatter::primeMeridianInDegree() const {
737
0
    return d->params_.primeMeridianInDegree_;
738
0
}
739
740
// ---------------------------------------------------------------------------
741
742
0
bool WKTFormatter::idOnTopLevelOnly() const {
743
0
    return d->params_.idOnTopLevelOnly_;
744
0
}
745
746
// ---------------------------------------------------------------------------
747
748
0
bool WKTFormatter::topLevelHasId() const {
749
0
    return d->stackHasId_.size() >= 2 && d->stackHasId_[1];
750
0
}
751
752
// ---------------------------------------------------------------------------
753
754
0
WKTFormatter::Version WKTFormatter::version() const {
755
0
    return d->params_.version_;
756
0
}
757
758
// ---------------------------------------------------------------------------
759
760
0
bool WKTFormatter::use2019Keywords() const {
761
0
    return d->params_.use2019Keywords_;
762
0
}
763
764
// ---------------------------------------------------------------------------
765
766
0
bool WKTFormatter::useESRIDialect() const { return d->params_.useESRIDialect_; }
767
768
// ---------------------------------------------------------------------------
769
770
0
const DatabaseContextPtr &WKTFormatter::databaseContext() const {
771
0
    return d->dbContext_;
772
0
}
773
774
// ---------------------------------------------------------------------------
775
776
0
void WKTFormatter::setAbridgedTransformation(bool outputIn) {
777
0
    d->abridgedTransformation_ = outputIn;
778
0
}
779
780
// ---------------------------------------------------------------------------
781
782
0
bool WKTFormatter::abridgedTransformation() const {
783
0
    return d->abridgedTransformation_;
784
0
}
785
786
// ---------------------------------------------------------------------------
787
788
0
void WKTFormatter::setUseDerivingConversion(bool useDerivingConversionIn) {
789
0
    d->useDerivingConversion_ = useDerivingConversionIn;
790
0
}
791
792
// ---------------------------------------------------------------------------
793
794
0
bool WKTFormatter::useDerivingConversion() const {
795
0
    return d->useDerivingConversion_;
796
0
}
797
798
// ---------------------------------------------------------------------------
799
800
0
void WKTFormatter::setTOWGS84Parameters(const std::vector<double> &params) {
801
0
    d->toWGS84Parameters_ = params;
802
0
}
803
804
// ---------------------------------------------------------------------------
805
806
0
const std::vector<double> &WKTFormatter::getTOWGS84Parameters() const {
807
0
    return d->toWGS84Parameters_;
808
0
}
809
810
// ---------------------------------------------------------------------------
811
812
0
void WKTFormatter::setVDatumExtension(const std::string &filename) {
813
0
    d->vDatumExtension_ = filename;
814
0
}
815
816
// ---------------------------------------------------------------------------
817
818
0
const std::string &WKTFormatter::getVDatumExtension() const {
819
0
    return d->vDatumExtension_;
820
0
}
821
822
// ---------------------------------------------------------------------------
823
824
0
void WKTFormatter::setHDatumExtension(const std::string &filename) {
825
0
    d->hDatumExtension_ = filename;
826
0
}
827
828
// ---------------------------------------------------------------------------
829
830
0
const std::string &WKTFormatter::getHDatumExtension() const {
831
0
    return d->hDatumExtension_;
832
0
}
833
834
// ---------------------------------------------------------------------------
835
836
0
void WKTFormatter::setGeogCRSOfCompoundCRS(const crs::GeographicCRSPtr &crs) {
837
0
    d->geogCRSOfCompoundCRS_ = crs;
838
0
}
839
840
// ---------------------------------------------------------------------------
841
842
0
const crs::GeographicCRSPtr &WKTFormatter::getGeogCRSOfCompoundCRS() const {
843
0
    return d->geogCRSOfCompoundCRS_;
844
0
}
845
846
// ---------------------------------------------------------------------------
847
848
0
std::string WKTFormatter::morphNameToESRI(const std::string &name) {
849
850
0
    for (const auto *suffix : {"(m)", "(ftUS)", "(E-N)", "(N-E)"}) {
851
0
        if (ends_with(name, suffix)) {
852
0
            return morphNameToESRI(
853
0
                       name.substr(0, name.size() - strlen(suffix))) +
854
0
                   suffix;
855
0
        }
856
0
    }
857
858
0
    std::string ret;
859
0
    bool insertUnderscore = false;
860
    // Replace any special character by underscore, except at the beginning
861
    // and of the name where those characters are removed.
862
0
    for (char ch : name) {
863
0
        if (ch == '+' || ch == '-' || (ch >= '0' && ch <= '9') ||
864
0
            (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
865
0
            if (insertUnderscore && !ret.empty()) {
866
0
                ret += '_';
867
0
            }
868
0
            ret += ch;
869
0
            insertUnderscore = false;
870
0
        } else {
871
0
            insertUnderscore = true;
872
0
        }
873
0
    }
874
0
    return ret;
875
0
}
876
877
// ---------------------------------------------------------------------------
878
879
0
void WKTFormatter::ingestWKTNode(const WKTNodeNNPtr &node) {
880
0
    startNode(node->value(), true);
881
0
    for (const auto &child : node->children()) {
882
0
        if (!child->children().empty()) {
883
0
            ingestWKTNode(child);
884
0
        } else {
885
0
            add(child->value());
886
0
        }
887
0
    }
888
0
    endNode();
889
0
}
890
891
//! @endcond
892
893
// ---------------------------------------------------------------------------
894
895
//! @cond Doxygen_Suppress
896
897
static WKTNodeNNPtr
898
    null_node(NN_NO_CHECK(std::make_unique<WKTNode>(std::string())));
899
900
182k
static inline bool isNull(const WKTNodeNNPtr &node) {
901
182k
    return &node == &null_node;
902
182k
}
903
904
struct WKTNode::Private {
905
    std::string value_{};
906
    std::vector<WKTNodeNNPtr> children_{};
907
908
73.4k
    explicit Private(const std::string &valueIn) : value_(valueIn) {}
909
910
    // cppcheck-suppress functionStatic
911
961k
    inline const std::string &value() PROJ_PURE_DEFN { return value_; }
912
913
    // cppcheck-suppress functionStatic
914
66.0k
    inline const std::vector<WKTNodeNNPtr> &children() PROJ_PURE_DEFN {
915
66.0k
        return children_;
916
66.0k
    }
917
918
    // cppcheck-suppress functionStatic
919
12.8k
    inline size_t childrenSize() PROJ_PURE_DEFN { return children_.size(); }
920
921
    // cppcheck-suppress functionStatic
922
    const WKTNodeNNPtr &lookForChild(const std::string &childName,
923
                                     int occurrence) const noexcept;
924
925
    // cppcheck-suppress functionStatic
926
    const WKTNodeNNPtr &lookForChild(const std::string &name) const noexcept;
927
928
    // cppcheck-suppress functionStatic
929
    const WKTNodeNNPtr &lookForChild(const std::string &name,
930
                                     const std::string &name2) const noexcept;
931
932
    // cppcheck-suppress functionStatic
933
    const WKTNodeNNPtr &lookForChild(const std::string &name,
934
                                     const std::string &name2,
935
                                     const std::string &name3) const noexcept;
936
937
    // cppcheck-suppress functionStatic
938
    const WKTNodeNNPtr &lookForChild(const std::string &name,
939
                                     const std::string &name2,
940
                                     const std::string &name3,
941
                                     const std::string &name4) const noexcept;
942
};
943
944
1.03M
#define GP() getPrivate()
945
946
// ---------------------------------------------------------------------------
947
948
const WKTNodeNNPtr &
949
WKTNode::Private::lookForChild(const std::string &childName,
950
215
                               int occurrence) const noexcept {
951
215
    int occCount = 0;
952
564
    for (const auto &child : children_) {
953
564
        if (ci_equal(child->GP()->value(), childName)) {
954
217
            if (occurrence == occCount) {
955
215
                return child;
956
215
            }
957
2
            occCount++;
958
2
        }
959
564
    }
960
0
    return null_node;
961
215
}
962
963
const WKTNodeNNPtr &
964
170k
WKTNode::Private::lookForChild(const std::string &name) const noexcept {
965
709k
    for (const auto &child : children_) {
966
709k
        const auto &v = child->GP()->value();
967
709k
        if (ci_equal(v, name)) {
968
4.43k
            return child;
969
4.43k
        }
970
709k
    }
971
166k
    return null_node;
972
170k
}
973
974
const WKTNodeNNPtr &
975
WKTNode::Private::lookForChild(const std::string &name,
976
6.09k
                               const std::string &name2) const noexcept {
977
19.6k
    for (const auto &child : children_) {
978
19.6k
        const auto &v = child->GP()->value();
979
19.6k
        if (ci_equal(v, name) || ci_equal(v, name2)) {
980
2.43k
            return child;
981
2.43k
        }
982
19.6k
    }
983
3.66k
    return null_node;
984
6.09k
}
985
986
const WKTNodeNNPtr &
987
WKTNode::Private::lookForChild(const std::string &name,
988
                               const std::string &name2,
989
2.06k
                               const std::string &name3) const noexcept {
990
4.08k
    for (const auto &child : children_) {
991
4.08k
        const auto &v = child->GP()->value();
992
4.08k
        if (ci_equal(v, name) || ci_equal(v, name2) || ci_equal(v, name3)) {
993
1.86k
            return child;
994
1.86k
        }
995
4.08k
    }
996
195
    return null_node;
997
2.06k
}
998
999
const WKTNodeNNPtr &WKTNode::Private::lookForChild(
1000
    const std::string &name, const std::string &name2, const std::string &name3,
1001
717
    const std::string &name4) const noexcept {
1002
1.59k
    for (const auto &child : children_) {
1003
1.59k
        const auto &v = child->GP()->value();
1004
1.59k
        if (ci_equal(v, name) || ci_equal(v, name2) || ci_equal(v, name3) ||
1005
1.09k
            ci_equal(v, name4)) {
1006
649
            return child;
1007
649
        }
1008
1.59k
    }
1009
68
    return null_node;
1010
717
}
1011
1012
//! @endcond
1013
1014
// ---------------------------------------------------------------------------
1015
1016
/** \brief Instantiate a WKTNode.
1017
 *
1018
 * @param valueIn the name of the node.
1019
 */
1020
WKTNode::WKTNode(const std::string &valueIn)
1021
73.4k
    : d(std::make_unique<Private>(valueIn)) {}
1022
1023
// ---------------------------------------------------------------------------
1024
1025
//! @cond Doxygen_Suppress
1026
73.4k
WKTNode::~WKTNode() = default;
1027
//! @endcond
1028
1029
// ---------------------------------------------------------------------------
1030
1031
/** \brief Adds a child to the current node.
1032
 *
1033
 * @param child child to add. This should not be a parent of this node.
1034
 */
1035
69.9k
void WKTNode::addChild(WKTNodeNNPtr &&child) {
1036
69.9k
    d->children_.push_back(std::move(child));
1037
69.9k
}
1038
1039
// ---------------------------------------------------------------------------
1040
1041
/** \brief Return the (occurrence-1)th sub-node of name childName.
1042
 *
1043
 * @param childName name of the child.
1044
 * @param occurrence occurrence index (starting at 0)
1045
 * @return the child, or nullptr.
1046
 */
1047
const WKTNodePtr &WKTNode::lookForChild(const std::string &childName,
1048
1.66k
                                        int occurrence) const noexcept {
1049
1.66k
    int occCount = 0;
1050
11.5k
    for (const auto &child : d->children_) {
1051
11.5k
        if (ci_equal(child->GP()->value(), childName)) {
1052
146
            if (occurrence == occCount) {
1053
146
                return child;
1054
146
            }
1055
0
            occCount++;
1056
0
        }
1057
11.5k
    }
1058
1.51k
    return null_node;
1059
1.66k
}
1060
1061
// ---------------------------------------------------------------------------
1062
1063
/** \brief Return the count of children of given name.
1064
 *
1065
 * @param childName name of the children to look for.
1066
 * @return count
1067
 */
1068
3.38k
int WKTNode::countChildrenOfName(const std::string &childName) const noexcept {
1069
3.38k
    int occCount = 0;
1070
19.4k
    for (const auto &child : d->children_) {
1071
19.4k
        if (ci_equal(child->GP()->value(), childName)) {
1072
236
            occCount++;
1073
236
        }
1074
19.4k
    }
1075
3.38k
    return occCount;
1076
3.38k
}
1077
1078
// ---------------------------------------------------------------------------
1079
1080
/** \brief Return the value of a node.
1081
 */
1082
0
const std::string &WKTNode::value() const { return d->value_; }
1083
1084
// ---------------------------------------------------------------------------
1085
1086
/** \brief Return the children of a node.
1087
 */
1088
0
const std::vector<WKTNodeNNPtr> &WKTNode::children() const {
1089
0
    return d->children_;
1090
0
}
1091
1092
// ---------------------------------------------------------------------------
1093
1094
//! @cond Doxygen_Suppress
1095
255k
static size_t skipSpace(const std::string &str, size_t start) {
1096
255k
    size_t i = start;
1097
258k
    while (i < str.size() && ::isspace(static_cast<unsigned char>(str[i]))) {
1098
3.48k
        ++i;
1099
3.48k
    }
1100
255k
    return i;
1101
255k
}
1102
//! @endcond
1103
1104
// ---------------------------------------------------------------------------
1105
1106
//! @cond Doxygen_Suppress
1107
// As used in examples of OGC 12-063r5
1108
static const std::string startPrintedQuote("\xE2\x80\x9C");
1109
static const std::string endPrintedQuote("\xE2\x80\x9D");
1110
//! @endcond
1111
1112
WKTNodeNNPtr WKTNode::createFrom(const std::string &wkt, size_t indexStart,
1113
73.7k
                                 int recLevel, size_t &indexEnd) {
1114
73.7k
    if (recLevel == 16) {
1115
2
        throw ParsingException("too many nesting levels");
1116
2
    }
1117
73.7k
    std::string value;
1118
73.7k
    size_t i = skipSpace(wkt, indexStart);
1119
73.7k
    if (i == wkt.size()) {
1120
0
        throw ParsingException("whitespace only string");
1121
0
    }
1122
73.7k
    std::string closingStringMarker;
1123
73.7k
    bool inString = false;
1124
1125
623k
    for (; i < wkt.size() &&
1126
623k
           (inString ||
1127
463k
            (wkt[i] != '[' && wkt[i] != '(' && wkt[i] != ',' && wkt[i] != ']' &&
1128
391k
             wkt[i] != ')' && !::isspace(static_cast<unsigned char>(wkt[i]))));
1129
549k
         ++i) {
1130
549k
        if (wkt[i] == '"') {
1131
19.3k
            if (!inString) {
1132
9.31k
                inString = true;
1133
9.31k
                closingStringMarker = "\"";
1134
10.0k
            } else if (closingStringMarker == "\"") {
1135
9.88k
                if (i + 1 < wkt.size() && wkt[i + 1] == '"') {
1136
612
                    i++;
1137
9.27k
                } else {
1138
9.27k
                    inString = false;
1139
9.27k
                    closingStringMarker.clear();
1140
9.27k
                }
1141
9.88k
            }
1142
530k
        } else if (i + 3 <= wkt.size() &&
1143
529k
                   wkt.substr(i, 3) == startPrintedQuote) {
1144
109
            if (!inString) {
1145
69
                inString = true;
1146
69
                closingStringMarker = endPrintedQuote;
1147
69
                value += '"';
1148
69
                i += 2;
1149
69
                continue;
1150
69
            }
1151
530k
        } else if (i + 3 <= wkt.size() &&
1152
529k
                   closingStringMarker == endPrintedQuote &&
1153
918
                   wkt.substr(i, 3) == endPrintedQuote) {
1154
31
            inString = false;
1155
31
            closingStringMarker.clear();
1156
31
            value += '"';
1157
31
            i += 2;
1158
31
            continue;
1159
31
        }
1160
549k
        value += wkt[i];
1161
549k
    }
1162
73.7k
    i = skipSpace(wkt, i);
1163
73.7k
    if (i == wkt.size()) {
1164
306
        if (indexStart == 0) {
1165
0
            throw ParsingException("missing [");
1166
306
        } else {
1167
306
            throw ParsingException("missing , or ]");
1168
306
        }
1169
306
    }
1170
1171
73.4k
    auto node = NN_NO_CHECK(std::make_unique<WKTNode>(value));
1172
1173
73.4k
    if (indexStart > 0) {
1174
70.5k
        if (wkt[i] == ',') {
1175
25.9k
            indexEnd = i + 1;
1176
25.9k
            return node;
1177
25.9k
        }
1178
44.5k
        if (wkt[i] == ']' || wkt[i] == ')') {
1179
21.1k
            indexEnd = i;
1180
21.1k
            return node;
1181
21.1k
        }
1182
44.5k
    }
1183
26.3k
    if (wkt[i] != '[' && wkt[i] != '(') {
1184
36
        throw ParsingException("missing [");
1185
36
    }
1186
26.2k
    ++i; // skip [
1187
26.2k
    i = skipSpace(wkt, i);
1188
96.8k
    while (i < wkt.size() && wkt[i] != ']' && wkt[i] != ')') {
1189
70.5k
        size_t indexEndChild;
1190
70.5k
        node->addChild(createFrom(wkt, i, recLevel + 1, indexEndChild));
1191
70.5k
        assert(indexEndChild > i);
1192
70.5k
        i = indexEndChild;
1193
70.5k
        i = skipSpace(wkt, i);
1194
70.5k
        if (i < wkt.size() && wkt[i] == ',') {
1195
10.2k
            ++i;
1196
10.2k
            i = skipSpace(wkt, i);
1197
10.2k
        }
1198
70.5k
    }
1199
26.2k
    if (i == wkt.size() || (wkt[i] != ']' && wkt[i] != ')')) {
1200
57
        throw ParsingException("missing ]");
1201
57
    }
1202
26.2k
    indexEnd = i + 1;
1203
26.2k
    return node;
1204
26.2k
}
1205
// ---------------------------------------------------------------------------
1206
1207
/** \brief Instantiate a WKTNode hierarchy from a WKT string.
1208
 *
1209
 * @param wkt the WKT string to parse.
1210
 * @param indexStart the start index in the wkt string.
1211
 * @throw ParsingException if the string cannot be parsed.
1212
 */
1213
0
WKTNodeNNPtr WKTNode::createFrom(const std::string &wkt, size_t indexStart) {
1214
0
    size_t indexEnd;
1215
0
    return createFrom(wkt, indexStart, 0, indexEnd);
1216
0
}
1217
1218
// ---------------------------------------------------------------------------
1219
1220
//! @cond Doxygen_Suppress
1221
0
static std::string escapeIfQuotedString(const std::string &str) {
1222
0
    if (str.size() > 2 && str[0] == '"' && str.back() == '"') {
1223
0
        std::string res("\"");
1224
0
        res += replaceAll(str.substr(1, str.size() - 2), "\"", "\"\"");
1225
0
        res += '"';
1226
0
        return res;
1227
0
    } else {
1228
0
        return str;
1229
0
    }
1230
0
}
1231
//! @endcond
1232
1233
// ---------------------------------------------------------------------------
1234
1235
/** \brief Return a WKT representation of the tree structure.
1236
 */
1237
0
std::string WKTNode::toString() const {
1238
0
    std::string str(escapeIfQuotedString(d->value_));
1239
0
    if (!d->children_.empty()) {
1240
0
        str += "[";
1241
0
        bool first = true;
1242
0
        for (auto &child : d->children_) {
1243
0
            if (!first) {
1244
0
                str += ',';
1245
0
            }
1246
0
            first = false;
1247
0
            str += child->toString();
1248
0
        }
1249
0
        str += "]";
1250
0
    }
1251
0
    return str;
1252
0
}
1253
1254
// ---------------------------------------------------------------------------
1255
1256
//! @cond Doxygen_Suppress
1257
struct WKTParser::Private {
1258
1259
    struct ci_less_struct {
1260
        bool operator()(const std::string &lhs,
1261
21.7k
                        const std::string &rhs) const noexcept {
1262
21.7k
            return ci_less(lhs, rhs);
1263
21.7k
        }
1264
    };
1265
1266
    bool strict_ = true;
1267
    bool unsetIdentifiersIfIncompatibleDef_ = true;
1268
    std::list<std::string> warningList_{};
1269
    std::list<std::string> grammarErrorList_{};
1270
    std::vector<double> toWGS84Parameters_{};
1271
    std::string datumPROJ4Grids_{};
1272
    bool esriStyle_ = false;
1273
    bool maybeEsriStyle_ = false;
1274
    DatabaseContextPtr dbContext_{};
1275
    crs::GeographicCRSPtr geogCRSOfCompoundCRS_{};
1276
1277
    static constexpr unsigned int MAX_PROPERTY_SIZE = 1024;
1278
    std::vector<std::unique_ptr<PropertyMap>> properties_{};
1279
1280
2.89k
    Private() = default;
1281
2.89k
    ~Private() = default;
1282
    Private(const Private &) = delete;
1283
    Private &operator=(const Private &) = delete;
1284
1285
    void emitRecoverableWarning(const std::string &warningMsg);
1286
    void emitGrammarError(const std::string &errorMsg);
1287
    void emitRecoverableMissingUNIT(const std::string &parentNodeName,
1288
                                    const UnitOfMeasure &fallbackUnit);
1289
1290
    BaseObjectNNPtr build(const WKTNodeNNPtr &node);
1291
1292
    IdentifierPtr buildId(const WKTNodeNNPtr &parentNode,
1293
                          const WKTNodeNNPtr &node, bool tolerant,
1294
                          bool removeInverseOf);
1295
1296
    PropertyMap &buildProperties(const WKTNodeNNPtr &node,
1297
                                 bool removeInverseOf = false,
1298
                                 bool hasName = true);
1299
1300
    ObjectDomainPtr buildObjectDomain(const WKTNodeNNPtr &node);
1301
1302
    static std::string stripQuotes(const WKTNodeNNPtr &node);
1303
1304
    static double asDouble(const WKTNodeNNPtr &node);
1305
1306
    UnitOfMeasure
1307
    buildUnit(const WKTNodeNNPtr &node,
1308
              UnitOfMeasure::Type type = UnitOfMeasure::Type::UNKNOWN);
1309
1310
    UnitOfMeasure buildUnitInSubNode(
1311
        const WKTNodeNNPtr &node,
1312
        common::UnitOfMeasure::Type type = UnitOfMeasure::Type::UNKNOWN);
1313
1314
    EllipsoidNNPtr buildEllipsoid(const WKTNodeNNPtr &node);
1315
1316
    PrimeMeridianNNPtr
1317
    buildPrimeMeridian(const WKTNodeNNPtr &node,
1318
                       const UnitOfMeasure &defaultAngularUnit);
1319
1320
    static optional<std::string> getAnchor(const WKTNodeNNPtr &node);
1321
1322
    static optional<common::Measure> getAnchorEpoch(const WKTNodeNNPtr &node);
1323
1324
    static void parseDynamic(const WKTNodeNNPtr &dynamicNode,
1325
                             double &frameReferenceEpoch,
1326
                             util::optional<std::string> &modelName);
1327
1328
    GeodeticReferenceFrameNNPtr
1329
    buildGeodeticReferenceFrame(const WKTNodeNNPtr &node,
1330
                                const PrimeMeridianNNPtr &primeMeridian,
1331
                                const WKTNodeNNPtr &dynamicNode);
1332
1333
    DatumEnsembleNNPtr buildDatumEnsemble(const WKTNodeNNPtr &node,
1334
                                          const PrimeMeridianPtr &primeMeridian,
1335
                                          bool expectEllipsoid);
1336
1337
    MeridianNNPtr buildMeridian(const WKTNodeNNPtr &node);
1338
    CoordinateSystemAxisNNPtr buildAxis(const WKTNodeNNPtr &node,
1339
                                        const UnitOfMeasure &unitIn,
1340
                                        const UnitOfMeasure::Type &unitType,
1341
                                        bool isGeocentric,
1342
                                        int expectedOrderNum);
1343
1344
    CoordinateSystemNNPtr buildCS(const WKTNodeNNPtr &node, /* maybe null */
1345
                                  const WKTNodeNNPtr &parentNode,
1346
                                  const UnitOfMeasure &defaultAngularUnit);
1347
1348
    GeodeticCRSNNPtr buildGeodeticCRS(const WKTNodeNNPtr &node,
1349
                                      bool forceGeocentricIfNoCs = false);
1350
1351
    CRSNNPtr buildDerivedGeodeticCRS(const WKTNodeNNPtr &node);
1352
1353
    static UnitOfMeasure
1354
    guessUnitForParameter(const std::string &paramName,
1355
                          const UnitOfMeasure &defaultLinearUnit,
1356
                          const UnitOfMeasure &defaultAngularUnit);
1357
1358
    void consumeParameters(const WKTNodeNNPtr &node, bool isAbridged,
1359
                           std::vector<OperationParameterNNPtr> &parameters,
1360
                           std::vector<ParameterValueNNPtr> &values,
1361
                           const UnitOfMeasure &defaultLinearUnit,
1362
                           const UnitOfMeasure &defaultAngularUnit);
1363
1364
    static std::string getExtensionProj4(const WKTNode::Private *nodeP);
1365
1366
    static void addExtensionProj4ToProp(const WKTNode::Private *nodeP,
1367
                                        PropertyMap &props);
1368
1369
    ConversionNNPtr buildConversion(const WKTNodeNNPtr &node,
1370
                                    const UnitOfMeasure &defaultLinearUnit,
1371
                                    const UnitOfMeasure &defaultAngularUnit);
1372
1373
    static bool hasWebMercPROJ4String(const WKTNodeNNPtr &projCRSNode,
1374
                                      const WKTNodeNNPtr &projectionNode);
1375
1376
    static std::string projectionGetParameter(const WKTNodeNNPtr &projCRSNode,
1377
                                              const char *paramName);
1378
1379
    ConversionNNPtr buildProjection(const GeodeticCRSNNPtr &baseGeodCRS,
1380
                                    const WKTNodeNNPtr &projCRSNode,
1381
                                    const WKTNodeNNPtr &projectionNode,
1382
                                    const UnitOfMeasure &defaultLinearUnit,
1383
                                    const UnitOfMeasure &defaultAngularUnit);
1384
1385
    ConversionNNPtr
1386
    buildProjectionStandard(const GeodeticCRSNNPtr &baseGeodCRS,
1387
                            const WKTNodeNNPtr &projCRSNode,
1388
                            const WKTNodeNNPtr &projectionNode,
1389
                            const UnitOfMeasure &defaultLinearUnit,
1390
                            const UnitOfMeasure &defaultAngularUnit);
1391
1392
    const ESRIMethodMapping *
1393
    getESRIMapping(const WKTNodeNNPtr &projCRSNode,
1394
                   const WKTNodeNNPtr &projectionNode,
1395
                   std::map<std::string, std::string, ci_less_struct>
1396
                       &mapParamNameToValue);
1397
1398
    static ConversionNNPtr
1399
    buildProjectionFromESRI(const GeodeticCRSNNPtr &baseGeodCRS,
1400
                            const WKTNodeNNPtr &projCRSNode,
1401
                            const WKTNodeNNPtr &projectionNode,
1402
                            const UnitOfMeasure &defaultLinearUnit,
1403
                            const UnitOfMeasure &defaultAngularUnit,
1404
                            const ESRIMethodMapping *esriMapping,
1405
                            std::map<std::string, std::string, ci_less_struct>
1406
                                &mapParamNameToValue);
1407
1408
    ConversionNNPtr
1409
    buildProjectionFromESRI(const GeodeticCRSNNPtr &baseGeodCRS,
1410
                            const WKTNodeNNPtr &projCRSNode,
1411
                            const WKTNodeNNPtr &projectionNode,
1412
                            const UnitOfMeasure &defaultLinearUnit,
1413
                            const UnitOfMeasure &defaultAngularUnit);
1414
1415
    ProjectedCRSNNPtr buildProjectedCRS(const WKTNodeNNPtr &node);
1416
1417
    VerticalReferenceFrameNNPtr
1418
    buildVerticalReferenceFrame(const WKTNodeNNPtr &node,
1419
                                const WKTNodeNNPtr &dynamicNode);
1420
1421
    TemporalDatumNNPtr buildTemporalDatum(const WKTNodeNNPtr &node);
1422
1423
    EngineeringDatumNNPtr buildEngineeringDatum(const WKTNodeNNPtr &node);
1424
1425
    ParametricDatumNNPtr buildParametricDatum(const WKTNodeNNPtr &node);
1426
1427
    CRSNNPtr buildVerticalCRS(const WKTNodeNNPtr &node);
1428
1429
    DerivedVerticalCRSNNPtr buildDerivedVerticalCRS(const WKTNodeNNPtr &node);
1430
1431
    CRSNNPtr buildCompoundCRS(const WKTNodeNNPtr &node);
1432
1433
    BoundCRSNNPtr buildBoundCRS(const WKTNodeNNPtr &node);
1434
1435
    TemporalCSNNPtr buildTemporalCS(const WKTNodeNNPtr &parentNode);
1436
1437
    TemporalCRSNNPtr buildTemporalCRS(const WKTNodeNNPtr &node);
1438
1439
    DerivedTemporalCRSNNPtr buildDerivedTemporalCRS(const WKTNodeNNPtr &node);
1440
1441
    EngineeringCRSNNPtr buildEngineeringCRS(const WKTNodeNNPtr &node);
1442
1443
    EngineeringCRSNNPtr
1444
    buildEngineeringCRSFromLocalCS(const WKTNodeNNPtr &node);
1445
1446
    DerivedEngineeringCRSNNPtr
1447
    buildDerivedEngineeringCRS(const WKTNodeNNPtr &node);
1448
1449
    ParametricCSNNPtr buildParametricCS(const WKTNodeNNPtr &parentNode);
1450
1451
    ParametricCRSNNPtr buildParametricCRS(const WKTNodeNNPtr &node);
1452
1453
    DerivedParametricCRSNNPtr
1454
    buildDerivedParametricCRS(const WKTNodeNNPtr &node);
1455
1456
    DerivedProjectedCRSNNPtr buildDerivedProjectedCRS(const WKTNodeNNPtr &node);
1457
1458
    CRSPtr buildCRS(const WKTNodeNNPtr &node);
1459
1460
    TransformationNNPtr buildCoordinateOperation(const WKTNodeNNPtr &node);
1461
1462
    PointMotionOperationNNPtr
1463
    buildPointMotionOperation(const WKTNodeNNPtr &node);
1464
1465
    ConcatenatedOperationNNPtr
1466
    buildConcatenatedOperation(const WKTNodeNNPtr &node);
1467
1468
    CoordinateMetadataNNPtr buildCoordinateMetadata(const WKTNodeNNPtr &node);
1469
};
1470
//! @endcond
1471
1472
// ---------------------------------------------------------------------------
1473
1474
2.89k
WKTParser::WKTParser() : d(std::make_unique<Private>()) {}
1475
1476
// ---------------------------------------------------------------------------
1477
1478
//! @cond Doxygen_Suppress
1479
2.89k
WKTParser::~WKTParser() = default;
1480
//! @endcond
1481
1482
// ---------------------------------------------------------------------------
1483
1484
/** \brief Set whether parsing should be done in strict mode.
1485
 */
1486
2.89k
WKTParser &WKTParser::setStrict(bool strict) {
1487
2.89k
    d->strict_ = strict;
1488
2.89k
    return *this;
1489
2.89k
}
1490
1491
// ---------------------------------------------------------------------------
1492
1493
/** \brief Set whether object identifiers should be unset when there is
1494
 *         a contradiction between the definition from WKT and the one from
1495
 *         the database.
1496
 *
1497
 * At time of writing, this only applies to the base geographic CRS of a
1498
 * projected CRS, when comparing its coordinate system.
1499
 */
1500
0
WKTParser &WKTParser::setUnsetIdentifiersIfIncompatibleDef(bool unset) {
1501
0
    d->unsetIdentifiersIfIncompatibleDef_ = unset;
1502
0
    return *this;
1503
0
}
1504
1505
// ---------------------------------------------------------------------------
1506
1507
/** \brief Return the list of warnings found during parsing.
1508
 *
1509
 * \note The list might be non-empty only is setStrict(false) has been called.
1510
 */
1511
0
std::list<std::string> WKTParser::warningList() const {
1512
0
    return d->warningList_;
1513
0
}
1514
1515
// ---------------------------------------------------------------------------
1516
1517
/** \brief Return the list of grammar errors found during parsing.
1518
 *
1519
 * Grammar errors are non-compliance issues with respect to the WKT grammar.
1520
 *
1521
 * \note The list might be non-empty only is setStrict(false) has been called.
1522
 *
1523
 * @since PROJ 9.5
1524
 */
1525
0
std::list<std::string> WKTParser::grammarErrorList() const {
1526
0
    return d->grammarErrorList_;
1527
0
}
1528
1529
// ---------------------------------------------------------------------------
1530
1531
//! @cond Doxygen_Suppress
1532
2.58k
void WKTParser::Private::emitRecoverableWarning(const std::string &errorMsg) {
1533
2.58k
    if (strict_) {
1534
0
        throw ParsingException(errorMsg);
1535
2.58k
    } else {
1536
2.58k
        warningList_.push_back(errorMsg);
1537
2.58k
    }
1538
2.58k
}
1539
//! @endcond
1540
1541
// ---------------------------------------------------------------------------
1542
1543
//! @cond Doxygen_Suppress
1544
1.01k
void WKTParser::Private::emitGrammarError(const std::string &errorMsg) {
1545
1.01k
    if (strict_) {
1546
0
        throw ParsingException(errorMsg);
1547
1.01k
    } else {
1548
1.01k
        grammarErrorList_.push_back(errorMsg);
1549
1.01k
    }
1550
1.01k
}
1551
//! @endcond
1552
1553
// ---------------------------------------------------------------------------
1554
1555
11.6k
static double asDouble(const std::string &val) { return c_locale_stod(val); }
1556
1557
// ---------------------------------------------------------------------------
1558
1559
148
PROJ_NO_RETURN static void ThrowNotEnoughChildren(const std::string &nodeName) {
1560
148
    throw ParsingException(
1561
148
        concat("not enough children in ", nodeName, " node"));
1562
148
}
1563
1564
// ---------------------------------------------------------------------------
1565
1566
PROJ_NO_RETURN static void
1567
27
ThrowNotRequiredNumberOfChildren(const std::string &nodeName) {
1568
27
    throw ParsingException(
1569
27
        concat("not required number of children in ", nodeName, " node"));
1570
27
}
1571
1572
// ---------------------------------------------------------------------------
1573
1574
306
PROJ_NO_RETURN static void ThrowMissing(const std::string &nodeName) {
1575
306
    throw ParsingException(concat("missing ", nodeName, " node"));
1576
306
}
1577
1578
// ---------------------------------------------------------------------------
1579
1580
PROJ_NO_RETURN static void
1581
0
ThrowNotExpectedCSType(const std::string &expectedCSType) {
1582
0
    throw ParsingException(concat("CS node is not of type ", expectedCSType));
1583
0
}
1584
1585
// ---------------------------------------------------------------------------
1586
1587
static ParsingException buildRethrow(const char *funcName,
1588
75
                                     const std::exception &e) {
1589
75
    std::string res(funcName);
1590
75
    res += ": ";
1591
75
    res += e.what();
1592
75
    return ParsingException(res);
1593
75
}
1594
1595
// ---------------------------------------------------------------------------
1596
1597
//! @cond Doxygen_Suppress
1598
31.2k
std::string WKTParser::Private::stripQuotes(const WKTNodeNNPtr &node) {
1599
31.2k
    return ::stripQuotes(node->GP()->value());
1600
31.2k
}
1601
1602
// ---------------------------------------------------------------------------
1603
1604
9.15k
double WKTParser::Private::asDouble(const WKTNodeNNPtr &node) {
1605
9.15k
    return io::asDouble(node->GP()->value());
1606
9.15k
}
1607
1608
// ---------------------------------------------------------------------------
1609
1610
IdentifierPtr WKTParser::Private::buildId(const WKTNodeNNPtr &parentNode,
1611
                                          const WKTNodeNNPtr &node,
1612
2.41k
                                          bool tolerant, bool removeInverseOf) {
1613
2.41k
    const auto *nodeP = node->GP();
1614
2.41k
    const auto &nodeChildren = nodeP->children();
1615
2.41k
    if (nodeChildren.size() >= 2) {
1616
2.08k
        auto codeSpace = stripQuotes(nodeChildren[0]);
1617
2.08k
        if (removeInverseOf && starts_with(codeSpace, "INVERSE(") &&
1618
57
            codeSpace.back() == ')') {
1619
53
            codeSpace = codeSpace.substr(strlen("INVERSE("));
1620
53
            codeSpace.resize(codeSpace.size() - 1);
1621
53
        }
1622
1623
2.08k
        PropertyMap propertiesId;
1624
2.08k
        if (nodeChildren.size() >= 3 &&
1625
1.08k
            nodeChildren[2]->GP()->childrenSize() == 0) {
1626
827
            std::string version = stripQuotes(nodeChildren[2]);
1627
1628
            // IAU + 2015 -> IAU_2015
1629
827
            if (dbContext_) {
1630
641
                std::string codeSpaceOut;
1631
641
                if (dbContext_->getVersionedAuthority(codeSpace, version,
1632
641
                                                      codeSpaceOut)) {
1633
0
                    codeSpace = std::move(codeSpaceOut);
1634
0
                    version.clear();
1635
0
                }
1636
641
            }
1637
1638
827
            if (!version.empty()) {
1639
799
                propertiesId.set(Identifier::VERSION_KEY, version);
1640
799
            }
1641
827
        }
1642
1643
2.08k
        auto code = stripQuotes(nodeChildren[1]);
1644
1645
        // Prior to PROJ 9.5, when synthetizing an ID for a CONVERSION UTM Zone
1646
        // south, we generated a wrong value. Auto-fix that
1647
2.08k
        const auto &parentNodeKeyword(parentNode->GP()->value());
1648
2.08k
        if (parentNodeKeyword == WKTConstants::CONVERSION &&
1649
233
            codeSpace == Identifier::EPSG) {
1650
21
            const auto &parentNodeChildren = parentNode->GP()->children();
1651
21
            if (!parentNodeChildren.empty()) {
1652
21
                const auto parentNodeName(stripQuotes(parentNodeChildren[0]));
1653
21
                if (ci_starts_with(parentNodeName, "UTM Zone ") &&
1654
0
                    parentNodeName.find('S') != std::string::npos) {
1655
0
                    const int nZone =
1656
0
                        atoi(parentNodeName.c_str() + strlen("UTM Zone "));
1657
0
                    if (nZone >= 1 && nZone <= 60) {
1658
0
                        code = internal::toString(16100 + nZone);
1659
0
                    }
1660
0
                }
1661
21
            }
1662
21
        }
1663
1664
2.08k
        auto &citationNode = nodeP->lookForChild(WKTConstants::CITATION);
1665
2.08k
        auto &uriNode = nodeP->lookForChild(WKTConstants::URI);
1666
1667
2.08k
        propertiesId.set(Identifier::CODESPACE_KEY, codeSpace);
1668
2.08k
        bool authoritySet = false;
1669
2.08k
        /*if (!isNull(citationNode))*/ {
1670
2.08k
            const auto *citationNodeP = citationNode->GP();
1671
2.08k
            if (citationNodeP->childrenSize() == 1) {
1672
4
                authoritySet = true;
1673
4
                propertiesId.set(Identifier::AUTHORITY_KEY,
1674
4
                                 stripQuotes(citationNodeP->children()[0]));
1675
4
            }
1676
2.08k
        }
1677
2.08k
        if (!authoritySet) {
1678
2.07k
            propertiesId.set(Identifier::AUTHORITY_KEY, codeSpace);
1679
2.07k
        }
1680
2.08k
        /*if (!isNull(uriNode))*/ {
1681
2.08k
            const auto *uriNodeP = uriNode->GP();
1682
2.08k
            if (uriNodeP->childrenSize() == 1) {
1683
14
                propertiesId.set(Identifier::URI_KEY,
1684
14
                                 stripQuotes(uriNodeP->children()[0]));
1685
14
            }
1686
2.08k
        }
1687
2.08k
        return Identifier::create(code, propertiesId);
1688
2.08k
    } else if (strict_ || !tolerant) {
1689
4
        ThrowNotEnoughChildren(nodeP->value());
1690
332
    } else {
1691
332
        std::string msg("not enough children in ");
1692
332
        msg += nodeP->value();
1693
332
        msg += " node";
1694
332
        warningList_.emplace_back(std::move(msg));
1695
332
    }
1696
332
    return nullptr;
1697
2.41k
}
1698
1699
// ---------------------------------------------------------------------------
1700
1701
PropertyMap &WKTParser::Private::buildProperties(const WKTNodeNNPtr &node,
1702
                                                 bool removeInverseOf,
1703
12.7k
                                                 bool hasName) {
1704
1705
12.7k
    if (properties_.size() >= MAX_PROPERTY_SIZE) {
1706
0
        throw ParsingException("MAX_PROPERTY_SIZE reached");
1707
0
    }
1708
12.7k
    properties_.push_back(std::make_unique<PropertyMap>());
1709
12.7k
    auto properties = properties_.back().get();
1710
1711
12.7k
    std::string authNameFromAlias;
1712
12.7k
    std::string codeFromAlias;
1713
12.7k
    const auto *nodeP = node->GP();
1714
12.7k
    const auto &nodeChildren = nodeP->children();
1715
1716
12.7k
    auto identifiers = ArrayOfBaseObject::create();
1717
47.8k
    for (const auto &subNode : nodeChildren) {
1718
47.8k
        const auto &subNodeName(subNode->GP()->value());
1719
47.8k
        if (ci_equal(subNodeName, WKTConstants::ID) ||
1720
45.5k
            ci_equal(subNodeName, WKTConstants::AUTHORITY)) {
1721
2.38k
            auto id = buildId(node, subNode, true, removeInverseOf);
1722
2.38k
            if (id) {
1723
2.05k
                identifiers->add(NN_NO_CHECK(id));
1724
2.05k
            }
1725
2.38k
        }
1726
47.8k
    }
1727
1728
12.7k
    if (hasName && !nodeChildren.empty()) {
1729
11.9k
        const auto &nodeName(nodeP->value());
1730
11.9k
        auto name(stripQuotes(nodeChildren[0]));
1731
11.9k
        if (removeInverseOf && starts_with(name, "Inverse of ")) {
1732
100
            name = name.substr(strlen("Inverse of "));
1733
100
        }
1734
1735
11.9k
        if (ends_with(name, " (deprecated)")) {
1736
1
            name.resize(name.size() - strlen(" (deprecated)"));
1737
1
            properties->set(common::IdentifiedObject::DEPRECATED_KEY, true);
1738
1
        }
1739
1740
        // Oracle WKT can contain names like
1741
        // "Reseau Geodesique Francais 1993 (EPSG ID 6171)"
1742
        // for WKT attributes to the auth_name = "IGN - Paris"
1743
        // Strip that suffix from the name and assign a true EPSG code to the
1744
        // object
1745
11.9k
        if (identifiers->empty()) {
1746
11.3k
            const auto pos = name.find(" (EPSG ID ");
1747
11.3k
            if (pos != std::string::npos && name.back() == ')') {
1748
154
                const auto code =
1749
154
                    name.substr(pos + strlen(" (EPSG ID "),
1750
154
                                name.size() - 1 - pos - strlen(" (EPSG ID "));
1751
154
                name.resize(pos);
1752
1753
154
                PropertyMap propertiesId;
1754
154
                propertiesId.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
1755
154
                propertiesId.set(Identifier::AUTHORITY_KEY, Identifier::EPSG);
1756
154
                identifiers->add(Identifier::create(code, propertiesId));
1757
154
            }
1758
11.3k
        }
1759
1760
11.9k
        const char *tableNameForAlias = nullptr;
1761
11.9k
        if (ci_equal(nodeName, WKTConstants::GEOGCS)) {
1762
1.22k
            if (starts_with(name, "GCS_")) {
1763
320
                esriStyle_ = true;
1764
320
                if (name == "GCS_WGS_1984") {
1765
149
                    name = "WGS 84";
1766
171
                } else if (name == "GCS_unknown") {
1767
0
                    name = "unknown";
1768
171
                } else {
1769
171
                    tableNameForAlias = "geodetic_crs";
1770
171
                }
1771
320
            }
1772
10.7k
        } else if (esriStyle_ && ci_equal(nodeName, WKTConstants::SPHEROID)) {
1773
349
            if (name == "WGS_1984") {
1774
149
                name = "WGS 84";
1775
149
                authNameFromAlias = Identifier::EPSG;
1776
149
                codeFromAlias = "7030";
1777
200
            } else {
1778
200
                tableNameForAlias = "ellipsoid";
1779
200
            }
1780
349
        }
1781
1782
11.9k
        if (dbContext_ && tableNameForAlias) {
1783
344
            std::string outTableName;
1784
344
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
1785
344
                                                        std::string());
1786
344
            auto officialName = authFactory->getOfficialNameFromAlias(
1787
344
                name, tableNameForAlias, "ESRI", false, outTableName,
1788
344
                authNameFromAlias, codeFromAlias);
1789
344
            if (!officialName.empty()) {
1790
156
                name = std::move(officialName);
1791
1792
                // Clearing authority for geodetic_crs because of
1793
                // potential axis order mismatch.
1794
156
                if (strcmp(tableNameForAlias, "geodetic_crs") == 0) {
1795
125
                    authNameFromAlias.clear();
1796
125
                    codeFromAlias.clear();
1797
125
                }
1798
156
            }
1799
344
        }
1800
1801
11.9k
        properties->set(IdentifiedObject::NAME_KEY, name);
1802
11.9k
    }
1803
1804
12.7k
    if (identifiers->empty() && !authNameFromAlias.empty()) {
1805
180
        identifiers->add(Identifier::create(
1806
180
            codeFromAlias,
1807
180
            PropertyMap()
1808
180
                .set(Identifier::CODESPACE_KEY, authNameFromAlias)
1809
180
                .set(Identifier::AUTHORITY_KEY, authNameFromAlias)));
1810
180
    }
1811
12.7k
    if (!identifiers->empty()) {
1812
961
        properties->set(IdentifiedObject::IDENTIFIERS_KEY, identifiers);
1813
961
    }
1814
1815
12.7k
    auto &remarkNode = nodeP->lookForChild(WKTConstants::REMARK);
1816
12.7k
    if (!isNull(remarkNode)) {
1817
50
        const auto &remarkChildren = remarkNode->GP()->children();
1818
50
        if (remarkChildren.size() == 1) {
1819
46
            properties->set(IdentifiedObject::REMARKS_KEY,
1820
46
                            stripQuotes(remarkChildren[0]));
1821
46
        } else {
1822
4
            ThrowNotRequiredNumberOfChildren(remarkNode->GP()->value());
1823
4
        }
1824
50
    }
1825
1826
12.7k
    ArrayOfBaseObjectNNPtr array = ArrayOfBaseObject::create();
1827
47.7k
    for (const auto &subNode : nodeP->children()) {
1828
47.7k
        const auto &subNodeName(subNode->GP()->value());
1829
47.7k
        if (ci_equal(subNodeName, WKTConstants::USAGE)) {
1830
103
            auto objectDomain = buildObjectDomain(subNode);
1831
103
            if (!objectDomain) {
1832
3
                throw ParsingException(
1833
3
                    concat("missing children in ", subNodeName, " node"));
1834
3
            }
1835
100
            array->add(NN_NO_CHECK(objectDomain));
1836
100
        }
1837
47.7k
    }
1838
12.7k
    if (!array->empty()) {
1839
31
        properties->set(ObjectUsage::OBJECT_DOMAIN_KEY, array);
1840
12.7k
    } else {
1841
12.7k
        auto objectDomain = buildObjectDomain(node);
1842
12.7k
        if (objectDomain) {
1843
282
            properties->set(ObjectUsage::OBJECT_DOMAIN_KEY,
1844
282
                            NN_NO_CHECK(objectDomain));
1845
282
        }
1846
12.7k
    }
1847
1848
12.7k
    auto &versionNode = nodeP->lookForChild(WKTConstants::VERSION);
1849
12.7k
    if (!isNull(versionNode)) {
1850
18
        const auto &versionChildren = versionNode->GP()->children();
1851
18
        if (versionChildren.size() == 1) {
1852
15
            properties->set(CoordinateOperation::OPERATION_VERSION_KEY,
1853
15
                            stripQuotes(versionChildren[0]));
1854
15
        } else {
1855
3
            ThrowNotRequiredNumberOfChildren(versionNode->GP()->value());
1856
3
        }
1857
18
    }
1858
1859
12.7k
    return *properties;
1860
12.7k
}
1861
1862
// ---------------------------------------------------------------------------
1863
1864
ObjectDomainPtr
1865
12.8k
WKTParser::Private::buildObjectDomain(const WKTNodeNNPtr &node) {
1866
1867
12.8k
    const auto *nodeP = node->GP();
1868
12.8k
    auto &scopeNode = nodeP->lookForChild(WKTConstants::SCOPE);
1869
12.8k
    auto &areaNode = nodeP->lookForChild(WKTConstants::AREA);
1870
12.8k
    auto &bboxNode = nodeP->lookForChild(WKTConstants::BBOX);
1871
12.8k
    auto &verticalExtentNode =
1872
12.8k
        nodeP->lookForChild(WKTConstants::VERTICALEXTENT);
1873
12.8k
    auto &temporalExtentNode = nodeP->lookForChild(WKTConstants::TIMEEXTENT);
1874
12.8k
    if (!isNull(scopeNode) || !isNull(areaNode) || !isNull(bboxNode) ||
1875
12.4k
        !isNull(verticalExtentNode) || !isNull(temporalExtentNode)) {
1876
413
        optional<std::string> scope;
1877
413
        const auto *scopeNodeP = scopeNode->GP();
1878
413
        const auto &scopeChildren = scopeNodeP->children();
1879
413
        if (scopeChildren.size() == 1) {
1880
0
            scope = stripQuotes(scopeChildren[0]);
1881
0
        }
1882
413
        ExtentPtr extent;
1883
413
        if (!isNull(areaNode) || !isNull(bboxNode)) {
1884
377
            util::optional<std::string> description;
1885
377
            std::vector<GeographicExtentNNPtr> geogExtent;
1886
377
            std::vector<VerticalExtentNNPtr> verticalExtent;
1887
377
            std::vector<TemporalExtentNNPtr> temporalExtent;
1888
377
            if (!isNull(areaNode)) {
1889
100
                const auto &areaChildren = areaNode->GP()->children();
1890
100
                if (areaChildren.size() == 1) {
1891
100
                    description = stripQuotes(areaChildren[0]);
1892
100
                } else {
1893
0
                    ThrowNotRequiredNumberOfChildren(areaNode->GP()->value());
1894
0
                }
1895
100
            }
1896
377
            if (!isNull(bboxNode)) {
1897
277
                const auto &bboxChildren = bboxNode->GP()->children();
1898
277
                if (bboxChildren.size() == 4) {
1899
263
                    double south, west, north, east;
1900
263
                    try {
1901
263
                        south = asDouble(bboxChildren[0]);
1902
263
                        west = asDouble(bboxChildren[1]);
1903
263
                        north = asDouble(bboxChildren[2]);
1904
263
                        east = asDouble(bboxChildren[3]);
1905
263
                    } catch (const std::exception &) {
1906
3
                        throw ParsingException(concat("not 4 double values in ",
1907
3
                                                      bboxNode->GP()->value(),
1908
3
                                                      " node"));
1909
3
                    }
1910
260
                    try {
1911
260
                        auto bbox = GeographicBoundingBox::create(west, south,
1912
260
                                                                  east, north);
1913
260
                        geogExtent.emplace_back(bbox);
1914
260
                    } catch (const std::exception &e) {
1915
4
                        throw ParsingException(concat("Invalid ",
1916
4
                                                      bboxNode->GP()->value(),
1917
4
                                                      " node: ") +
1918
4
                                               e.what());
1919
4
                    }
1920
260
                } else {
1921
14
                    ThrowNotRequiredNumberOfChildren(bboxNode->GP()->value());
1922
14
                }
1923
277
            }
1924
1925
356
            if (!isNull(verticalExtentNode)) {
1926
21
                const auto &verticalExtentChildren =
1927
21
                    verticalExtentNode->GP()->children();
1928
21
                const auto verticalExtentChildrenSize =
1929
21
                    verticalExtentChildren.size();
1930
21
                if (verticalExtentChildrenSize == 2 ||
1931
19
                    verticalExtentChildrenSize == 3) {
1932
19
                    double min;
1933
19
                    double max;
1934
19
                    try {
1935
19
                        min = asDouble(verticalExtentChildren[0]);
1936
19
                        max = asDouble(verticalExtentChildren[1]);
1937
19
                    } catch (const std::exception &) {
1938
3
                        throw ParsingException(
1939
3
                            concat("not 2 double values in ",
1940
3
                                   verticalExtentNode->GP()->value(), " node"));
1941
3
                    }
1942
16
                    UnitOfMeasure unit = UnitOfMeasure::METRE;
1943
16
                    if (verticalExtentChildrenSize == 3) {
1944
1
                        unit = buildUnit(verticalExtentChildren[2],
1945
1
                                         UnitOfMeasure::Type::LINEAR);
1946
1
                    }
1947
16
                    verticalExtent.emplace_back(VerticalExtent::create(
1948
16
                        min, max, util::nn_make_shared<UnitOfMeasure>(unit)));
1949
16
                } else {
1950
2
                    ThrowNotRequiredNumberOfChildren(
1951
2
                        verticalExtentNode->GP()->value());
1952
2
                }
1953
21
            }
1954
1955
351
            if (!isNull(temporalExtentNode)) {
1956
80
                const auto &temporalExtentChildren =
1957
80
                    temporalExtentNode->GP()->children();
1958
80
                if (temporalExtentChildren.size() == 2) {
1959
76
                    temporalExtent.emplace_back(TemporalExtent::create(
1960
76
                        stripQuotes(temporalExtentChildren[0]),
1961
76
                        stripQuotes(temporalExtentChildren[1])));
1962
76
                } else {
1963
4
                    ThrowNotRequiredNumberOfChildren(
1964
4
                        temporalExtentNode->GP()->value());
1965
4
                }
1966
80
            }
1967
347
            extent = Extent::create(description, geogExtent, verticalExtent,
1968
347
                                    temporalExtent)
1969
347
                         .as_nullable();
1970
347
        }
1971
383
        return ObjectDomain::create(scope, extent).as_nullable();
1972
413
    }
1973
1974
12.4k
    return nullptr;
1975
12.8k
}
1976
1977
// ---------------------------------------------------------------------------
1978
1979
UnitOfMeasure WKTParser::Private::buildUnit(const WKTNodeNNPtr &node,
1980
2.39k
                                            UnitOfMeasure::Type type) {
1981
2.39k
    const auto *nodeP = node->GP();
1982
2.39k
    const auto &children = nodeP->children();
1983
2.39k
    if ((type != UnitOfMeasure::Type::TIME && children.size() < 2) ||
1984
2.38k
        (type == UnitOfMeasure::Type::TIME && children.size() < 1)) {
1985
19
        ThrowNotEnoughChildren(nodeP->value());
1986
19
    }
1987
2.37k
    try {
1988
2.37k
        std::string unitName(stripQuotes(children[0]));
1989
2.37k
        PropertyMap properties(buildProperties(node));
1990
2.37k
        auto &idNode =
1991
2.37k
            nodeP->lookForChild(WKTConstants::ID, WKTConstants::AUTHORITY);
1992
2.37k
        if (!isNull(idNode) && idNode->GP()->childrenSize() < 2) {
1993
121
            emitRecoverableWarning("not enough children in " +
1994
121
                                   idNode->GP()->value() + " node");
1995
121
        }
1996
2.37k
        const bool hasValidIdNode =
1997
2.37k
            !isNull(idNode) && idNode->GP()->childrenSize() >= 2;
1998
1999
2.37k
        const auto &idNodeChildren(idNode->GP()->children());
2000
2.37k
        std::string codeSpace(hasValidIdNode ? stripQuotes(idNodeChildren[0])
2001
2.37k
                                             : std::string());
2002
2.37k
        std::string code(hasValidIdNode ? stripQuotes(idNodeChildren[1])
2003
2.37k
                                        : std::string());
2004
2005
2.37k
        bool queryDb = true;
2006
2.37k
        if (type == UnitOfMeasure::Type::UNKNOWN) {
2007
29
            if (ci_equal(unitName, "METER") || ci_equal(unitName, "METRE")) {
2008
0
                type = UnitOfMeasure::Type::LINEAR;
2009
0
                unitName = "metre";
2010
0
                if (codeSpace.empty()) {
2011
0
                    codeSpace = Identifier::EPSG;
2012
0
                    code = "9001";
2013
0
                    queryDb = false;
2014
0
                }
2015
29
            } else if (ci_equal(unitName, "DEGREE") ||
2016
29
                       ci_equal(unitName, "GRAD")) {
2017
0
                type = UnitOfMeasure::Type::ANGULAR;
2018
0
            }
2019
29
        }
2020
2021
2.37k
        if (esriStyle_ && dbContext_ && queryDb) {
2022
1.21k
            std::string outTableName;
2023
1.21k
            std::string authNameFromAlias;
2024
1.21k
            std::string codeFromAlias;
2025
1.21k
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
2026
1.21k
                                                        std::string());
2027
1.21k
            auto officialName = authFactory->getOfficialNameFromAlias(
2028
1.21k
                unitName, "unit_of_measure", "ESRI", false, outTableName,
2029
1.21k
                authNameFromAlias, codeFromAlias);
2030
1.21k
            if (!officialName.empty()) {
2031
590
                unitName = std::move(officialName);
2032
590
                codeSpace = std::move(authNameFromAlias);
2033
590
                code = std::move(codeFromAlias);
2034
590
            }
2035
1.21k
        }
2036
2037
2.37k
        double convFactor = children.size() >= 2 ? asDouble(children[1]) : 0.0;
2038
2.37k
        constexpr double US_FOOT_CONV_FACTOR = 12.0 / 39.37;
2039
2.37k
        constexpr double REL_ERROR = 1e-10;
2040
        // Fix common rounding errors
2041
2.37k
        if (std::fabs(convFactor - UnitOfMeasure::DEGREE.conversionToSI()) <
2042
2.37k
            REL_ERROR * convFactor) {
2043
628
            convFactor = UnitOfMeasure::DEGREE.conversionToSI();
2044
1.75k
        } else if (std::fabs(convFactor - US_FOOT_CONV_FACTOR) <
2045
1.75k
                   REL_ERROR * convFactor) {
2046
4
            convFactor = US_FOOT_CONV_FACTOR;
2047
4
        }
2048
2049
2.37k
        return UnitOfMeasure(unitName, convFactor, type, codeSpace, code);
2050
2.37k
    } catch (const std::exception &e) {
2051
16
        throw buildRethrow(__FUNCTION__, e);
2052
16
    }
2053
2.37k
}
2054
2055
// ---------------------------------------------------------------------------
2056
2057
// node here is a parent node, not a UNIT/LENGTHUNIT/ANGLEUNIT/TIMEUNIT/... node
2058
UnitOfMeasure WKTParser::Private::buildUnitInSubNode(const WKTNodeNNPtr &node,
2059
7.66k
                                                     UnitOfMeasure::Type type) {
2060
7.66k
    const auto *nodeP = node->GP();
2061
7.66k
    {
2062
7.66k
        auto &unitNode = nodeP->lookForChild(WKTConstants::LENGTHUNIT);
2063
7.66k
        if (!isNull(unitNode)) {
2064
3
            return buildUnit(unitNode, UnitOfMeasure::Type::LINEAR);
2065
3
        }
2066
7.66k
    }
2067
2068
7.65k
    {
2069
7.65k
        auto &unitNode = nodeP->lookForChild(WKTConstants::ANGLEUNIT);
2070
7.65k
        if (!isNull(unitNode)) {
2071
6
            return buildUnit(unitNode, UnitOfMeasure::Type::ANGULAR);
2072
6
        }
2073
7.65k
    }
2074
2075
7.65k
    {
2076
7.65k
        auto &unitNode = nodeP->lookForChild(WKTConstants::SCALEUNIT);
2077
7.65k
        if (!isNull(unitNode)) {
2078
5
            return buildUnit(unitNode, UnitOfMeasure::Type::SCALE);
2079
5
        }
2080
7.65k
    }
2081
2082
7.64k
    {
2083
7.64k
        auto &unitNode = nodeP->lookForChild(WKTConstants::TIMEUNIT);
2084
7.64k
        if (!isNull(unitNode)) {
2085
1
            return buildUnit(unitNode, UnitOfMeasure::Type::TIME);
2086
1
        }
2087
7.64k
    }
2088
7.64k
    {
2089
7.64k
        auto &unitNode = nodeP->lookForChild(WKTConstants::TEMPORALQUANTITY);
2090
7.64k
        if (!isNull(unitNode)) {
2091
8
            return buildUnit(unitNode, UnitOfMeasure::Type::TIME);
2092
8
        }
2093
7.64k
    }
2094
2095
7.63k
    {
2096
7.63k
        auto &unitNode = nodeP->lookForChild(WKTConstants::PARAMETRICUNIT);
2097
7.63k
        if (!isNull(unitNode)) {
2098
2
            return buildUnit(unitNode, UnitOfMeasure::Type::PARAMETRIC);
2099
2
        }
2100
7.63k
    }
2101
2102
7.63k
    {
2103
7.63k
        auto &unitNode = nodeP->lookForChild(WKTConstants::UNIT);
2104
7.63k
        if (!isNull(unitNode)) {
2105
2.37k
            return buildUnit(unitNode, type);
2106
2.37k
        }
2107
7.63k
    }
2108
2109
5.26k
    return UnitOfMeasure::NONE;
2110
7.63k
}
2111
2112
// ---------------------------------------------------------------------------
2113
2114
2.10k
EllipsoidNNPtr WKTParser::Private::buildEllipsoid(const WKTNodeNNPtr &node) {
2115
2.10k
    const auto *nodeP = node->GP();
2116
2.10k
    const auto &children = nodeP->children();
2117
2.10k
    if (children.size() < 3) {
2118
7
        ThrowNotEnoughChildren(nodeP->value());
2119
7
    }
2120
2.09k
    try {
2121
2.09k
        UnitOfMeasure unit =
2122
2.09k
            buildUnitInSubNode(node, UnitOfMeasure::Type::LINEAR);
2123
2.09k
        if (unit == UnitOfMeasure::NONE) {
2124
1.51k
            unit = UnitOfMeasure::METRE;
2125
1.51k
        }
2126
2.09k
        Length semiMajorAxis(asDouble(children[1]), unit);
2127
        // Some WKT in the wild use "inf". Cf SPHEROID["unnamed",6370997,"inf"]
2128
        // in https://zenodo.org/record/3878979#.Y_P4g4CZNH4,
2129
        // https://zenodo.org/record/5831940#.Y_P4i4CZNH5
2130
        // or https://grasswiki.osgeo.org/wiki/Marine_Science
2131
2.09k
        const auto &invFlatteningChild = children[2];
2132
2.09k
        if (invFlatteningChild->GP()->value() == "\"inf\"") {
2133
0
            emitRecoverableWarning("Inverse flattening = \"inf\" is not "
2134
0
                                   "conformant, but understood");
2135
0
        }
2136
2.09k
        Scale invFlattening(invFlatteningChild->GP()->value() == "\"inf\""
2137
2.09k
                                ? 0
2138
2.09k
                                : asDouble(invFlatteningChild));
2139
2.09k
        const auto ellpsProperties = buildProperties(node);
2140
2.09k
        std::string ellpsName;
2141
2.09k
        ellpsProperties.getStringValue(IdentifiedObject::NAME_KEY, ellpsName);
2142
2.09k
        const auto celestialBody(Ellipsoid::guessBodyName(
2143
2.09k
            dbContext_, semiMajorAxis.getSIValue(), ellpsName));
2144
2.09k
        if (invFlattening.getSIValue() == 0) {
2145
931
            return Ellipsoid::createSphere(ellpsProperties, semiMajorAxis,
2146
931
                                           celestialBody);
2147
1.16k
        } else {
2148
1.16k
            return Ellipsoid::createFlattenedSphere(
2149
1.16k
                ellpsProperties, semiMajorAxis, invFlattening, celestialBody);
2150
1.16k
        }
2151
2.09k
    } catch (const std::exception &e) {
2152
48
        throw buildRethrow(__FUNCTION__, e);
2153
48
    }
2154
2.09k
}
2155
2156
// ---------------------------------------------------------------------------
2157
2158
PrimeMeridianNNPtr WKTParser::Private::buildPrimeMeridian(
2159
333
    const WKTNodeNNPtr &node, const UnitOfMeasure &defaultAngularUnit) {
2160
333
    const auto *nodeP = node->GP();
2161
333
    const auto &children = nodeP->children();
2162
333
    if (children.size() < 2) {
2163
3
        ThrowNotEnoughChildren(nodeP->value());
2164
3
    }
2165
330
    auto name = stripQuotes(children[0]);
2166
330
    UnitOfMeasure unit = buildUnitInSubNode(node, UnitOfMeasure::Type::ANGULAR);
2167
330
    if (unit == UnitOfMeasure::NONE) {
2168
330
        unit = defaultAngularUnit;
2169
330
        if (unit == UnitOfMeasure::NONE) {
2170
0
            unit = UnitOfMeasure::DEGREE;
2171
0
        }
2172
330
    }
2173
330
    try {
2174
330
        double angleValue = asDouble(children[1]);
2175
2176
        // Correct for GDAL WKT1 and WKT1-ESRI departure
2177
330
        if (name == "Paris" && std::fabs(angleValue - 2.33722917) < 1e-8 &&
2178
0
            unit._isEquivalentTo(UnitOfMeasure::GRAD,
2179
0
                                 util::IComparable::Criterion::EQUIVALENT)) {
2180
0
            angleValue = 2.5969213;
2181
330
        } else {
2182
330
            static const struct {
2183
330
                const char *name;
2184
330
                int deg;
2185
330
                int min;
2186
330
                double sec;
2187
330
            } primeMeridiansDMS[] = {
2188
330
                {"Lisbon", -9, 7, 54.862},  {"Bogota", -74, 4, 51.3},
2189
330
                {"Madrid", -3, 41, 14.55},  {"Rome", 12, 27, 8.4},
2190
330
                {"Bern", 7, 26, 22.5},      {"Jakarta", 106, 48, 27.79},
2191
330
                {"Ferro", -17, 40, 0},      {"Brussels", 4, 22, 4.71},
2192
330
                {"Stockholm", 18, 3, 29.8}, {"Athens", 23, 42, 58.815},
2193
330
                {"Oslo", 10, 43, 22.5},     {"Paris RGS", 2, 20, 13.95},
2194
330
                {"Paris_RGS", 2, 20, 13.95}};
2195
2196
            // Current epsg.org output may use the EPSG:9110 "sexagesimal DMS"
2197
            // unit and a DD.MMSSsss value, but this will likely be changed to
2198
            // use decimal degree.
2199
            // Or WKT1 may for example use the Paris RGS decimal degree value
2200
            // but with a GEOGCS with UNIT["Grad"]
2201
4.20k
            for (const auto &pmDef : primeMeridiansDMS) {
2202
4.20k
                if (name == pmDef.name) {
2203
5
                    double dmsAsDecimalValue =
2204
5
                        (pmDef.deg >= 0 ? 1 : -1) *
2205
5
                        (std::abs(pmDef.deg) + pmDef.min / 100. +
2206
5
                         pmDef.sec / 10000.);
2207
5
                    double dmsAsDecimalDegreeValue =
2208
5
                        (pmDef.deg >= 0 ? 1 : -1) *
2209
5
                        (std::abs(pmDef.deg) + pmDef.min / 60. +
2210
5
                         pmDef.sec / 3600.);
2211
5
                    if (std::fabs(angleValue - dmsAsDecimalValue) < 1e-8 ||
2212
5
                        std::fabs(angleValue - dmsAsDecimalDegreeValue) <
2213
5
                            1e-8) {
2214
0
                        angleValue = dmsAsDecimalDegreeValue;
2215
0
                        unit = UnitOfMeasure::DEGREE;
2216
0
                    }
2217
5
                    break;
2218
5
                }
2219
4.20k
            }
2220
330
        }
2221
2222
330
        auto &properties = buildProperties(node);
2223
330
        if (dbContext_ && esriStyle_) {
2224
298
            std::string outTableName;
2225
298
            std::string codeFromAlias;
2226
298
            std::string authNameFromAlias;
2227
298
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
2228
298
                                                        std::string());
2229
298
            auto officialName = authFactory->getOfficialNameFromAlias(
2230
298
                name, "prime_meridian", "ESRI", false, outTableName,
2231
298
                authNameFromAlias, codeFromAlias);
2232
298
            if (!officialName.empty()) {
2233
0
                properties.set(IdentifiedObject::NAME_KEY, officialName);
2234
0
                if (!authNameFromAlias.empty()) {
2235
0
                    auto identifiers = ArrayOfBaseObject::create();
2236
0
                    identifiers->add(Identifier::create(
2237
0
                        codeFromAlias,
2238
0
                        PropertyMap()
2239
0
                            .set(Identifier::CODESPACE_KEY, authNameFromAlias)
2240
0
                            .set(Identifier::AUTHORITY_KEY,
2241
0
                                 authNameFromAlias)));
2242
0
                    properties.set(IdentifiedObject::IDENTIFIERS_KEY,
2243
0
                                   identifiers);
2244
0
                }
2245
0
            }
2246
298
        }
2247
2248
330
        Angle angle(angleValue, unit);
2249
330
        return PrimeMeridian::create(properties, angle);
2250
330
    } catch (const std::exception &e) {
2251
6
        throw buildRethrow(__FUNCTION__, e);
2252
6
    }
2253
330
}
2254
2255
// ---------------------------------------------------------------------------
2256
2257
1.90k
optional<std::string> WKTParser::Private::getAnchor(const WKTNodeNNPtr &node) {
2258
2259
1.90k
    auto &anchorNode = node->GP()->lookForChild(WKTConstants::ANCHOR);
2260
1.90k
    if (anchorNode->GP()->childrenSize() == 1) {
2261
0
        return optional<std::string>(
2262
0
            stripQuotes(anchorNode->GP()->children()[0]));
2263
0
    }
2264
1.90k
    return optional<std::string>();
2265
1.90k
}
2266
2267
// ---------------------------------------------------------------------------
2268
2269
optional<common::Measure>
2270
1.87k
WKTParser::Private::getAnchorEpoch(const WKTNodeNNPtr &node) {
2271
2272
1.87k
    auto &anchorEpochNode = node->GP()->lookForChild(WKTConstants::ANCHOREPOCH);
2273
1.87k
    if (anchorEpochNode->GP()->childrenSize() == 1) {
2274
0
        try {
2275
0
            double value = asDouble(anchorEpochNode->GP()->children()[0]);
2276
0
            return optional<common::Measure>(
2277
0
                common::Measure(value, common::UnitOfMeasure::YEAR));
2278
0
        } catch (const std::exception &e) {
2279
0
            throw buildRethrow(__FUNCTION__, e);
2280
0
        }
2281
0
    }
2282
1.87k
    return optional<common::Measure>();
2283
1.87k
}
2284
// ---------------------------------------------------------------------------
2285
2286
static const PrimeMeridianNNPtr &
2287
fixupPrimeMeridan(const EllipsoidNNPtr &ellipsoid,
2288
2.00k
                  const PrimeMeridianNNPtr &pm) {
2289
2.00k
    return (ellipsoid->celestialBody() != Ellipsoid::EARTH &&
2290
980
            pm.get() == PrimeMeridian::GREENWICH.get())
2291
2.00k
               ? PrimeMeridian::REFERENCE_MERIDIAN
2292
2.00k
               : pm;
2293
2.00k
}
2294
2295
// ---------------------------------------------------------------------------
2296
2297
GeodeticReferenceFrameNNPtr WKTParser::Private::buildGeodeticReferenceFrame(
2298
    const WKTNodeNNPtr &node, const PrimeMeridianNNPtr &primeMeridian,
2299
1.21k
    const WKTNodeNNPtr &dynamicNode) {
2300
1.21k
    const auto *nodeP = node->GP();
2301
1.21k
    auto &ellipsoidNode =
2302
1.21k
        nodeP->lookForChild(WKTConstants::ELLIPSOID, WKTConstants::SPHEROID);
2303
1.21k
    if (isNull(ellipsoidNode)) {
2304
72
        ThrowMissing(WKTConstants::ELLIPSOID);
2305
72
    }
2306
1.14k
    auto &properties = buildProperties(node);
2307
2308
    // do that before buildEllipsoid() so that esriStyle_ can be set
2309
1.14k
    auto name = stripQuotes(nodeP->children()[0]);
2310
2311
1.14k
    const auto identifyFromName = [&](const std::string &l_name) {
2312
157
        if (dbContext_) {
2313
148
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
2314
148
                                                        std::string());
2315
148
            auto res = authFactory->createObjectsFromName(
2316
148
                l_name,
2317
148
                {AuthorityFactory::ObjectType::GEODETIC_REFERENCE_FRAME}, true,
2318
148
                1);
2319
148
            if (!res.empty()) {
2320
80
                bool foundDatumName = false;
2321
80
                const auto &refDatum = res.front();
2322
80
                if (metadata::Identifier::isEquivalentName(
2323
80
                        l_name.c_str(), refDatum->nameStr().c_str())) {
2324
16
                    foundDatumName = true;
2325
64
                } else if (refDatum->identifiers().size() == 1) {
2326
64
                    const auto &id = refDatum->identifiers()[0];
2327
64
                    const auto aliases =
2328
64
                        authFactory->databaseContext()->getAliases(
2329
64
                            *id->codeSpace(), id->code(), refDatum->nameStr(),
2330
64
                            "geodetic_datum", "not EPSG_OLD");
2331
83
                    for (const auto &alias : aliases) {
2332
83
                        if (metadata::Identifier::isEquivalentName(
2333
83
                                l_name.c_str(), alias.c_str())) {
2334
0
                            foundDatumName = true;
2335
0
                            break;
2336
0
                        }
2337
83
                    }
2338
64
                }
2339
80
                if (foundDatumName) {
2340
16
                    properties.set(IdentifiedObject::NAME_KEY,
2341
16
                                   refDatum->nameStr());
2342
16
                    if (!properties.get(Identifier::CODESPACE_KEY) &&
2343
16
                        refDatum->identifiers().size() == 1) {
2344
16
                        const auto &id = refDatum->identifiers()[0];
2345
16
                        auto identifiers = ArrayOfBaseObject::create();
2346
16
                        identifiers->add(Identifier::create(
2347
16
                            id->code(), PropertyMap()
2348
16
                                            .set(Identifier::CODESPACE_KEY,
2349
16
                                                 *id->codeSpace())
2350
16
                                            .set(Identifier::AUTHORITY_KEY,
2351
16
                                                 *id->codeSpace())));
2352
16
                        properties.set(IdentifiedObject::IDENTIFIERS_KEY,
2353
16
                                       identifiers);
2354
16
                    }
2355
16
                    return true;
2356
16
                }
2357
80
            } else {
2358
                // Get official name from database if AUTHORITY is present
2359
68
                auto &idNode = nodeP->lookForChild(WKTConstants::AUTHORITY);
2360
68
                if (!isNull(idNode)) {
2361
2
                    try {
2362
2
                        auto id = buildId(node, idNode, false, false);
2363
2
                        auto authFactory2 = AuthorityFactory::create(
2364
2
                            NN_NO_CHECK(dbContext_), *id->codeSpace());
2365
2
                        auto dbDatum =
2366
2
                            authFactory2->createGeodeticDatum(id->code());
2367
2
                        properties.set(IdentifiedObject::NAME_KEY,
2368
2
                                       dbDatum->nameStr());
2369
2
                        return true;
2370
2
                    } catch (const std::exception &) {
2371
2
                    }
2372
2
                }
2373
68
            }
2374
148
        }
2375
141
        return false;
2376
157
    };
2377
2378
    // Remap GDAL WGS_1984 to EPSG v9 "World Geodetic System 1984" official
2379
    // name.
2380
1.14k
    bool nameSet = false;
2381
1.14k
    if (name == "WGS_1984") {
2382
0
        nameSet = true;
2383
0
        properties.set(IdentifiedObject::NAME_KEY,
2384
0
                       GeodeticReferenceFrame::EPSG_6326->nameStr());
2385
0
    }
2386
    // Also remap EPSG v10 datum ensemble names to non-ensemble EPSG v9
2387
1.14k
    else if (internal::ends_with(name, " ensemble")) {
2388
0
        auto massagedName = DatumEnsemble::ensembleNameToNonEnsembleName(name);
2389
0
        if (!massagedName.empty()) {
2390
0
            nameSet = true;
2391
0
            properties.set(IdentifiedObject::NAME_KEY, massagedName);
2392
0
        }
2393
0
    }
2394
    // If we got hints this might be a ESRI WKT, then check in the DB to
2395
    // confirm
2396
1.14k
    std::string officialName;
2397
1.14k
    std::string authNameFromAlias;
2398
1.14k
    std::string codeFromAlias;
2399
1.14k
    if (!nameSet && maybeEsriStyle_ && dbContext_ &&
2400
876
        !(starts_with(name, "D_") || esriStyle_)) {
2401
569
        std::string outTableName;
2402
569
        auto authFactory =
2403
569
            AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string());
2404
569
        officialName = authFactory->getOfficialNameFromAlias(
2405
569
            name, "geodetic_datum", "ESRI", false, outTableName,
2406
569
            authNameFromAlias, codeFromAlias);
2407
569
        if (!officialName.empty()) {
2408
0
            maybeEsriStyle_ = false;
2409
0
            esriStyle_ = true;
2410
0
        }
2411
569
    }
2412
2413
1.14k
    if (!nameSet && (starts_with(name, "D_") || esriStyle_)) {
2414
351
        esriStyle_ = true;
2415
351
        const char *tableNameForAlias = nullptr;
2416
351
        if (name == "D_WGS_1984") {
2417
149
            name = "World Geodetic System 1984";
2418
149
            authNameFromAlias = Identifier::EPSG;
2419
149
            codeFromAlias = "6326";
2420
202
        } else if (name == "D_ETRS_1989") {
2421
0
            name = "European Terrestrial Reference System 1989";
2422
0
            authNameFromAlias = Identifier::EPSG;
2423
0
            codeFromAlias = "6258";
2424
202
        } else if (name == "D_unknown") {
2425
0
            name = "unknown";
2426
202
        } else if (name == "D_Unknown_based_on_WGS_84_ellipsoid") {
2427
0
            name = "Unknown based on WGS 84 ellipsoid";
2428
202
        } else {
2429
202
            tableNameForAlias = "geodetic_datum";
2430
202
        }
2431
2432
351
        bool setNameAndId = true;
2433
351
        if (dbContext_ && tableNameForAlias) {
2434
188
            if (officialName.empty()) {
2435
188
                std::string outTableName;
2436
188
                auto authFactory = AuthorityFactory::create(
2437
188
                    NN_NO_CHECK(dbContext_), std::string());
2438
188
                officialName = authFactory->getOfficialNameFromAlias(
2439
188
                    name, tableNameForAlias, "ESRI", false, outTableName,
2440
188
                    authNameFromAlias, codeFromAlias);
2441
188
            }
2442
188
            if (officialName.empty()) {
2443
71
                if (starts_with(name, "D_")) {
2444
                    // For the case of "D_GDA2020" where there is no D_GDA2020
2445
                    // ESRI alias, so just try without the D_ prefix.
2446
39
                    const auto nameWithoutDPrefix = name.substr(2);
2447
39
                    if (identifyFromName(nameWithoutDPrefix)) {
2448
0
                        setNameAndId =
2449
0
                            false; // already done in identifyFromName()
2450
0
                    }
2451
39
                }
2452
117
            } else {
2453
117
                if (primeMeridian->nameStr() !=
2454
117
                    PrimeMeridian::GREENWICH->nameStr()) {
2455
0
                    auto nameWithPM =
2456
0
                        officialName + " (" + primeMeridian->nameStr() + ")";
2457
0
                    if (dbContext_->isKnownName(nameWithPM, "geodetic_datum")) {
2458
0
                        officialName = std::move(nameWithPM);
2459
0
                    }
2460
0
                }
2461
117
                name = std::move(officialName);
2462
117
            }
2463
188
        }
2464
2465
351
        if (setNameAndId) {
2466
351
            properties.set(IdentifiedObject::NAME_KEY, name);
2467
351
            if (!authNameFromAlias.empty()) {
2468
266
                auto identifiers = ArrayOfBaseObject::create();
2469
266
                identifiers->add(Identifier::create(
2470
266
                    codeFromAlias,
2471
266
                    PropertyMap()
2472
266
                        .set(Identifier::CODESPACE_KEY, authNameFromAlias)
2473
266
                        .set(Identifier::AUTHORITY_KEY, authNameFromAlias)));
2474
266
                properties.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers);
2475
266
            }
2476
351
        }
2477
789
    } else if (!nameSet && name.find('_') != std::string::npos) {
2478
        // Likely coming from WKT1
2479
118
        identifyFromName(name);
2480
118
    }
2481
2482
1.14k
    auto ellipsoid = buildEllipsoid(ellipsoidNode);
2483
1.14k
    const auto &primeMeridianModified =
2484
1.14k
        fixupPrimeMeridan(ellipsoid, primeMeridian);
2485
2486
1.14k
    auto &TOWGS84Node = nodeP->lookForChild(WKTConstants::TOWGS84);
2487
1.14k
    if (!isNull(TOWGS84Node)) {
2488
4
        const auto &TOWGS84Children = TOWGS84Node->GP()->children();
2489
4
        const size_t TOWGS84Size = TOWGS84Children.size();
2490
4
        if (TOWGS84Size == 3 || TOWGS84Size == 7) {
2491
1
            try {
2492
2
                for (const auto &child : TOWGS84Children) {
2493
2
                    toWGS84Parameters_.push_back(asDouble(child));
2494
2
                }
2495
2496
1
                if (TOWGS84Size == 7 && dbContext_) {
2497
0
                    dbContext_->toWGS84AutocorrectWrongValues(
2498
0
                        toWGS84Parameters_[0], toWGS84Parameters_[1],
2499
0
                        toWGS84Parameters_[2], toWGS84Parameters_[3],
2500
0
                        toWGS84Parameters_[4], toWGS84Parameters_[5],
2501
0
                        toWGS84Parameters_[6]);
2502
0
                }
2503
2504
1
                for (size_t i = TOWGS84Size; i < 7; ++i) {
2505
0
                    toWGS84Parameters_.push_back(0.0);
2506
0
                }
2507
1
            } catch (const std::exception &) {
2508
1
                throw ParsingException("Invalid TOWGS84 node");
2509
1
            }
2510
3
        } else {
2511
3
            throw ParsingException("Invalid TOWGS84 node");
2512
3
        }
2513
4
    }
2514
2515
1.13k
    auto &extensionNode = nodeP->lookForChild(WKTConstants::EXTENSION);
2516
1.13k
    const auto &extensionChildren = extensionNode->GP()->children();
2517
1.13k
    if (extensionChildren.size() == 2) {
2518
4
        if (ci_equal(stripQuotes(extensionChildren[0]), "PROJ4_GRIDS")) {
2519
0
            datumPROJ4Grids_ = stripQuotes(extensionChildren[1]);
2520
0
        }
2521
4
    }
2522
2523
1.13k
    if (!isNull(dynamicNode)) {
2524
21
        double frameReferenceEpoch = 0.0;
2525
21
        util::optional<std::string> modelName;
2526
21
        parseDynamic(dynamicNode, frameReferenceEpoch, modelName);
2527
21
        return DynamicGeodeticReferenceFrame::create(
2528
21
            properties, ellipsoid, getAnchor(node), primeMeridianModified,
2529
21
            common::Measure(frameReferenceEpoch, common::UnitOfMeasure::YEAR),
2530
21
            modelName);
2531
21
    }
2532
2533
1.11k
    return GeodeticReferenceFrame::create(properties, ellipsoid,
2534
1.11k
                                          getAnchor(node), getAnchorEpoch(node),
2535
1.11k
                                          primeMeridianModified);
2536
1.13k
}
2537
2538
// ---------------------------------------------------------------------------
2539
2540
DatumEnsembleNNPtr
2541
WKTParser::Private::buildDatumEnsemble(const WKTNodeNNPtr &node,
2542
                                       const PrimeMeridianPtr &primeMeridian,
2543
212
                                       bool expectEllipsoid) {
2544
212
    const auto *nodeP = node->GP();
2545
212
    auto &ellipsoidNode =
2546
212
        nodeP->lookForChild(WKTConstants::ELLIPSOID, WKTConstants::SPHEROID);
2547
212
    if (expectEllipsoid && isNull(ellipsoidNode)) {
2548
10
        ThrowMissing(WKTConstants::ELLIPSOID);
2549
10
    }
2550
2551
202
    auto properties = buildProperties(node);
2552
2553
202
    std::vector<DatumNNPtr> datums;
2554
4.06k
    for (const auto &subNode : nodeP->children()) {
2555
4.06k
        if (ci_equal(subNode->GP()->value(), WKTConstants::MEMBER)) {
2556
1.17k
            if (subNode->GP()->childrenSize() == 0) {
2557
11
                throw ParsingException("Invalid MEMBER node");
2558
11
            }
2559
1.16k
            if (expectEllipsoid) {
2560
963
                datums.emplace_back(GeodeticReferenceFrame::create(
2561
963
                    buildProperties(subNode), buildEllipsoid(ellipsoidNode),
2562
963
                    optional<std::string>(),
2563
963
                    primeMeridian ? NN_NO_CHECK(primeMeridian)
2564
963
                                  : PrimeMeridian::GREENWICH));
2565
963
            } else {
2566
200
                datums.emplace_back(
2567
200
                    VerticalReferenceFrame::create(buildProperties(subNode)));
2568
200
            }
2569
1.16k
        }
2570
4.06k
    }
2571
2572
191
    if (datums.empty() && !nodeP->children().empty()) {
2573
9
        auto name = stripQuotes(nodeP->children()[0]);
2574
9
        if (dbContext_) {
2575
8
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
2576
8
                                                        std::string());
2577
8
            auto res = authFactory->createObjectsFromName(
2578
8
                name, {AuthorityFactory::ObjectType::DATUM_ENSEMBLE}, true, 1);
2579
8
            if (res.size() == 1) {
2580
2
                auto datumEnsemble =
2581
2
                    dynamic_cast<const DatumEnsemble *>(res.front().get());
2582
2
                if (datumEnsemble) {
2583
2
                    datums = datumEnsemble->datums();
2584
2
                }
2585
6
            } else {
2586
6
                throw ParsingException(
2587
6
                    "No entry for datum ensemble '" + name +
2588
6
                    "' in database, and no explicit member specified");
2589
6
            }
2590
8
        } else {
2591
1
            throw ParsingException("Datum ensemble '" + name +
2592
1
                                   "' has no explicit member specified and no "
2593
1
                                   "connection to database");
2594
1
        }
2595
9
    }
2596
2597
184
    auto &accuracyNode = nodeP->lookForChild(WKTConstants::ENSEMBLEACCURACY);
2598
184
    auto &accuracyNodeChildren = accuracyNode->GP()->children();
2599
184
    if (accuracyNodeChildren.empty()) {
2600
121
        ThrowMissing(WKTConstants::ENSEMBLEACCURACY);
2601
121
    }
2602
63
    auto accuracy =
2603
63
        PositionalAccuracy::create(accuracyNodeChildren[0]->GP()->value());
2604
2605
63
    try {
2606
63
        return DatumEnsemble::create(properties, datums, accuracy);
2607
63
    } catch (const util::Exception &e) {
2608
5
        throw buildRethrow(__FUNCTION__, e);
2609
5
    }
2610
63
}
2611
2612
// ---------------------------------------------------------------------------
2613
2614
0
MeridianNNPtr WKTParser::Private::buildMeridian(const WKTNodeNNPtr &node) {
2615
0
    const auto *nodeP = node->GP();
2616
0
    const auto &children = nodeP->children();
2617
0
    if (children.size() < 2) {
2618
0
        ThrowNotEnoughChildren(nodeP->value());
2619
0
    }
2620
0
    UnitOfMeasure unit = buildUnitInSubNode(node, UnitOfMeasure::Type::ANGULAR);
2621
0
    try {
2622
0
        double angleValue = asDouble(children[0]);
2623
0
        Angle angle(angleValue, unit);
2624
0
        return Meridian::create(angle);
2625
0
    } catch (const std::exception &e) {
2626
0
        throw buildRethrow(__FUNCTION__, e);
2627
0
    }
2628
0
}
2629
2630
// ---------------------------------------------------------------------------
2631
2632
8
PROJ_NO_RETURN static void ThrowParsingExceptionMissingUNIT() {
2633
8
    throw ParsingException("buildCS: missing UNIT");
2634
8
}
2635
2636
// ---------------------------------------------------------------------------
2637
2638
CoordinateSystemAxisNNPtr
2639
WKTParser::Private::buildAxis(const WKTNodeNNPtr &node,
2640
                              const UnitOfMeasure &unitIn,
2641
                              const UnitOfMeasure::Type &unitType,
2642
215
                              bool isGeocentric, int expectedOrderNum) {
2643
215
    const auto *nodeP = node->GP();
2644
215
    const auto &children = nodeP->children();
2645
215
    if (children.size() < 2) {
2646
10
        ThrowNotEnoughChildren(nodeP->value());
2647
10
    }
2648
2649
205
    auto &orderNode = nodeP->lookForChild(WKTConstants::ORDER);
2650
205
    if (!isNull(orderNode)) {
2651
11
        const auto &orderNodeChildren = orderNode->GP()->children();
2652
11
        if (orderNodeChildren.size() != 1) {
2653
2
            ThrowNotEnoughChildren(WKTConstants::ORDER);
2654
2
        }
2655
9
        const auto &order = orderNodeChildren[0]->GP()->value();
2656
9
        int orderNum;
2657
9
        try {
2658
9
            orderNum = std::stoi(order);
2659
9
        } catch (const std::exception &) {
2660
3
            throw ParsingException(
2661
3
                concat("buildAxis: invalid ORDER value: ", order));
2662
3
        }
2663
6
        if (orderNum != expectedOrderNum) {
2664
4
            throw ParsingException(
2665
4
                concat("buildAxis: did not get expected ORDER value: ", order));
2666
4
        }
2667
6
    }
2668
2669
    // The axis designation in WK2 can be: "name", "(abbrev)" or "name
2670
    // (abbrev)"
2671
196
    std::string axisDesignation(stripQuotes(children[0]));
2672
196
    size_t sepPos = axisDesignation.find(" (");
2673
196
    std::string axisName;
2674
196
    std::string abbreviation;
2675
196
    if (sepPos != std::string::npos && axisDesignation.back() == ')') {
2676
7
        axisName = CoordinateSystemAxis::normalizeAxisName(
2677
7
            axisDesignation.substr(0, sepPos));
2678
7
        abbreviation = axisDesignation.substr(sepPos + 2);
2679
7
        abbreviation.resize(abbreviation.size() - 1);
2680
189
    } else if (!axisDesignation.empty() && axisDesignation[0] == '(' &&
2681
35
               axisDesignation.back() == ')') {
2682
22
        abbreviation = axisDesignation.substr(1, axisDesignation.size() - 2);
2683
22
        if (abbreviation == AxisAbbreviation::E) {
2684
2
            axisName = AxisName::Easting;
2685
20
        } else if (abbreviation == AxisAbbreviation::N) {
2686
0
            axisName = AxisName::Northing;
2687
20
        } else if (abbreviation == AxisAbbreviation::lat) {
2688
0
            axisName = AxisName::Latitude;
2689
20
        } else if (abbreviation == AxisAbbreviation::lon) {
2690
0
            axisName = AxisName::Longitude;
2691
0
        }
2692
167
    } else {
2693
167
        axisName = CoordinateSystemAxis::normalizeAxisName(axisDesignation);
2694
167
        if (axisName == AxisName::Latitude) {
2695
0
            abbreviation = AxisAbbreviation::lat;
2696
167
        } else if (axisName == AxisName::Longitude) {
2697
0
            abbreviation = AxisAbbreviation::lon;
2698
167
        } else if (axisName == AxisName::Ellipsoidal_height) {
2699
0
            abbreviation = AxisAbbreviation::h;
2700
0
        }
2701
167
    }
2702
196
    const std::string &dirString = children[1]->GP()->value();
2703
196
    const AxisDirection *direction = AxisDirection::valueOf(dirString);
2704
2705
    // WKT2, geocentric CS: axis names are omitted
2706
196
    if (axisName.empty()) {
2707
22
        if (direction == &AxisDirection::GEOCENTRIC_X &&
2708
0
            abbreviation == AxisAbbreviation::X) {
2709
0
            axisName = AxisName::Geocentric_X;
2710
22
        } else if (direction == &AxisDirection::GEOCENTRIC_Y &&
2711
7
                   abbreviation == AxisAbbreviation::Y) {
2712
0
            axisName = AxisName::Geocentric_Y;
2713
22
        } else if (direction == &AxisDirection::GEOCENTRIC_Z &&
2714
0
                   abbreviation == AxisAbbreviation::Z) {
2715
0
            axisName = AxisName::Geocentric_Z;
2716
0
        }
2717
22
    }
2718
2719
    // WKT1
2720
196
    if (!direction && isGeocentric && axisName == AxisName::Geocentric_X) {
2721
20
        abbreviation = AxisAbbreviation::X;
2722
20
        direction = &AxisDirection::GEOCENTRIC_X;
2723
176
    } else if (!direction && isGeocentric &&
2724
22
               axisName == AxisName::Geocentric_Y) {
2725
0
        abbreviation = AxisAbbreviation::Y;
2726
0
        direction = &AxisDirection::GEOCENTRIC_Y;
2727
176
    } else if (isGeocentric && axisName == AxisName::Geocentric_Z &&
2728
6
               (dirString == AxisDirectionWKT1::NORTH.toString() ||
2729
6
                dirString == AxisDirectionWKT1::OTHER.toString())) {
2730
0
        abbreviation = AxisAbbreviation::Z;
2731
0
        direction = &AxisDirection::GEOCENTRIC_Z;
2732
176
    } else if (dirString == AxisDirectionWKT1::OTHER.toString()) {
2733
0
        direction = &AxisDirection::UNSPECIFIED;
2734
176
    } else if (dirString == "UNKNOWN") {
2735
        // Found in WKT1 of NSIDC's EASE-Grid Sea Ice Age datasets.
2736
        // Cf https://github.com/OSGeo/gdal/issues/7210
2737
0
        emitRecoverableWarning("UNKNOWN is not a valid direction name.");
2738
0
        direction = &AxisDirection::UNSPECIFIED;
2739
0
    }
2740
2741
196
    if (!direction) {
2742
91
        throw ParsingException(
2743
91
            concat("unhandled axis direction: ", children[1]->GP()->value()));
2744
91
    }
2745
105
    UnitOfMeasure unit(buildUnitInSubNode(node));
2746
105
    if (unit == UnitOfMeasure::NONE) {
2747
        // If no unit in the AXIS node, use the one potentially coming from
2748
        // the CS.
2749
92
        unit = unitIn;
2750
92
        if (unit == UnitOfMeasure::NONE &&
2751
8
            unitType != UnitOfMeasure::Type::NONE &&
2752
8
            unitType != UnitOfMeasure::Type::TIME) {
2753
8
            ThrowParsingExceptionMissingUNIT();
2754
8
        }
2755
92
    }
2756
2757
97
    auto &meridianNode = nodeP->lookForChild(WKTConstants::MERIDIAN);
2758
2759
97
    util::optional<double> minVal;
2760
97
    auto &axisMinValueNode = nodeP->lookForChild(WKTConstants::AXISMINVALUE);
2761
97
    if (!isNull(axisMinValueNode)) {
2762
0
        const auto &axisMinValueNodeChildren =
2763
0
            axisMinValueNode->GP()->children();
2764
0
        if (axisMinValueNodeChildren.size() != 1) {
2765
0
            ThrowNotEnoughChildren(WKTConstants::AXISMINVALUE);
2766
0
        }
2767
0
        const auto &val = axisMinValueNodeChildren[0];
2768
0
        try {
2769
0
            minVal = asDouble(val);
2770
0
        } catch (const std::exception &) {
2771
0
            throw ParsingException(concat(
2772
0
                "buildAxis: invalid AXISMINVALUE value: ", val->GP()->value()));
2773
0
        }
2774
0
    }
2775
2776
97
    util::optional<double> maxVal;
2777
97
    auto &axisMaxValueNode = nodeP->lookForChild(WKTConstants::AXISMAXVALUE);
2778
97
    if (!isNull(axisMaxValueNode)) {
2779
0
        const auto &axisMaxValueNodeChildren =
2780
0
            axisMaxValueNode->GP()->children();
2781
0
        if (axisMaxValueNodeChildren.size() != 1) {
2782
0
            ThrowNotEnoughChildren(WKTConstants::AXISMAXVALUE);
2783
0
        }
2784
0
        const auto &val = axisMaxValueNodeChildren[0];
2785
0
        try {
2786
0
            maxVal = asDouble(val);
2787
0
        } catch (const std::exception &) {
2788
0
            throw ParsingException(concat(
2789
0
                "buildAxis: invalid AXISMAXVALUE value: ", val->GP()->value()));
2790
0
        }
2791
0
    }
2792
2793
97
    util::optional<RangeMeaning> rangeMeaning;
2794
97
    auto &rangeMeaningNode = nodeP->lookForChild(WKTConstants::RANGEMEANING);
2795
97
    if (!isNull(rangeMeaningNode)) {
2796
10
        const auto &rangeMeaningNodeChildren =
2797
10
            rangeMeaningNode->GP()->children();
2798
10
        if (rangeMeaningNodeChildren.size() != 1) {
2799
1
            ThrowNotEnoughChildren(WKTConstants::RANGEMEANING);
2800
1
        }
2801
9
        const std::string &val = rangeMeaningNodeChildren[0]->GP()->value();
2802
9
        const RangeMeaning *meaning = RangeMeaning::valueOf(val);
2803
9
        if (meaning == nullptr) {
2804
9
            throw ParsingException(
2805
9
                concat("buildAxis: invalid RANGEMEANING value: ", val));
2806
9
        }
2807
0
        rangeMeaning = util::optional<RangeMeaning>(*meaning);
2808
0
    }
2809
2810
87
    return CoordinateSystemAxis::create(
2811
87
        buildProperties(node).set(IdentifiedObject::NAME_KEY, axisName),
2812
87
        abbreviation, *direction, unit, minVal, maxVal, rangeMeaning,
2813
87
        !isNull(meridianNode) ? buildMeridian(meridianNode).as_nullable()
2814
87
                              : nullptr);
2815
97
}
2816
2817
// ---------------------------------------------------------------------------
2818
2819
static const PropertyMap emptyPropertyMap{};
2820
2821
// ---------------------------------------------------------------------------
2822
2823
4
PROJ_NO_RETURN static void ThrowParsingException(const std::string &msg) {
2824
4
    throw ParsingException(msg);
2825
4
}
2826
2827
// ---------------------------------------------------------------------------
2828
2829
static ParsingException
2830
18
buildParsingExceptionInvalidAxisCount(const std::string &csType) {
2831
18
    return ParsingException(
2832
18
        concat("buildCS: invalid CS axis count for ", csType));
2833
18
}
2834
2835
// ---------------------------------------------------------------------------
2836
2837
void WKTParser::Private::emitRecoverableMissingUNIT(
2838
1.46k
    const std::string &parentNodeName, const UnitOfMeasure &fallbackUnit) {
2839
1.46k
    std::string msg("buildCS: missing UNIT in ");
2840
1.46k
    msg += parentNodeName;
2841
1.46k
    if (!strict_ && fallbackUnit == UnitOfMeasure::METRE) {
2842
984
        msg += ". Assuming metre";
2843
984
    } else if (!strict_ && fallbackUnit == UnitOfMeasure::DEGREE) {
2844
484
        msg += ". Assuming degree";
2845
484
    }
2846
1.46k
    emitRecoverableWarning(msg);
2847
1.46k
}
2848
2849
// ---------------------------------------------------------------------------
2850
2851
CoordinateSystemNNPtr
2852
WKTParser::Private::buildCS(const WKTNodeNNPtr &node, /* maybe null */
2853
                            const WKTNodeNNPtr &parentNode,
2854
2.81k
                            const UnitOfMeasure &defaultAngularUnit) {
2855
2.81k
    bool isGeocentric = false;
2856
2.81k
    std::string csType;
2857
2.81k
    const int numberOfAxis =
2858
2.81k
        parentNode->countChildrenOfName(WKTConstants::AXIS);
2859
2.81k
    int axisCount = numberOfAxis;
2860
2.81k
    const auto &parentNodeName = parentNode->GP()->value();
2861
2.81k
    if (!isNull(node)) {
2862
22
        const auto *nodeP = node->GP();
2863
22
        const auto &children = nodeP->children();
2864
22
        if (children.size() < 2) {
2865
6
            ThrowNotEnoughChildren(nodeP->value());
2866
6
        }
2867
16
        csType = children[0]->GP()->value();
2868
16
        try {
2869
16
            axisCount = std::stoi(children[1]->GP()->value());
2870
16
        } catch (const std::exception &) {
2871
4
            ThrowParsingException(concat("buildCS: invalid CS axis count: ",
2872
4
                                         children[1]->GP()->value()));
2873
4
        }
2874
2.79k
    } else {
2875
2.79k
        const char *csTypeCStr = CartesianCS::WKT2_TYPE;
2876
2.79k
        if (ci_equal(parentNodeName, WKTConstants::GEOCCS)) {
2877
            // csTypeCStr = CartesianCS::WKT2_TYPE;
2878
83
            isGeocentric = true;
2879
83
            if (axisCount == 0) {
2880
42
                auto unit =
2881
42
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR);
2882
42
                if (unit == UnitOfMeasure::NONE) {
2883
34
                    unit = UnitOfMeasure::METRE;
2884
34
                    emitRecoverableMissingUNIT(parentNodeName, unit);
2885
34
                }
2886
42
                return CartesianCS::createGeocentric(unit);
2887
42
            }
2888
2.70k
        } else if (ci_equal(parentNodeName, WKTConstants::GEOGCS)) {
2889
992
            csTypeCStr = EllipsoidalCS::WKT2_TYPE;
2890
992
            if (axisCount == 0) {
2891
                // Missing axis with GEOGCS ? Presumably Long/Lat order
2892
                // implied
2893
991
                auto unit = buildUnitInSubNode(parentNode,
2894
991
                                               UnitOfMeasure::Type::ANGULAR);
2895
991
                if (unit == UnitOfMeasure::NONE) {
2896
484
                    unit = defaultAngularUnit;
2897
484
                    emitRecoverableMissingUNIT(parentNodeName, unit);
2898
484
                }
2899
2900
                // ESRI WKT for geographic 3D CRS
2901
991
                auto &linUnitNode =
2902
991
                    parentNode->GP()->lookForChild(WKTConstants::LINUNIT);
2903
991
                if (!isNull(linUnitNode)) {
2904
0
                    return EllipsoidalCS::
2905
0
                        createLongitudeLatitudeEllipsoidalHeight(
2906
0
                            unit, buildUnit(linUnitNode,
2907
0
                                            UnitOfMeasure::Type::LINEAR));
2908
0
                }
2909
2910
                // WKT1 --> long/lat
2911
991
                return EllipsoidalCS::createLongitudeLatitude(unit);
2912
991
            }
2913
1.71k
        } else if (ci_equal(parentNodeName, WKTConstants::BASEGEODCRS) ||
2914
1.71k
                   ci_equal(parentNodeName, WKTConstants::BASEGEOGCRS)) {
2915
0
            csTypeCStr = EllipsoidalCS::WKT2_TYPE;
2916
0
            if (axisCount == 0) {
2917
0
                auto unit = buildUnitInSubNode(parentNode,
2918
0
                                               UnitOfMeasure::Type::ANGULAR);
2919
0
                if (unit == UnitOfMeasure::NONE) {
2920
0
                    unit = defaultAngularUnit;
2921
0
                }
2922
                // WKT2 --> presumably lat/long
2923
0
                return EllipsoidalCS::createLatitudeLongitude(unit);
2924
0
            }
2925
1.71k
        } else if (ci_equal(parentNodeName, WKTConstants::PROJCS) ||
2926
1.01k
                   ci_equal(parentNodeName, WKTConstants::BASEPROJCRS) ||
2927
1.01k
                   ci_equal(parentNodeName, WKTConstants::BASEENGCRS)) {
2928
704
            csTypeCStr = CartesianCS::WKT2_TYPE;
2929
704
            if (axisCount == 0) {
2930
704
                auto unit =
2931
704
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR);
2932
704
                if (unit == UnitOfMeasure::NONE) {
2933
385
                    unit = UnitOfMeasure::METRE;
2934
385
                    if (ci_equal(parentNodeName, WKTConstants::PROJCS)) {
2935
385
                        emitRecoverableMissingUNIT(parentNodeName, unit);
2936
385
                    }
2937
385
                }
2938
704
                return CartesianCS::createEastingNorthing(unit);
2939
704
            }
2940
1.01k
        } else if (ci_equal(parentNodeName, WKTConstants::VERT_CS) ||
2941
990
                   ci_equal(parentNodeName, WKTConstants::VERTCS) ||
2942
655
                   ci_equal(parentNodeName, WKTConstants::BASEVERTCRS)) {
2943
655
            csTypeCStr = VerticalCS::WKT2_TYPE;
2944
2945
655
            bool downDirection = false;
2946
655
            if (ci_equal(parentNodeName, WKTConstants::VERTCS)) // ESRI
2947
634
            {
2948
3.05k
                for (const auto &childNode : parentNode->GP()->children()) {
2949
3.05k
                    const auto &childNodeChildren = childNode->GP()->children();
2950
3.05k
                    if (childNodeChildren.size() == 2 &&
2951
297
                        ci_equal(childNode->GP()->value(),
2952
297
                                 WKTConstants::PARAMETER) &&
2953
17
                        childNodeChildren[0]->GP()->value() ==
2954
17
                            "\"Direction\"") {
2955
0
                        const auto &paramValue =
2956
0
                            childNodeChildren[1]->GP()->value();
2957
0
                        try {
2958
0
                            double val = asDouble(childNodeChildren[1]);
2959
0
                            if (val == 1.0) {
2960
                                // ok
2961
0
                            } else if (val == -1.0) {
2962
0
                                downDirection = true;
2963
0
                            }
2964
0
                        } catch (const std::exception &) {
2965
0
                            throw ParsingException(
2966
0
                                concat("unhandled parameter value type : ",
2967
0
                                       paramValue));
2968
0
                        }
2969
0
                    }
2970
3.05k
                }
2971
634
            }
2972
2973
655
            if (axisCount == 0) {
2974
561
                auto unit =
2975
561
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR);
2976
561
                if (unit == UnitOfMeasure::NONE) {
2977
471
                    unit = UnitOfMeasure::METRE;
2978
471
                    if (ci_equal(parentNodeName, WKTConstants::VERT_CS) ||
2979
471
                        ci_equal(parentNodeName, WKTConstants::VERTCS)) {
2980
471
                        emitRecoverableMissingUNIT(parentNodeName, unit);
2981
471
                    }
2982
471
                }
2983
561
                if (downDirection) {
2984
0
                    return VerticalCS::create(
2985
0
                        util::PropertyMap(),
2986
0
                        CoordinateSystemAxis::create(
2987
0
                            util::PropertyMap().set(IdentifiedObject::NAME_KEY,
2988
0
                                                    "depth"),
2989
0
                            "D", AxisDirection::DOWN, unit));
2990
0
                }
2991
561
                return VerticalCS::createGravityRelatedHeight(unit);
2992
561
            }
2993
655
        } else if (ci_equal(parentNodeName, WKTConstants::LOCAL_CS)) {
2994
356
            if (axisCount == 0) {
2995
274
                auto unit =
2996
274
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR);
2997
274
                if (unit == UnitOfMeasure::NONE) {
2998
271
                    unit = UnitOfMeasure::METRE;
2999
271
                }
3000
274
                return CartesianCS::createEastingNorthing(unit);
3001
274
            } else if (axisCount == 1) {
3002
74
                csTypeCStr = VerticalCS::WKT2_TYPE;
3003
74
            } else if (axisCount == 2 || axisCount == 3) {
3004
6
                csTypeCStr = CartesianCS::WKT2_TYPE;
3005
6
            } else {
3006
2
                throw ParsingException(
3007
2
                    "buildCS: unexpected AXIS count for LOCAL_CS");
3008
2
            }
3009
356
        } else if (ci_equal(parentNodeName, WKTConstants::BASEPARAMCRS)) {
3010
0
            csTypeCStr = ParametricCS::WKT2_TYPE;
3011
0
            if (axisCount == 0) {
3012
0
                auto unit =
3013
0
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::LINEAR);
3014
0
                if (unit == UnitOfMeasure::NONE) {
3015
0
                    unit = UnitOfMeasure("unknown", 1,
3016
0
                                         UnitOfMeasure::Type::PARAMETRIC);
3017
0
                }
3018
0
                return ParametricCS::create(
3019
0
                    emptyPropertyMap,
3020
0
                    CoordinateSystemAxis::create(
3021
0
                        PropertyMap().set(IdentifiedObject::NAME_KEY,
3022
0
                                          "unknown parametric"),
3023
0
                        std::string(), AxisDirection::UNSPECIFIED, unit));
3024
0
            }
3025
0
        } else if (ci_equal(parentNodeName, WKTConstants::BASETIMECRS)) {
3026
0
            csTypeCStr = TemporalCS::WKT2_2015_TYPE;
3027
0
            if (axisCount == 0) {
3028
0
                auto unit =
3029
0
                    buildUnitInSubNode(parentNode, UnitOfMeasure::Type::TIME);
3030
0
                if (unit == UnitOfMeasure::NONE) {
3031
0
                    unit =
3032
0
                        UnitOfMeasure("unknown", 1, UnitOfMeasure::Type::TIME);
3033
0
                }
3034
0
                return DateTimeTemporalCS::create(
3035
0
                    emptyPropertyMap,
3036
0
                    CoordinateSystemAxis::create(
3037
0
                        PropertyMap().set(IdentifiedObject::NAME_KEY,
3038
0
                                          "unknown temporal"),
3039
0
                        std::string(), AxisDirection::FUTURE, unit));
3040
0
            }
3041
0
        } else {
3042
            // Shouldn't happen normally
3043
0
            throw ParsingException(
3044
0
                concat("buildCS: unexpected parent node: ", parentNodeName));
3045
0
        }
3046
216
        csType = csTypeCStr;
3047
216
    }
3048
3049
228
    if (axisCount != 1 && axisCount != 2 && axisCount != 3) {
3050
12
        throw buildParsingExceptionInvalidAxisCount(csType);
3051
12
    }
3052
216
    if (numberOfAxis != axisCount) {
3053
0
        throw ParsingException("buildCS: declared number of axis by CS node "
3054
0
                               "and number of AXIS are inconsistent");
3055
0
    }
3056
3057
216
    const auto unitType =
3058
216
        ci_equal(csType, EllipsoidalCS::WKT2_TYPE)
3059
216
            ? UnitOfMeasure::Type::ANGULAR
3060
216
        : ci_equal(csType, OrdinalCS::WKT2_TYPE) ? UnitOfMeasure::Type::NONE
3061
215
        : ci_equal(csType, ParametricCS::WKT2_TYPE)
3062
215
            ? UnitOfMeasure::Type::PARAMETRIC
3063
215
        : ci_equal(csType, CartesianCS::WKT2_TYPE) ||
3064
168
                ci_equal(csType, VerticalCS::WKT2_TYPE) ||
3065
0
                ci_equal(csType, AffineCS::WKT2_TYPE)
3066
215
            ? UnitOfMeasure::Type::LINEAR
3067
215
        : (ci_equal(csType, TemporalCS::WKT2_2015_TYPE) ||
3068
0
           ci_equal(csType, DateTimeTemporalCS::WKT2_2019_TYPE) ||
3069
0
           ci_equal(csType, TemporalCountCS::WKT2_2019_TYPE) ||
3070
0
           ci_equal(csType, TemporalMeasureCS::WKT2_2019_TYPE))
3071
0
            ? UnitOfMeasure::Type::TIME
3072
0
            : UnitOfMeasure::Type::UNKNOWN;
3073
216
    UnitOfMeasure unit = buildUnitInSubNode(parentNode, unitType);
3074
3075
216
    if (unit == UnitOfMeasure::NONE) {
3076
203
        if (ci_equal(parentNodeName, WKTConstants::VERT_CS) ||
3077
202
            ci_equal(parentNodeName, WKTConstants::VERTCS)) {
3078
94
            unit = UnitOfMeasure::METRE;
3079
94
            emitRecoverableMissingUNIT(parentNodeName, unit);
3080
94
        }
3081
203
    }
3082
3083
216
    std::vector<CoordinateSystemAxisNNPtr> axisList;
3084
431
    for (int i = 0; i < axisCount; i++) {
3085
215
        axisList.emplace_back(
3086
215
            buildAxis(parentNode->GP()->lookForChild(WKTConstants::AXIS, i),
3087
215
                      unit, unitType, isGeocentric, i + 1));
3088
215
    }
3089
3090
216
    const PropertyMap &csMap = emptyPropertyMap;
3091
216
    if (ci_equal(csType, EllipsoidalCS::WKT2_TYPE)) {
3092
0
        if (axisCount == 2) {
3093
0
            return EllipsoidalCS::create(csMap, axisList[0], axisList[1]);
3094
0
        } else if (axisCount == 3) {
3095
0
            return EllipsoidalCS::create(csMap, axisList[0], axisList[1],
3096
0
                                         axisList[2]);
3097
0
        }
3098
216
    } else if (ci_equal(csType, CartesianCS::WKT2_TYPE)) {
3099
6
        if (axisCount == 2) {
3100
1
            if (axisList[0]->unit() != axisList[1]->unit()) {
3101
0
                emitRecoverableWarning(
3102
0
                    "All axis of a CartesianCS must have the same unit");
3103
0
            }
3104
1
            return CartesianCS::create(csMap, axisList[0], axisList[1],
3105
1
                                       /* enforceSameUnit = */ false);
3106
5
        } else if (axisCount == 3) {
3107
0
            if (axisList[0]->unit() != axisList[1]->unit() ||
3108
0
                axisList[0]->unit() != axisList[2]->unit()) {
3109
0
                emitRecoverableWarning(
3110
0
                    "All axis of a CartesianCS must have the same unit");
3111
0
            }
3112
0
            return CartesianCS::create(csMap, axisList[0], axisList[1],
3113
0
                                       axisList[2],
3114
0
                                       /* enforceSameUnit = */ false);
3115
0
        }
3116
210
    } else if (ci_equal(csType, AffineCS::WKT2_TYPE)) {
3117
0
        if (axisCount == 2) {
3118
0
            return AffineCS::create(csMap, axisList[0], axisList[1]);
3119
0
        } else if (axisCount == 3) {
3120
0
            return AffineCS::create(csMap, axisList[0], axisList[1],
3121
0
                                    axisList[2]);
3122
0
        }
3123
210
    } else if (ci_equal(csType, VerticalCS::WKT2_TYPE)) {
3124
77
        if (axisCount == 1) {
3125
76
            return VerticalCS::create(csMap, axisList[0]);
3126
76
        }
3127
133
    } else if (ci_equal(csType, SphericalCS::WKT2_TYPE)) {
3128
0
        if (axisCount == 2) {
3129
            // Extension to ISO19111 to support (planet)-ocentric CS with
3130
            // geocentric latitude
3131
0
            return SphericalCS::create(csMap, axisList[0], axisList[1]);
3132
0
        } else if (axisCount == 3) {
3133
0
            return SphericalCS::create(csMap, axisList[0], axisList[1],
3134
0
                                       axisList[2]);
3135
0
        }
3136
133
    } else if (ci_equal(csType, OrdinalCS::WKT2_TYPE)) { // WKT2-2019
3137
0
        return OrdinalCS::create(csMap, axisList);
3138
133
    } else if (ci_equal(csType, ParametricCS::WKT2_TYPE)) {
3139
0
        if (axisCount == 1) {
3140
0
            return ParametricCS::create(csMap, axisList[0]);
3141
0
        }
3142
133
    } else if (ci_equal(csType, TemporalCS::WKT2_2015_TYPE)) {
3143
0
        if (axisCount == 1) {
3144
0
            if (isNull(
3145
0
                    parentNode->GP()->lookForChild(WKTConstants::TIMEUNIT)) &&
3146
0
                isNull(parentNode->GP()->lookForChild(WKTConstants::UNIT))) {
3147
0
                return DateTimeTemporalCS::create(csMap, axisList[0]);
3148
0
            } else {
3149
                // Default to TemporalMeasureCS
3150
                // TemporalCount could also be possible
3151
0
                return TemporalMeasureCS::create(csMap, axisList[0]);
3152
0
            }
3153
0
        }
3154
133
    } else if (ci_equal(csType, DateTimeTemporalCS::WKT2_2019_TYPE)) {
3155
0
        if (axisCount == 1) {
3156
0
            return DateTimeTemporalCS::create(csMap, axisList[0]);
3157
0
        }
3158
133
    } else if (ci_equal(csType, TemporalCountCS::WKT2_2019_TYPE)) {
3159
0
        if (axisCount == 1) {
3160
0
            return TemporalCountCS::create(csMap, axisList[0]);
3161
0
        }
3162
133
    } else if (ci_equal(csType, TemporalMeasureCS::WKT2_2019_TYPE)) {
3163
0
        if (axisCount == 1) {
3164
0
            return TemporalMeasureCS::create(csMap, axisList[0]);
3165
0
        }
3166
133
    } else {
3167
133
        throw ParsingException(concat("unhandled CS type: ", csType));
3168
133
    }
3169
6
    throw buildParsingExceptionInvalidAxisCount(csType);
3170
216
}
3171
3172
// ---------------------------------------------------------------------------
3173
3174
std::string
3175
2.63k
WKTParser::Private::getExtensionProj4(const WKTNode::Private *nodeP) {
3176
2.63k
    auto &extensionNode = nodeP->lookForChild(WKTConstants::EXTENSION);
3177
2.63k
    const auto &extensionChildren = extensionNode->GP()->children();
3178
2.63k
    if (extensionChildren.size() == 2) {
3179
190
        if (ci_equal(stripQuotes(extensionChildren[0]), "PROJ4")) {
3180
179
            return stripQuotes(extensionChildren[1]);
3181
179
        }
3182
190
    }
3183
2.45k
    return std::string();
3184
2.63k
}
3185
3186
// ---------------------------------------------------------------------------
3187
3188
void WKTParser::Private::addExtensionProj4ToProp(const WKTNode::Private *nodeP,
3189
1.78k
                                                 PropertyMap &props) {
3190
1.78k
    const auto extensionProj4(getExtensionProj4(nodeP));
3191
1.78k
    if (!extensionProj4.empty()) {
3192
50
        props.set("EXTENSION_PROJ4", extensionProj4);
3193
50
    }
3194
1.78k
}
3195
3196
// ---------------------------------------------------------------------------
3197
3198
GeodeticCRSNNPtr
3199
WKTParser::Private::buildGeodeticCRS(const WKTNodeNNPtr &node,
3200
1.32k
                                     bool forceGeocentricIfNoCs) {
3201
1.32k
    const auto *nodeP = node->GP();
3202
1.32k
    auto &datumNode = nodeP->lookForChild(
3203
1.32k
        WKTConstants::DATUM, WKTConstants::GEODETICDATUM, WKTConstants::TRF);
3204
1.32k
    auto &ensembleNode = nodeP->lookForChild(WKTConstants::ENSEMBLE);
3205
1.32k
    if (isNull(datumNode) && isNull(ensembleNode)) {
3206
14
        throw ParsingException("Missing DATUM or ENSEMBLE node");
3207
14
    }
3208
3209
    // Do that now so that esriStyle_ can be set before buildPrimeMeridian()
3210
1.31k
    auto props = buildProperties(node);
3211
3212
1.31k
    auto &dynamicNode = nodeP->lookForChild(WKTConstants::DYNAMIC);
3213
3214
1.31k
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
3215
1.31k
    const auto &nodeName = nodeP->value();
3216
1.31k
    if (isNull(csNode) && !ci_equal(nodeName, WKTConstants::GEOGCS) &&
3217
91
        !ci_equal(nodeName, WKTConstants::GEOCCS) &&
3218
3
        !ci_equal(nodeName, WKTConstants::BASEGEODCRS) &&
3219
3
        !ci_equal(nodeName, WKTConstants::BASEGEOGCRS)) {
3220
3
        ThrowMissing(WKTConstants::CS_);
3221
3
    }
3222
3223
1.31k
    auto &primeMeridianNode =
3224
1.31k
        nodeP->lookForChild(WKTConstants::PRIMEM, WKTConstants::PRIMEMERIDIAN);
3225
1.31k
    if (isNull(primeMeridianNode)) {
3226
        // PRIMEM is required in WKT1
3227
980
        if (ci_equal(nodeName, WKTConstants::GEOGCS) ||
3228
980
            ci_equal(nodeName, WKTConstants::GEOCCS)) {
3229
980
            emitRecoverableWarning(nodeName + " should have a PRIMEM node");
3230
980
        }
3231
980
    }
3232
3233
1.31k
    auto angularUnit =
3234
1.31k
        buildUnitInSubNode(node, ci_equal(nodeName, WKTConstants::GEOGCS)
3235
1.31k
                                     ? UnitOfMeasure::Type::ANGULAR
3236
1.31k
                                     : UnitOfMeasure::Type::UNKNOWN);
3237
1.31k
    if (angularUnit.type() != UnitOfMeasure::Type::ANGULAR) {
3238
775
        angularUnit = UnitOfMeasure::NONE;
3239
775
    }
3240
3241
1.31k
    auto primeMeridian =
3242
1.31k
        !isNull(primeMeridianNode)
3243
1.31k
            ? buildPrimeMeridian(primeMeridianNode, angularUnit)
3244
1.31k
            : PrimeMeridian::GREENWICH;
3245
1.31k
    if (angularUnit == UnitOfMeasure::NONE) {
3246
775
        angularUnit = primeMeridian->longitude().unit();
3247
775
    }
3248
3249
1.31k
    addExtensionProj4ToProp(nodeP, props);
3250
3251
    // No explicit AXIS node ? (WKT1)
3252
1.31k
    if (isNull(nodeP->lookForChild(WKTConstants::AXIS))) {
3253
1.24k
        props.set("IMPLICIT_CS", true);
3254
1.24k
    }
3255
3256
1.31k
    const std::string crsName = stripQuotes(nodeP->children()[0]);
3257
1.31k
    if (esriStyle_ && dbContext_) {
3258
342
        std::string outTableName;
3259
342
        std::string authNameFromAlias;
3260
342
        std::string codeFromAlias;
3261
342
        auto authFactory =
3262
342
            AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string());
3263
342
        auto officialName = authFactory->getOfficialNameFromAlias(
3264
342
            crsName, "geodetic_crs", "ESRI", false, outTableName,
3265
342
            authNameFromAlias, codeFromAlias);
3266
342
        if (!officialName.empty()) {
3267
274
            props.set(IdentifiedObject::NAME_KEY, officialName);
3268
274
        }
3269
342
    }
3270
3271
1.31k
    auto datum =
3272
1.31k
        !isNull(datumNode)
3273
1.31k
            ? buildGeodeticReferenceFrame(datumNode, primeMeridian, dynamicNode)
3274
1.11k
                  .as_nullable()
3275
1.31k
            : nullptr;
3276
1.31k
    auto datumEnsemble =
3277
1.31k
        !isNull(ensembleNode)
3278
1.31k
            ? buildDatumEnsemble(ensembleNode, primeMeridian, true)
3279
171
                  .as_nullable()
3280
1.31k
            : nullptr;
3281
1.31k
    auto cs = buildCS(csNode, node, angularUnit);
3282
3283
    // If there's no CS[] node, typically for a BASEGEODCRS of a projected CRS,
3284
    // in a few rare cases, this might be a Geocentric CRS, and thus a
3285
    // Cartesian CS, and not the ellipsoidalCS we assumed above. The only way
3286
    // to figure that is to resolve the CRS from its code...
3287
1.31k
    if (isNull(csNode) && dbContext_ &&
3288
918
        ci_equal(nodeName, WKTConstants::BASEGEODCRS)) {
3289
0
        const auto &nodeChildren = nodeP->children();
3290
0
        for (const auto &subNode : nodeChildren) {
3291
0
            const auto &subNodeName(subNode->GP()->value());
3292
0
            if (ci_equal(subNodeName, WKTConstants::ID) ||
3293
0
                ci_equal(subNodeName, WKTConstants::AUTHORITY)) {
3294
0
                auto id = buildId(node, subNode, true, false);
3295
0
                if (id) {
3296
0
                    try {
3297
0
                        auto authFactory = AuthorityFactory::create(
3298
0
                            NN_NO_CHECK(dbContext_), *id->codeSpace());
3299
0
                        auto dbCRS = authFactory->createGeodeticCRS(id->code());
3300
0
                        cs = dbCRS->coordinateSystem();
3301
0
                    } catch (const util::Exception &) {
3302
0
                    }
3303
0
                }
3304
0
            }
3305
0
        }
3306
0
    }
3307
1.31k
    if (forceGeocentricIfNoCs && isNull(csNode) &&
3308
0
        ci_equal(nodeName, WKTConstants::BASEGEODCRS)) {
3309
0
        cs = cs::CartesianCS::createGeocentric(UnitOfMeasure::METRE);
3310
0
    }
3311
3312
1.31k
    auto ellipsoidalCS = nn_dynamic_pointer_cast<EllipsoidalCS>(cs);
3313
1.31k
    if (ellipsoidalCS) {
3314
991
        if (ci_equal(nodeName, WKTConstants::GEOCCS)) {
3315
0
            throw ParsingException("ellipsoidal CS not expected in GEOCCS");
3316
0
        }
3317
991
        try {
3318
991
            auto crs = GeographicCRS::create(props, datum, datumEnsemble,
3319
991
                                             NN_NO_CHECK(ellipsoidalCS));
3320
            // In case of missing CS node, or to check it, query the coordinate
3321
            // system from the DB if possible (typically for the baseCRS of a
3322
            // ProjectedCRS)
3323
991
            if (!crs->identifiers().empty() && dbContext_) {
3324
5
                GeographicCRSPtr dbCRS;
3325
5
                try {
3326
5
                    const auto &id = crs->identifiers()[0];
3327
5
                    auto authFactory = AuthorityFactory::create(
3328
5
                        NN_NO_CHECK(dbContext_), *id->codeSpace());
3329
5
                    dbCRS = authFactory->createGeographicCRS(id->code())
3330
5
                                .as_nullable();
3331
5
                } catch (const util::Exception &) {
3332
5
                }
3333
5
                if (dbCRS &&
3334
0
                    (!isNull(csNode) ||
3335
0
                     node->countChildrenOfName(WKTConstants::AXIS) != 0) &&
3336
0
                    !ellipsoidalCS->_isEquivalentTo(
3337
0
                        dbCRS->coordinateSystem().get(),
3338
0
                        util::IComparable::Criterion::EQUIVALENT)) {
3339
0
                    if (unsetIdentifiersIfIncompatibleDef_) {
3340
0
                        emitRecoverableWarning(
3341
0
                            "Coordinate system of GeographicCRS in the WKT "
3342
0
                            "definition is different from the one of the "
3343
0
                            "authority. Unsetting the identifier to avoid "
3344
0
                            "confusion");
3345
0
                        props.unset(Identifier::CODESPACE_KEY);
3346
0
                        props.unset(Identifier::AUTHORITY_KEY);
3347
0
                        props.unset(IdentifiedObject::IDENTIFIERS_KEY);
3348
0
                    }
3349
0
                    crs = GeographicCRS::create(props, datum, datumEnsemble,
3350
0
                                                NN_NO_CHECK(ellipsoidalCS));
3351
5
                } else if (dbCRS) {
3352
0
                    auto csFromDB = dbCRS->coordinateSystem();
3353
0
                    auto csFromDBAltered = csFromDB;
3354
0
                    if (!isNull(nodeP->lookForChild(WKTConstants::UNIT))) {
3355
0
                        csFromDBAltered =
3356
0
                            csFromDB->alterAngularUnit(angularUnit);
3357
0
                        if (unsetIdentifiersIfIncompatibleDef_ &&
3358
0
                            !csFromDBAltered->_isEquivalentTo(
3359
0
                                csFromDB.get(),
3360
0
                                util::IComparable::Criterion::EQUIVALENT)) {
3361
0
                            emitRecoverableWarning(
3362
0
                                "Coordinate system of GeographicCRS in the WKT "
3363
0
                                "definition is different from the one of the "
3364
0
                                "authority. Unsetting the identifier to avoid "
3365
0
                                "confusion");
3366
0
                            props.unset(Identifier::CODESPACE_KEY);
3367
0
                            props.unset(Identifier::AUTHORITY_KEY);
3368
0
                            props.unset(IdentifiedObject::IDENTIFIERS_KEY);
3369
0
                        }
3370
0
                    }
3371
0
                    crs = GeographicCRS::create(props, datum, datumEnsemble,
3372
0
                                                csFromDBAltered);
3373
0
                }
3374
5
            }
3375
991
            return crs;
3376
991
        } catch (const util::Exception &e) {
3377
0
            throw ParsingException(std::string("buildGeodeticCRS: ") +
3378
0
                                   e.what());
3379
0
        }
3380
991
    } else if (ci_equal(nodeName, WKTConstants::GEOGCRS) ||
3381
43
               ci_equal(nodeName, WKTConstants::GEOGRAPHICCRS) ||
3382
43
               ci_equal(nodeName, WKTConstants::BASEGEOGCRS)) {
3383
        // This is a WKT2-2019 GeographicCRS. An ellipsoidal CS is expected
3384
0
        throw ParsingException(concat("ellipsoidal CS expected, but found ",
3385
0
                                      cs->getWKT2Type(true)));
3386
0
    }
3387
3388
319
    auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs);
3389
319
    if (cartesianCS) {
3390
43
        if (cartesianCS->axisList().size() != 3) {
3391
1
            throw ParsingException(
3392
1
                "Cartesian CS for a GeodeticCRS should have 3 axis");
3393
1
        }
3394
42
        try {
3395
42
            return GeodeticCRS::create(props, datum, datumEnsemble,
3396
42
                                       NN_NO_CHECK(cartesianCS));
3397
42
        } catch (const util::Exception &e) {
3398
0
            throw ParsingException(std::string("buildGeodeticCRS: ") +
3399
0
                                   e.what());
3400
0
        }
3401
42
    }
3402
3403
276
    auto sphericalCS = nn_dynamic_pointer_cast<SphericalCS>(cs);
3404
276
    if (sphericalCS) {
3405
0
        try {
3406
0
            return GeodeticCRS::create(props, datum, datumEnsemble,
3407
0
                                       NN_NO_CHECK(sphericalCS));
3408
0
        } catch (const util::Exception &e) {
3409
0
            throw ParsingException(std::string("buildGeodeticCRS: ") +
3410
0
                                   e.what());
3411
0
        }
3412
0
    }
3413
3414
276
    throw ParsingException(
3415
276
        concat("unhandled CS type: ", cs->getWKT2Type(true)));
3416
276
}
3417
3418
// ---------------------------------------------------------------------------
3419
3420
0
CRSNNPtr WKTParser::Private::buildDerivedGeodeticCRS(const WKTNodeNNPtr &node) {
3421
0
    const auto *nodeP = node->GP();
3422
0
    auto &baseGeodCRSNode = nodeP->lookForChild(WKTConstants::BASEGEODCRS,
3423
0
                                                WKTConstants::BASEGEOGCRS);
3424
    // given the constraints enforced on calling code path
3425
0
    assert(!isNull(baseGeodCRSNode));
3426
3427
0
    auto &derivingConversionNode =
3428
0
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
3429
0
    if (isNull(derivingConversionNode)) {
3430
0
        ThrowMissing(WKTConstants::DERIVINGCONVERSION);
3431
0
    }
3432
0
    auto derivingConversion = buildConversion(
3433
0
        derivingConversionNode, UnitOfMeasure::NONE, UnitOfMeasure::NONE);
3434
3435
0
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
3436
0
    if (isNull(csNode)) {
3437
0
        ThrowMissing(WKTConstants::CS_);
3438
0
    }
3439
0
    auto cs = buildCS(csNode, node, UnitOfMeasure::NONE);
3440
3441
0
    bool forceGeocentricIfNoCs = false;
3442
0
    auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs);
3443
0
    if (cartesianCS) {
3444
0
        if (cartesianCS->axisList().size() != 3) {
3445
0
            throw ParsingException(
3446
0
                "Cartesian CS for a GeodeticCRS should have 3 axis");
3447
0
        }
3448
0
        const int methodCode = derivingConversion->method()->getEPSGCode();
3449
0
        if ((methodCode == EPSG_CODE_METHOD_COORDINATE_FRAME_GEOCENTRIC ||
3450
0
             methodCode ==
3451
0
                 EPSG_CODE_METHOD_COORDINATE_FRAME_FULL_MATRIX_GEOCENTRIC ||
3452
0
             methodCode == EPSG_CODE_METHOD_POSITION_VECTOR_GEOCENTRIC ||
3453
0
             methodCode == EPSG_CODE_METHOD_GEOCENTRIC_TRANSLATION_GEOCENTRIC ||
3454
0
             methodCode ==
3455
0
                 EPSG_CODE_METHOD_TIME_DEPENDENT_POSITION_VECTOR_GEOCENTRIC ||
3456
0
             methodCode ==
3457
0
                 EPSG_CODE_METHOD_TIME_DEPENDENT_COORDINATE_FRAME_GEOCENTRIC) &&
3458
0
            nodeP->lookForChild(WKTConstants::BASEGEODCRS) != nullptr) {
3459
0
            forceGeocentricIfNoCs = true;
3460
0
        }
3461
0
    }
3462
0
    auto baseGeodCRS = buildGeodeticCRS(baseGeodCRSNode, forceGeocentricIfNoCs);
3463
3464
0
    auto ellipsoidalCS = nn_dynamic_pointer_cast<EllipsoidalCS>(cs);
3465
0
    if (ellipsoidalCS) {
3466
3467
0
        if (ellipsoidalCS->axisList().size() == 3 &&
3468
0
            baseGeodCRS->coordinateSystem()->axisList().size() == 2) {
3469
0
            baseGeodCRS =
3470
0
                NN_NO_CHECK(util::nn_dynamic_pointer_cast<GeodeticCRS>(
3471
0
                    baseGeodCRS->promoteTo3D(std::string(), dbContext_)));
3472
0
        }
3473
3474
0
        return DerivedGeographicCRS::create(buildProperties(node), baseGeodCRS,
3475
0
                                            derivingConversion,
3476
0
                                            NN_NO_CHECK(ellipsoidalCS));
3477
0
    } else if (ci_equal(nodeP->value(), WKTConstants::GEOGCRS)) {
3478
        // This is a WKT2-2019 GeographicCRS. An ellipsoidal CS is expected
3479
0
        throw ParsingException(concat("ellipsoidal CS expected, but found ",
3480
0
                                      cs->getWKT2Type(true)));
3481
0
    }
3482
3483
0
    if (cartesianCS) {
3484
0
        return DerivedGeodeticCRS::create(buildProperties(node), baseGeodCRS,
3485
0
                                          derivingConversion,
3486
0
                                          NN_NO_CHECK(cartesianCS));
3487
0
    }
3488
3489
0
    auto sphericalCS = nn_dynamic_pointer_cast<SphericalCS>(cs);
3490
0
    if (sphericalCS) {
3491
0
        return DerivedGeodeticCRS::create(buildProperties(node), baseGeodCRS,
3492
0
                                          derivingConversion,
3493
0
                                          NN_NO_CHECK(sphericalCS));
3494
0
    }
3495
3496
0
    throw ParsingException(
3497
0
        concat("unhandled CS type: ", cs->getWKT2Type(true)));
3498
0
}
3499
3500
// ---------------------------------------------------------------------------
3501
3502
UnitOfMeasure WKTParser::Private::guessUnitForParameter(
3503
    const std::string &paramName, const UnitOfMeasure &defaultLinearUnit,
3504
3.36k
    const UnitOfMeasure &defaultAngularUnit) {
3505
3.36k
    UnitOfMeasure unit;
3506
    // scale must be first because of 'Scale factor on pseudo standard parallel'
3507
3.36k
    if (ci_find(paramName, "scale") != std::string::npos ||
3508
3.29k
        ci_find(paramName, "scaling factor") != std::string::npos) {
3509
74
        unit = UnitOfMeasure::SCALE_UNITY;
3510
3.29k
    } else if (ci_find(paramName, "latitude") != std::string::npos ||
3511
3.02k
               ci_find(paramName, "longitude") != std::string::npos ||
3512
2.67k
               ci_find(paramName, "meridian") != std::string::npos ||
3513
2.65k
               ci_find(paramName, "parallel") != std::string::npos ||
3514
2.63k
               ci_find(paramName, "azimuth") != std::string::npos ||
3515
2.60k
               ci_find(paramName, "angle") != std::string::npos ||
3516
2.58k
               ci_find(paramName, "heading") != std::string::npos ||
3517
2.52k
               ci_find(paramName, "rotation") != std::string::npos) {
3518
827
        unit = defaultAngularUnit;
3519
2.46k
    } else if (ci_find(paramName, "easting") != std::string::npos ||
3520
2.14k
               ci_find(paramName, "northing") != std::string::npos ||
3521
1.77k
               ci_find(paramName, "height") != std::string::npos) {
3522
737
        unit = defaultLinearUnit;
3523
737
    }
3524
3.36k
    return unit;
3525
3.36k
}
3526
3527
// ---------------------------------------------------------------------------
3528
3529
static bool
3530
589
isEPSGCodeForInterpolationParameter(const OperationParameterNNPtr &parameter) {
3531
589
    const auto &name = parameter->nameStr();
3532
589
    const auto epsgCode = parameter->getEPSGCode();
3533
589
    return name == EPSG_NAME_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS ||
3534
583
           epsgCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_INTERPOLATION_CRS ||
3535
535
           name == EPSG_NAME_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS ||
3536
535
           epsgCode == EPSG_CODE_PARAMETER_EPSG_CODE_FOR_HORIZONTAL_CRS;
3537
589
}
3538
3539
// ---------------------------------------------------------------------------
3540
3541
360
static bool isIntegerParameter(const OperationParameterNNPtr &parameter) {
3542
360
    return isEPSGCodeForInterpolationParameter(parameter);
3543
360
}
3544
3545
// ---------------------------------------------------------------------------
3546
3547
void WKTParser::Private::consumeParameters(
3548
    const WKTNodeNNPtr &node, bool isAbridged,
3549
    std::vector<OperationParameterNNPtr> &parameters,
3550
    std::vector<ParameterValueNNPtr> &values,
3551
    const UnitOfMeasure &defaultLinearUnit,
3552
355
    const UnitOfMeasure &defaultAngularUnit) {
3553
2.40k
    for (const auto &childNode : node->GP()->children()) {
3554
2.40k
        const auto &childNodeChildren = childNode->GP()->children();
3555
2.40k
        if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) {
3556
548
            if (childNodeChildren.size() < 2) {
3557
10
                ThrowNotEnoughChildren(childNode->GP()->value());
3558
10
            }
3559
538
            parameters.push_back(
3560
538
                OperationParameter::create(buildProperties(childNode)));
3561
538
            const auto &paramValue = childNodeChildren[1]->GP()->value();
3562
538
            if (!paramValue.empty() && paramValue[0] == '"') {
3563
155
                values.push_back(
3564
155
                    ParameterValue::create(stripQuotes(childNodeChildren[1])));
3565
383
            } else {
3566
383
                try {
3567
383
                    double val = asDouble(childNodeChildren[1]);
3568
383
                    auto unit = buildUnitInSubNode(childNode);
3569
383
                    if (unit == UnitOfMeasure::NONE) {
3570
360
                        const auto &paramName =
3571
360
                            childNodeChildren[0]->GP()->value();
3572
360
                        unit = guessUnitForParameter(
3573
360
                            paramName, defaultLinearUnit, defaultAngularUnit);
3574
360
                    }
3575
3576
383
                    if (isAbridged) {
3577
0
                        const auto &paramName = parameters.back()->nameStr();
3578
0
                        int paramEPSGCode = 0;
3579
0
                        const auto &paramIds = parameters.back()->identifiers();
3580
0
                        if (paramIds.size() == 1 &&
3581
0
                            ci_equal(*(paramIds[0]->codeSpace()),
3582
0
                                     Identifier::EPSG)) {
3583
0
                            paramEPSGCode = ::atoi(paramIds[0]->code().c_str());
3584
0
                        }
3585
0
                        const common::UnitOfMeasure *pUnit = nullptr;
3586
0
                        if (OperationParameterValue::convertFromAbridged(
3587
0
                                paramName, val, pUnit, paramEPSGCode)) {
3588
0
                            unit = *pUnit;
3589
0
                            parameters.back() = OperationParameter::create(
3590
0
                                buildProperties(childNode)
3591
0
                                    .set(Identifier::CODESPACE_KEY,
3592
0
                                         Identifier::EPSG)
3593
0
                                    .set(Identifier::CODE_KEY, paramEPSGCode));
3594
0
                        }
3595
0
                    }
3596
3597
383
                    if (isIntegerParameter(parameters.back())) {
3598
47
                        values.push_back(ParameterValue::create(
3599
47
                            std::stoi(childNodeChildren[1]->GP()->value())));
3600
336
                    } else {
3601
336
                        values.push_back(
3602
336
                            ParameterValue::create(Measure(val, unit)));
3603
336
                    }
3604
383
                } catch (const std::exception &) {
3605
28
                    throw ParsingException(concat(
3606
28
                        "unhandled parameter value type : ", paramValue));
3607
28
                }
3608
383
            }
3609
1.85k
        } else if (ci_equal(childNode->GP()->value(),
3610
1.85k
                            WKTConstants::PARAMETERFILE)) {
3611
55
            if (childNodeChildren.size() < 2) {
3612
3
                ThrowNotEnoughChildren(childNode->GP()->value());
3613
3
            }
3614
52
            parameters.push_back(
3615
52
                OperationParameter::create(buildProperties(childNode)));
3616
52
            values.push_back(ParameterValue::createFilename(
3617
52
                stripQuotes(childNodeChildren[1])));
3618
52
        }
3619
2.40k
    }
3620
355
}
3621
3622
// ---------------------------------------------------------------------------
3623
3624
static CRSPtr dealWithEPSGCodeForInterpolationCRSParameter(
3625
    DatabaseContextPtr &dbContext,
3626
    std::vector<OperationParameterNNPtr> &parameters,
3627
    std::vector<ParameterValueNNPtr> &values);
3628
3629
ConversionNNPtr
3630
WKTParser::Private::buildConversion(const WKTNodeNNPtr &node,
3631
                                    const UnitOfMeasure &defaultLinearUnit,
3632
363
                                    const UnitOfMeasure &defaultAngularUnit) {
3633
363
    auto &methodNode = node->GP()->lookForChild(WKTConstants::METHOD,
3634
363
                                                WKTConstants::PROJECTION);
3635
363
    if (isNull(methodNode)) {
3636
7
        ThrowMissing(WKTConstants::METHOD);
3637
7
    }
3638
356
    if (methodNode->GP()->childrenSize() == 0) {
3639
1
        ThrowNotEnoughChildren(WKTConstants::METHOD);
3640
1
    }
3641
3642
355
    std::vector<OperationParameterNNPtr> parameters;
3643
355
    std::vector<ParameterValueNNPtr> values;
3644
355
    consumeParameters(node, false, parameters, values, defaultLinearUnit,
3645
355
                      defaultAngularUnit);
3646
3647
355
    auto interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter(
3648
355
        dbContext_, parameters, values);
3649
3650
355
    auto &convProps = buildProperties(node);
3651
355
    auto &methodProps = buildProperties(methodNode);
3652
355
    std::string convName;
3653
355
    std::string methodName;
3654
355
    if (convProps.getStringValue(IdentifiedObject::NAME_KEY, convName) &&
3655
313
        methodProps.getStringValue(IdentifiedObject::NAME_KEY, methodName) &&
3656
313
        starts_with(convName, "Inverse of ") &&
3657
60
        starts_with(methodName, "Inverse of ")) {
3658
3659
50
        auto &invConvProps = buildProperties(node, true);
3660
50
        auto &invMethodProps = buildProperties(methodNode, true);
3661
50
        auto conv = NN_NO_CHECK(util::nn_dynamic_pointer_cast<Conversion>(
3662
50
            Conversion::create(invConvProps, invMethodProps, parameters, values)
3663
50
                ->inverse()));
3664
50
        if (interpolationCRS)
3665
0
            conv->setInterpolationCRS(interpolationCRS);
3666
50
        return conv;
3667
50
    }
3668
305
    auto conv = Conversion::create(convProps, methodProps, parameters, values);
3669
305
    if (interpolationCRS)
3670
0
        conv->setInterpolationCRS(interpolationCRS);
3671
305
    return conv;
3672
355
}
3673
3674
// ---------------------------------------------------------------------------
3675
3676
static CRSPtr dealWithEPSGCodeForInterpolationCRSParameter(
3677
    DatabaseContextPtr &dbContext,
3678
    std::vector<OperationParameterNNPtr> &parameters,
3679
314
    std::vector<ParameterValueNNPtr> &values) {
3680
    // Transform EPSG hacky PARAMETER["EPSG code for Interpolation CRS",
3681
    // crs_epsg_code] into proper interpolation CRS
3682
314
    if (dbContext != nullptr) {
3683
505
        for (size_t i = 0; i < parameters.size(); ++i) {
3684
229
            if (isEPSGCodeForInterpolationParameter(parameters[i])) {
3685
7
                const int code = values[i]->integerValue();
3686
7
                try {
3687
7
                    auto authFactory = AuthorityFactory::create(
3688
7
                        NN_NO_CHECK(dbContext), Identifier::EPSG);
3689
7
                    auto interpolationCRS =
3690
7
                        authFactory
3691
7
                            ->createGeographicCRS(internal::toString(code))
3692
7
                            .as_nullable();
3693
7
                    parameters.erase(parameters.begin() + i);
3694
7
                    values.erase(values.begin() + i);
3695
7
                    return interpolationCRS;
3696
7
                } catch (const util::Exception &) {
3697
7
                }
3698
7
            }
3699
229
        }
3700
276
    }
3701
314
    return nullptr;
3702
314
}
3703
3704
// ---------------------------------------------------------------------------
3705
3706
TransformationNNPtr
3707
11
WKTParser::Private::buildCoordinateOperation(const WKTNodeNNPtr &node) {
3708
11
    const auto *nodeP = node->GP();
3709
11
    auto &methodNode = nodeP->lookForChild(WKTConstants::METHOD);
3710
11
    if (isNull(methodNode)) {
3711
5
        ThrowMissing(WKTConstants::METHOD);
3712
5
    }
3713
6
    if (methodNode->GP()->childrenSize() == 0) {
3714
2
        ThrowNotEnoughChildren(WKTConstants::METHOD);
3715
2
    }
3716
3717
4
    auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS);
3718
4
    if (/*isNull(sourceCRSNode) ||*/ sourceCRSNode->GP()->childrenSize() != 1) {
3719
4
        ThrowMissing(WKTConstants::SOURCECRS);
3720
4
    }
3721
0
    auto sourceCRS = buildCRS(sourceCRSNode->GP()->children()[0]);
3722
0
    if (!sourceCRS) {
3723
0
        throw ParsingException("Invalid content in SOURCECRS node");
3724
0
    }
3725
3726
0
    auto &targetCRSNode = nodeP->lookForChild(WKTConstants::TARGETCRS);
3727
0
    if (/*isNull(targetCRSNode) ||*/ targetCRSNode->GP()->childrenSize() != 1) {
3728
0
        ThrowMissing(WKTConstants::TARGETCRS);
3729
0
    }
3730
0
    auto targetCRS = buildCRS(targetCRSNode->GP()->children()[0]);
3731
0
    if (!targetCRS) {
3732
0
        throw ParsingException("Invalid content in TARGETCRS node");
3733
0
    }
3734
3735
0
    auto &interpolationCRSNode =
3736
0
        nodeP->lookForChild(WKTConstants::INTERPOLATIONCRS);
3737
0
    CRSPtr interpolationCRS;
3738
0
    if (/*!isNull(interpolationCRSNode) && */ interpolationCRSNode->GP()
3739
0
            ->childrenSize() == 1) {
3740
0
        interpolationCRS = buildCRS(interpolationCRSNode->GP()->children()[0]);
3741
0
    }
3742
3743
0
    std::vector<OperationParameterNNPtr> parameters;
3744
0
    std::vector<ParameterValueNNPtr> values;
3745
0
    const auto &defaultLinearUnit = UnitOfMeasure::NONE;
3746
0
    const auto &defaultAngularUnit = UnitOfMeasure::NONE;
3747
0
    consumeParameters(node, false, parameters, values, defaultLinearUnit,
3748
0
                      defaultAngularUnit);
3749
3750
0
    if (interpolationCRS == nullptr)
3751
0
        interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter(
3752
0
            dbContext_, parameters, values);
3753
3754
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
3755
0
    auto &accuracyNode = nodeP->lookForChild(WKTConstants::OPERATIONACCURACY);
3756
0
    if (/*!isNull(accuracyNode) && */ accuracyNode->GP()->childrenSize() == 1) {
3757
0
        accuracies.push_back(PositionalAccuracy::create(
3758
0
            stripQuotes(accuracyNode->GP()->children()[0])));
3759
0
    }
3760
3761
0
    return Transformation::create(buildProperties(node), NN_NO_CHECK(sourceCRS),
3762
0
                                  NN_NO_CHECK(targetCRS), interpolationCRS,
3763
0
                                  buildProperties(methodNode), parameters,
3764
0
                                  values, accuracies);
3765
0
}
3766
3767
// ---------------------------------------------------------------------------
3768
3769
PointMotionOperationNNPtr
3770
1
WKTParser::Private::buildPointMotionOperation(const WKTNodeNNPtr &node) {
3771
1
    const auto *nodeP = node->GP();
3772
1
    auto &methodNode = nodeP->lookForChild(WKTConstants::METHOD);
3773
1
    if (isNull(methodNode)) {
3774
1
        ThrowMissing(WKTConstants::METHOD);
3775
1
    }
3776
0
    if (methodNode->GP()->childrenSize() == 0) {
3777
0
        ThrowNotEnoughChildren(WKTConstants::METHOD);
3778
0
    }
3779
3780
0
    auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS);
3781
0
    if (sourceCRSNode->GP()->childrenSize() != 1) {
3782
0
        ThrowMissing(WKTConstants::SOURCECRS);
3783
0
    }
3784
0
    auto sourceCRS = buildCRS(sourceCRSNode->GP()->children()[0]);
3785
0
    if (!sourceCRS) {
3786
0
        throw ParsingException("Invalid content in SOURCECRS node");
3787
0
    }
3788
3789
0
    std::vector<OperationParameterNNPtr> parameters;
3790
0
    std::vector<ParameterValueNNPtr> values;
3791
0
    const auto &defaultLinearUnit = UnitOfMeasure::NONE;
3792
0
    const auto &defaultAngularUnit = UnitOfMeasure::NONE;
3793
0
    consumeParameters(node, false, parameters, values, defaultLinearUnit,
3794
0
                      defaultAngularUnit);
3795
3796
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
3797
0
    auto &accuracyNode = nodeP->lookForChild(WKTConstants::OPERATIONACCURACY);
3798
0
    if (/*!isNull(accuracyNode) && */ accuracyNode->GP()->childrenSize() == 1) {
3799
0
        accuracies.push_back(PositionalAccuracy::create(
3800
0
            stripQuotes(accuracyNode->GP()->children()[0])));
3801
0
    }
3802
3803
0
    return PointMotionOperation::create(
3804
0
        buildProperties(node), NN_NO_CHECK(sourceCRS),
3805
0
        buildProperties(methodNode), parameters, values, accuracies);
3806
0
}
3807
3808
// ---------------------------------------------------------------------------
3809
3810
ConcatenatedOperationNNPtr
3811
5
WKTParser::Private::buildConcatenatedOperation(const WKTNodeNNPtr &node) {
3812
3813
5
    const auto *nodeP = node->GP();
3814
5
    auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS);
3815
5
    if (/*isNull(sourceCRSNode) ||*/ sourceCRSNode->GP()->childrenSize() != 1) {
3816
5
        ThrowMissing(WKTConstants::SOURCECRS);
3817
5
    }
3818
0
    auto sourceCRS = buildCRS(sourceCRSNode->GP()->children()[0]);
3819
0
    if (!sourceCRS) {
3820
0
        throw ParsingException("Invalid content in SOURCECRS node");
3821
0
    }
3822
3823
0
    auto &targetCRSNode = nodeP->lookForChild(WKTConstants::TARGETCRS);
3824
0
    if (/*isNull(targetCRSNode) ||*/ targetCRSNode->GP()->childrenSize() != 1) {
3825
0
        ThrowMissing(WKTConstants::TARGETCRS);
3826
0
    }
3827
0
    auto targetCRS = buildCRS(targetCRSNode->GP()->children()[0]);
3828
0
    if (!targetCRS) {
3829
0
        throw ParsingException("Invalid content in TARGETCRS node");
3830
0
    }
3831
3832
0
    std::vector<CoordinateOperationNNPtr> operations;
3833
0
    for (const auto &childNode : nodeP->children()) {
3834
0
        if (ci_equal(childNode->GP()->value(), WKTConstants::STEP)) {
3835
0
            if (childNode->GP()->childrenSize() != 1) {
3836
0
                throw ParsingException("Invalid content in STEP node");
3837
0
            }
3838
0
            auto op = nn_dynamic_pointer_cast<CoordinateOperation>(
3839
0
                build(childNode->GP()->children()[0]));
3840
0
            if (!op) {
3841
0
                throw ParsingException("Invalid content in STEP node");
3842
0
            }
3843
0
            operations.emplace_back(NN_NO_CHECK(op));
3844
0
        }
3845
0
    }
3846
3847
0
    ConcatenatedOperation::fixSteps(
3848
0
        NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCRS), operations, dbContext_,
3849
0
        /* fixDirectionAllowed = */ true);
3850
3851
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
3852
0
    auto &accuracyNode = nodeP->lookForChild(WKTConstants::OPERATIONACCURACY);
3853
0
    if (/*!isNull(accuracyNode) && */ accuracyNode->GP()->childrenSize() == 1) {
3854
0
        accuracies.push_back(PositionalAccuracy::create(
3855
0
            stripQuotes(accuracyNode->GP()->children()[0])));
3856
0
    }
3857
3858
0
    try {
3859
0
        return ConcatenatedOperation::create(buildProperties(node), operations,
3860
0
                                             accuracies);
3861
0
    } catch (const InvalidOperation &e) {
3862
0
        throw ParsingException(
3863
0
            std::string("Cannot build concatenated operation: ") + e.what());
3864
0
    }
3865
0
}
3866
3867
// ---------------------------------------------------------------------------
3868
3869
bool WKTParser::Private::hasWebMercPROJ4String(
3870
685
    const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode) {
3871
685
    if (projectionNode->GP()->childrenSize() == 0) {
3872
2
        ThrowNotEnoughChildren(WKTConstants::PROJECTION);
3873
2
    }
3874
683
    const std::string wkt1ProjectionName =
3875
683
        stripQuotes(projectionNode->GP()->children()[0]);
3876
3877
683
    auto &extensionNode = projCRSNode->lookForChild(WKTConstants::EXTENSION);
3878
3879
683
    if (metadata::Identifier::isEquivalentName(wkt1ProjectionName.c_str(),
3880
683
                                               "Mercator_1SP") &&
3881
0
        projCRSNode->countChildrenOfName("center_latitude") == 0) {
3882
3883
        // Hack to detect the hacky way of encodign webmerc in GDAL WKT1
3884
        // with a EXTENSION["PROJ4", "+proj=merc +a=6378137 +b=6378137
3885
        // +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m
3886
        // +nadgrids=@null +wktext +no_defs"] node
3887
0
        if (extensionNode && extensionNode->GP()->childrenSize() == 2 &&
3888
0
            ci_equal(stripQuotes(extensionNode->GP()->children()[0]),
3889
0
                     "PROJ4")) {
3890
0
            std::string projString =
3891
0
                stripQuotes(extensionNode->GP()->children()[1]);
3892
0
            if (projString.find("+proj=merc") != std::string::npos &&
3893
0
                projString.find("+a=6378137") != std::string::npos &&
3894
0
                projString.find("+b=6378137") != std::string::npos &&
3895
0
                projString.find("+lon_0=0") != std::string::npos &&
3896
0
                projString.find("+x_0=0") != std::string::npos &&
3897
0
                projString.find("+y_0=0") != std::string::npos &&
3898
0
                projString.find("+nadgrids=@null") != std::string::npos &&
3899
0
                (projString.find("+lat_ts=") == std::string::npos ||
3900
0
                 projString.find("+lat_ts=0") != std::string::npos) &&
3901
0
                (projString.find("+k=") == std::string::npos ||
3902
0
                 projString.find("+k=1") != std::string::npos) &&
3903
0
                (projString.find("+units=") == std::string::npos ||
3904
0
                 projString.find("+units=m") != std::string::npos)) {
3905
0
                return true;
3906
0
            }
3907
0
        }
3908
0
    }
3909
683
    return false;
3910
683
}
3911
3912
// ---------------------------------------------------------------------------
3913
3914
static const MethodMapping *
3915
selectSphericalOrEllipsoidal(const MethodMapping *mapping,
3916
4.55k
                             const GeodeticCRSNNPtr &baseGeodCRS) {
3917
4.55k
    if (mapping->epsg_code ==
3918
4.55k
            EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL ||
3919
4.55k
        mapping->epsg_code == EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA) {
3920
131
        mapping = getMapping(
3921
131
            baseGeodCRS->ellipsoid()->isSphere()
3922
131
                ? EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA_SPHERICAL
3923
131
                : EPSG_CODE_METHOD_LAMBERT_CYLINDRICAL_EQUAL_AREA);
3924
4.41k
    } else if (mapping->epsg_code ==
3925
4.41k
                   EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL ||
3926
4.41k
               mapping->epsg_code ==
3927
4.41k
                   EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA) {
3928
204
        mapping = getMapping(
3929
204
            baseGeodCRS->ellipsoid()->isSphere()
3930
204
                ? EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA_SPHERICAL
3931
204
                : EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA);
3932
4.21k
    } else if (mapping->epsg_code ==
3933
4.21k
                   EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL ||
3934
4.21k
               mapping->epsg_code == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL) {
3935
59
        mapping =
3936
59
            getMapping(baseGeodCRS->ellipsoid()->isSphere()
3937
59
                           ? EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL_SPHERICAL
3938
59
                           : EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL);
3939
59
    }
3940
4.55k
    return mapping;
3941
4.55k
}
3942
3943
// ---------------------------------------------------------------------------
3944
3945
const ESRIMethodMapping *WKTParser::Private::getESRIMapping(
3946
    const WKTNodeNNPtr &projCRSNode, const WKTNodeNNPtr &projectionNode,
3947
913
    std::map<std::string, std::string, ci_less_struct> &mapParamNameToValue) {
3948
913
    const std::string esriProjectionName =
3949
913
        stripQuotes(projectionNode->GP()->children()[0]);
3950
3951
    // Lambert_Conformal_Conic or Krovak may map to different WKT2 methods
3952
    // depending
3953
    // on the parameters / their values
3954
913
    const auto esriMappings = getMappingsFromESRI(esriProjectionName);
3955
913
    if (esriMappings.empty()) {
3956
388
        return nullptr;
3957
388
    }
3958
3959
    // Build a map of present parameters
3960
4.60k
    for (const auto &childNode : projCRSNode->GP()->children()) {
3961
4.60k
        if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) {
3962
2.17k
            const auto &childNodeChildren = childNode->GP()->children();
3963
2.17k
            if (childNodeChildren.size() < 2) {
3964
9
                ThrowNotEnoughChildren(WKTConstants::PARAMETER);
3965
9
            }
3966
2.16k
            const std::string parameterName(stripQuotes(childNodeChildren[0]));
3967
2.16k
            const auto &paramValue = childNodeChildren[1]->GP()->value();
3968
2.16k
            mapParamNameToValue[parameterName] = paramValue;
3969
2.16k
        }
3970
4.60k
    }
3971
3972
    // Compare parameters present with the ones expected in the mapping
3973
516
    const ESRIMethodMapping *esriMapping = nullptr;
3974
516
    int bestMatchCount = -1;
3975
771
    for (const auto &mapping : esriMappings) {
3976
771
        int matchCount = 0;
3977
771
        int unmatchCount = 0;
3978
5.48k
        for (const auto *param = mapping->params; param->esri_name; ++param) {
3979
4.73k
            auto iter = mapParamNameToValue.find(param->esri_name);
3980
4.73k
            if (iter != mapParamNameToValue.end()) {
3981
1.36k
                if (param->wkt2_name == nullptr) {
3982
31
                    bool ok = true;
3983
31
                    try {
3984
31
                        if (io::asDouble(param->fixed_value) ==
3985
31
                            io::asDouble(iter->second)) {
3986
13
                            matchCount++;
3987
18
                        } else {
3988
18
                            ok = false;
3989
18
                        }
3990
31
                    } catch (const std::exception &) {
3991
2
                        ok = false;
3992
2
                    }
3993
31
                    if (!ok) {
3994
18
                        matchCount = -1;
3995
18
                        break;
3996
18
                    }
3997
1.33k
                } else {
3998
1.33k
                    matchCount++;
3999
1.33k
                }
4000
3.37k
            } else if (param->is_fixed_value) {
4001
113
                mapParamNameToValue[param->esri_name] = param->fixed_value;
4002
3.25k
            } else {
4003
3.25k
                unmatchCount++;
4004
3.25k
            }
4005
4.73k
        }
4006
771
        if (matchCount > bestMatchCount &&
4007
721
            !(maybeEsriStyle_ && unmatchCount >= matchCount)) {
4008
332
            esriMapping = mapping;
4009
332
            bestMatchCount = matchCount;
4010
332
        }
4011
771
    }
4012
4013
516
    return esriMapping;
4014
516
}
4015
4016
// ---------------------------------------------------------------------------
4017
4018
ConversionNNPtr WKTParser::Private::buildProjectionFromESRI(
4019
    const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode,
4020
    const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit,
4021
    const UnitOfMeasure &defaultAngularUnit,
4022
    const ESRIMethodMapping *esriMapping,
4023
329
    std::map<std::string, std::string, ci_less_struct> &mapParamNameToValue) {
4024
329
    std::map<std::string, const char *> mapWKT2NameToESRIName;
4025
1.82k
    for (const auto *param = esriMapping->params; param->esri_name; ++param) {
4026
1.49k
        if (param->wkt2_name) {
4027
1.42k
            mapWKT2NameToESRIName[param->wkt2_name] = param->esri_name;
4028
1.42k
        }
4029
1.49k
    }
4030
4031
329
    const std::string esriProjectionName =
4032
329
        stripQuotes(projectionNode->GP()->children()[0]);
4033
329
    const char *projectionMethodWkt2Name = esriMapping->wkt2_name;
4034
329
    if (ci_equal(esriProjectionName, "Krovak")) {
4035
18
        const std::string projCRSName =
4036
18
            stripQuotes(projCRSNode->GP()->children()[0]);
4037
18
        if (projCRSName.find("_East_North") != std::string::npos) {
4038
0
            projectionMethodWkt2Name = EPSG_NAME_METHOD_KROVAK_NORTH_ORIENTED;
4039
0
        }
4040
18
    }
4041
4042
329
    const auto *wkt2_mapping = getMapping(projectionMethodWkt2Name);
4043
329
    if (ci_equal(esriProjectionName, "Stereographic")) {
4044
19
        try {
4045
19
            const auto iterLatitudeOfOrigin =
4046
19
                mapParamNameToValue.find("Latitude_Of_Origin");
4047
19
            if (iterLatitudeOfOrigin != mapParamNameToValue.end() &&
4048
18
                std::fabs(io::asDouble(iterLatitudeOfOrigin->second)) == 90.0) {
4049
14
                wkt2_mapping =
4050
14
                    getMapping(EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A);
4051
14
            }
4052
19
        } catch (const std::exception &) {
4053
0
        }
4054
19
    }
4055
329
    assert(wkt2_mapping);
4056
4057
329
    wkt2_mapping = selectSphericalOrEllipsoidal(wkt2_mapping, baseGeodCRS);
4058
4059
329
    PropertyMap propertiesMethod;
4060
329
    propertiesMethod.set(IdentifiedObject::NAME_KEY, wkt2_mapping->wkt2_name);
4061
329
    if (wkt2_mapping->epsg_code != 0) {
4062
150
        propertiesMethod.set(Identifier::CODE_KEY, wkt2_mapping->epsg_code);
4063
150
        propertiesMethod.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
4064
150
    }
4065
4066
329
    std::vector<OperationParameterNNPtr> parameters;
4067
329
    std::vector<ParameterValueNNPtr> values;
4068
4069
329
    if (wkt2_mapping->epsg_code == EPSG_CODE_METHOD_EQUIDISTANT_CYLINDRICAL &&
4070
1
        ci_equal(esriProjectionName, "Plate_Carree")) {
4071
        // Add a fixed  Latitude of 1st parallel = 0 so as to have all
4072
        // parameters expected by Equidistant Cylindrical.
4073
1
        mapWKT2NameToESRIName[EPSG_NAME_PARAMETER_LATITUDE_1ST_STD_PARALLEL] =
4074
1
            "Standard_Parallel_1";
4075
1
        mapParamNameToValue["Standard_Parallel_1"] = "0";
4076
328
    } else if ((wkt2_mapping->epsg_code ==
4077
328
                    EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A ||
4078
322
                wkt2_mapping->epsg_code ==
4079
322
                    EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B) &&
4080
6
               !ci_equal(esriProjectionName,
4081
6
                         "Rectified_Skew_Orthomorphic_Natural_Origin") &&
4082
0
               !ci_equal(esriProjectionName,
4083
0
                         "Rectified_Skew_Orthomorphic_Center")) {
4084
        // ESRI WKT lacks the angle to skew grid
4085
        // Take it from the azimuth value
4086
0
        mapWKT2NameToESRIName
4087
0
            [EPSG_NAME_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID] = "Azimuth";
4088
0
    }
4089
4090
1.72k
    for (int i = 0; wkt2_mapping->params[i] != nullptr; i++) {
4091
1.40k
        const auto *paramMapping = wkt2_mapping->params[i];
4092
4093
1.40k
        auto iter = mapWKT2NameToESRIName.find(paramMapping->wkt2_name);
4094
1.40k
        if (iter == mapWKT2NameToESRIName.end()) {
4095
11
            continue;
4096
11
        }
4097
1.39k
        const auto &esriParamName = iter->second;
4098
1.39k
        auto iter2 = mapParamNameToValue.find(esriParamName);
4099
1.39k
        auto mapParamNameToValueEnd = mapParamNameToValue.end();
4100
1.39k
        if (iter2 == mapParamNameToValueEnd) {
4101
            // In case we don't find a direct match, try the aliases
4102
137
            for (iter2 = mapParamNameToValue.begin();
4103
428
                 iter2 != mapParamNameToValueEnd; ++iter2) {
4104
295
                if (areEquivalentParameters(iter2->first, esriParamName)) {
4105
4
                    break;
4106
4
                }
4107
295
            }
4108
137
            if (iter2 == mapParamNameToValueEnd) {
4109
133
                continue;
4110
133
            }
4111
137
        }
4112
4113
1.26k
        PropertyMap propertiesParameter;
4114
1.26k
        propertiesParameter.set(IdentifiedObject::NAME_KEY,
4115
1.26k
                                paramMapping->wkt2_name);
4116
1.26k
        if (paramMapping->epsg_code != 0) {
4117
1.19k
            propertiesParameter.set(Identifier::CODE_KEY,
4118
1.19k
                                    paramMapping->epsg_code);
4119
1.19k
            propertiesParameter.set(Identifier::CODESPACE_KEY,
4120
1.19k
                                    Identifier::EPSG);
4121
1.19k
        }
4122
1.26k
        parameters.push_back(OperationParameter::create(propertiesParameter));
4123
4124
1.26k
        try {
4125
1.26k
            double val = io::asDouble(iter2->second);
4126
1.26k
            auto unit = guessUnitForParameter(
4127
1.26k
                paramMapping->wkt2_name, defaultLinearUnit, defaultAngularUnit);
4128
1.26k
            values.push_back(ParameterValue::create(Measure(val, unit)));
4129
1.26k
        } catch (const std::exception &) {
4130
7
            throw ParsingException(
4131
7
                concat("unhandled parameter value type : ", iter2->second));
4132
7
        }
4133
1.26k
    }
4134
4135
322
    return Conversion::create(
4136
322
               PropertyMap().set(IdentifiedObject::NAME_KEY,
4137
322
                                 esriProjectionName == "Gauss_Kruger"
4138
322
                                     ? "unnnamed (Gauss Kruger)"
4139
322
                                     : "unnamed"),
4140
322
               propertiesMethod, parameters, values)
4141
322
        ->identify();
4142
329
}
4143
4144
// ---------------------------------------------------------------------------
4145
4146
ConversionNNPtr WKTParser::Private::buildProjectionFromESRI(
4147
    const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode,
4148
    const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit,
4149
655
    const UnitOfMeasure &defaultAngularUnit) {
4150
4151
655
    std::map<std::string, std::string, ci_less_struct> mapParamNameToValue;
4152
655
    const auto esriMapping =
4153
655
        getESRIMapping(projCRSNode, projectionNode, mapParamNameToValue);
4154
655
    if (esriMapping == nullptr) {
4155
329
        return buildProjectionStandard(baseGeodCRS, projCRSNode, projectionNode,
4156
329
                                       defaultLinearUnit, defaultAngularUnit);
4157
329
    }
4158
4159
326
    return buildProjectionFromESRI(baseGeodCRS, projCRSNode, projectionNode,
4160
326
                                   defaultLinearUnit, defaultAngularUnit,
4161
326
                                   esriMapping, mapParamNameToValue);
4162
655
}
4163
4164
// ---------------------------------------------------------------------------
4165
4166
ConversionNNPtr WKTParser::Private::buildProjection(
4167
    const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode,
4168
    const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit,
4169
683
    const UnitOfMeasure &defaultAngularUnit) {
4170
683
    if (projectionNode->GP()->childrenSize() == 0) {
4171
0
        ThrowNotEnoughChildren(WKTConstants::PROJECTION);
4172
0
    }
4173
683
    if (esriStyle_ || maybeEsriStyle_) {
4174
655
        return buildProjectionFromESRI(baseGeodCRS, projCRSNode, projectionNode,
4175
655
                                       defaultLinearUnit, defaultAngularUnit);
4176
655
    }
4177
28
    return buildProjectionStandard(baseGeodCRS, projCRSNode, projectionNode,
4178
28
                                   defaultLinearUnit, defaultAngularUnit);
4179
683
}
4180
4181
// ---------------------------------------------------------------------------
4182
4183
std::string
4184
WKTParser::Private::projectionGetParameter(const WKTNodeNNPtr &projCRSNode,
4185
0
                                           const char *paramName) {
4186
0
    for (const auto &childNode : projCRSNode->GP()->children()) {
4187
0
        if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) {
4188
0
            const auto &childNodeChildren = childNode->GP()->children();
4189
0
            if (childNodeChildren.size() == 2 &&
4190
0
                metadata::Identifier::isEquivalentName(
4191
0
                    stripQuotes(childNodeChildren[0]).c_str(), paramName)) {
4192
0
                return childNodeChildren[1]->GP()->value();
4193
0
            }
4194
0
        }
4195
0
    }
4196
0
    return std::string();
4197
0
}
4198
4199
// ---------------------------------------------------------------------------
4200
4201
ConversionNNPtr WKTParser::Private::buildProjectionStandard(
4202
    const GeodeticCRSNNPtr &baseGeodCRS, const WKTNodeNNPtr &projCRSNode,
4203
    const WKTNodeNNPtr &projectionNode, const UnitOfMeasure &defaultLinearUnit,
4204
357
    const UnitOfMeasure &defaultAngularUnit) {
4205
357
    std::string wkt1ProjectionName =
4206
357
        stripQuotes(projectionNode->GP()->children()[0]);
4207
4208
357
    std::vector<OperationParameterNNPtr> parameters;
4209
357
    std::vector<ParameterValueNNPtr> values;
4210
357
    bool tryToIdentifyWKT1Method = true;
4211
4212
357
    auto &extensionNode = projCRSNode->lookForChild(WKTConstants::EXTENSION);
4213
357
    const auto &extensionChildren = extensionNode->GP()->children();
4214
4215
357
    bool gdal_3026_hack = false;
4216
357
    if (metadata::Identifier::isEquivalentName(wkt1ProjectionName.c_str(),
4217
357
                                               "Mercator_1SP") &&
4218
0
        projectionGetParameter(projCRSNode, "center_latitude").empty()) {
4219
4220
        // Hack for https://trac.osgeo.org/gdal/ticket/3026
4221
0
        std::string lat0(
4222
0
            projectionGetParameter(projCRSNode, "latitude_of_origin"));
4223
0
        if (!lat0.empty() && lat0 != "0" && lat0 != "0.0") {
4224
0
            wkt1ProjectionName = "Mercator_2SP";
4225
0
            gdal_3026_hack = true;
4226
0
        } else {
4227
            // The latitude of origin, which should always be zero, is
4228
            // missing
4229
            // in GDAL WKT1, but provisionned in the EPSG Mercator_1SP
4230
            // definition,
4231
            // so add it manually.
4232
0
            PropertyMap propertiesParameter;
4233
0
            propertiesParameter.set(IdentifiedObject::NAME_KEY,
4234
0
                                    "Latitude of natural origin");
4235
0
            propertiesParameter.set(Identifier::CODE_KEY, 8801);
4236
0
            propertiesParameter.set(Identifier::CODESPACE_KEY,
4237
0
                                    Identifier::EPSG);
4238
0
            parameters.push_back(
4239
0
                OperationParameter::create(propertiesParameter));
4240
0
            values.push_back(
4241
0
                ParameterValue::create(Measure(0, UnitOfMeasure::DEGREE)));
4242
0
        }
4243
4244
357
    } else if (metadata::Identifier::isEquivalentName(
4245
357
                   wkt1ProjectionName.c_str(), "Polar_Stereographic")) {
4246
84
        std::map<std::string, Measure> mapParameters;
4247
2.33k
        for (const auto &childNode : projCRSNode->GP()->children()) {
4248
2.33k
            const auto &childNodeChildren = childNode->GP()->children();
4249
2.33k
            if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER) &&
4250
870
                childNodeChildren.size() == 2) {
4251
799
                const std::string wkt1ParameterName(
4252
799
                    stripQuotes(childNodeChildren[0]));
4253
799
                try {
4254
799
                    double val = asDouble(childNodeChildren[1]);
4255
799
                    auto unit = guessUnitForParameter(wkt1ParameterName,
4256
799
                                                      defaultLinearUnit,
4257
799
                                                      defaultAngularUnit);
4258
799
                    mapParameters.insert(std::pair<std::string, Measure>(
4259
799
                        tolower(wkt1ParameterName), Measure(val, unit)));
4260
799
                } catch (const std::exception &) {
4261
45
                }
4262
799
            }
4263
2.33k
        }
4264
4265
84
        Measure latitudeOfOrigin = mapParameters["latitude_of_origin"];
4266
84
        Measure centralMeridian = mapParameters["central_meridian"];
4267
84
        Measure scaleFactorFromMap = mapParameters["scale_factor"];
4268
84
        Measure scaleFactor((scaleFactorFromMap.unit() == UnitOfMeasure::NONE)
4269
84
                                ? Measure(1.0, UnitOfMeasure::SCALE_UNITY)
4270
84
                                : scaleFactorFromMap);
4271
84
        Measure falseEasting = mapParameters["false_easting"];
4272
84
        Measure falseNorthing = mapParameters["false_northing"];
4273
84
        if (latitudeOfOrigin.unit() != UnitOfMeasure::NONE &&
4274
0
            scaleFactor.getSIValue() == 1.0) {
4275
0
            return Conversion::createPolarStereographicVariantB(
4276
0
                PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"),
4277
0
                Angle(latitudeOfOrigin.value(), latitudeOfOrigin.unit()),
4278
0
                Angle(centralMeridian.value(), centralMeridian.unit()),
4279
0
                Length(falseEasting.value(), falseEasting.unit()),
4280
0
                Length(falseNorthing.value(), falseNorthing.unit()));
4281
0
        }
4282
4283
84
        if (latitudeOfOrigin.unit() != UnitOfMeasure::NONE &&
4284
0
            std::fabs(std::fabs(latitudeOfOrigin.convertToUnit(
4285
0
                          UnitOfMeasure::DEGREE)) -
4286
0
                      90.0) < 1e-10) {
4287
0
            return Conversion::createPolarStereographicVariantA(
4288
0
                PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"),
4289
0
                Angle(latitudeOfOrigin.value(), latitudeOfOrigin.unit()),
4290
0
                Angle(centralMeridian.value(), centralMeridian.unit()),
4291
0
                Scale(scaleFactor.value(), scaleFactor.unit()),
4292
0
                Length(falseEasting.value(), falseEasting.unit()),
4293
0
                Length(falseNorthing.value(), falseNorthing.unit()));
4294
0
        }
4295
4296
84
        tryToIdentifyWKT1Method = false;
4297
        // Import GDAL PROJ4 extension nodes
4298
273
    } else if (extensionChildren.size() == 2 &&
4299
55
               ci_equal(stripQuotes(extensionChildren[0]), "PROJ4")) {
4300
50
        std::string projString = stripQuotes(extensionChildren[1]);
4301
50
        if (starts_with(projString, "+proj=")) {
4302
42
            if (projString.find(" +type=crs") == std::string::npos) {
4303
38
                projString += " +type=crs";
4304
38
            }
4305
42
            try {
4306
42
                auto projObj =
4307
42
                    PROJStringParser().createFromPROJString(projString);
4308
42
                auto projObjCrs =
4309
42
                    nn_dynamic_pointer_cast<ProjectedCRS>(projObj);
4310
42
                if (projObjCrs) {
4311
0
                    return projObjCrs->derivingConversion();
4312
0
                }
4313
42
            } catch (const io::ParsingException &) {
4314
38
            }
4315
42
        }
4316
50
    }
4317
4318
357
    std::string projectionName(std::move(wkt1ProjectionName));
4319
357
    const MethodMapping *mapping =
4320
357
        tryToIdentifyWKT1Method ? getMappingFromWKT1(projectionName) : nullptr;
4321
4322
357
    if (!mapping) {
4323
        // Sometimes non-WKT1:ESRI looking WKT can actually use WKT1:ESRI
4324
        // projection definitions
4325
258
        std::map<std::string, std::string, ci_less_struct> mapParamNameToValue;
4326
258
        const auto esriMapping =
4327
258
            getESRIMapping(projCRSNode, projectionNode, mapParamNameToValue);
4328
258
        if (esriMapping != nullptr) {
4329
9
            return buildProjectionFromESRI(
4330
9
                baseGeodCRS, projCRSNode, projectionNode, defaultLinearUnit,
4331
9
                defaultAngularUnit, esriMapping, mapParamNameToValue);
4332
9
        }
4333
258
    }
4334
4335
348
    if (mapping) {
4336
99
        mapping = selectSphericalOrEllipsoidal(mapping, baseGeodCRS);
4337
249
    } else if (metadata::Identifier::isEquivalentName(
4338
249
                   projectionName.c_str(), "Lambert Conformal Conic")) {
4339
        // Lambert Conformal Conic or Lambert_Conformal_Conic are respectively
4340
        // used by Oracle WKT and Trimble for either LCC 1SP or 2SP, so we
4341
        // have to look at parameters to figure out the variant.
4342
25
        bool found2ndStdParallel = false;
4343
25
        bool foundScaleFactor = false;
4344
215
        for (const auto &childNode : projCRSNode->GP()->children()) {
4345
215
            if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) {
4346
48
                const auto &childNodeChildren = childNode->GP()->children();
4347
48
                if (childNodeChildren.size() < 2) {
4348
3
                    ThrowNotEnoughChildren(WKTConstants::PARAMETER);
4349
3
                }
4350
45
                const std::string wkt1ParameterName(
4351
45
                    stripQuotes(childNodeChildren[0]));
4352
45
                if (metadata::Identifier::isEquivalentName(
4353
45
                        wkt1ParameterName.c_str(), WKT1_STANDARD_PARALLEL_2)) {
4354
4
                    found2ndStdParallel = true;
4355
41
                } else if (metadata::Identifier::isEquivalentName(
4356
41
                               wkt1ParameterName.c_str(), WKT1_SCALE_FACTOR)) {
4357
0
                    foundScaleFactor = true;
4358
0
                }
4359
45
            }
4360
215
        }
4361
22
        if (found2ndStdParallel && !foundScaleFactor) {
4362
4
            mapping = getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP);
4363
18
        } else if (!found2ndStdParallel && foundScaleFactor) {
4364
0
            mapping = getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP);
4365
18
        } else if (found2ndStdParallel && foundScaleFactor) {
4366
            // Not sure if that happens
4367
0
            mapping = getMapping(
4368
0
                EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN);
4369
0
        }
4370
22
    }
4371
4372
    // For Krovak, we need to look at axis to decide between the Krovak and
4373
    // Krovak East-North Oriented methods
4374
345
    if (ci_equal(projectionName, "Krovak") &&
4375
72
        projCRSNode->countChildrenOfName(WKTConstants::AXIS) == 2 &&
4376
0
        &buildAxis(projCRSNode->GP()->lookForChild(WKTConstants::AXIS, 0),
4377
0
                   defaultLinearUnit, UnitOfMeasure::Type::LINEAR, false, 1)
4378
0
                ->direction() == &AxisDirection::SOUTH &&
4379
0
        &buildAxis(projCRSNode->GP()->lookForChild(WKTConstants::AXIS, 1),
4380
0
                   defaultLinearUnit, UnitOfMeasure::Type::LINEAR, false, 2)
4381
0
                ->direction() == &AxisDirection::WEST) {
4382
0
        mapping = getMapping(EPSG_CODE_METHOD_KROVAK);
4383
0
    }
4384
4385
345
    PropertyMap propertiesMethod;
4386
345
    if (mapping) {
4387
103
        projectionName = mapping->wkt2_name;
4388
103
        if (mapping->epsg_code != 0) {
4389
97
            propertiesMethod.set(Identifier::CODE_KEY, mapping->epsg_code);
4390
97
            propertiesMethod.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
4391
97
        }
4392
103
    }
4393
345
    propertiesMethod.set(IdentifiedObject::NAME_KEY, projectionName);
4394
4395
345
    std::vector<bool> foundParameters;
4396
345
    if (mapping) {
4397
103
        size_t countParams = 0;
4398
772
        while (mapping->params[countParams] != nullptr) {
4399
669
            ++countParams;
4400
669
        }
4401
103
        foundParameters.resize(countParams);
4402
103
    }
4403
4404
3.20k
    for (const auto &childNode : projCRSNode->GP()->children()) {
4405
3.20k
        if (ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER)) {
4406
1.17k
            const auto &childNodeChildren = childNode->GP()->children();
4407
1.17k
            if (childNodeChildren.size() < 2) {
4408
52
                ThrowNotEnoughChildren(WKTConstants::PARAMETER);
4409
52
            }
4410
1.12k
            const auto &paramValue = childNodeChildren[1]->GP()->value();
4411
4412
1.12k
            PropertyMap propertiesParameter;
4413
1.12k
            const std::string wkt1ParameterName(
4414
1.12k
                stripQuotes(childNodeChildren[0]));
4415
1.12k
            std::string parameterName(wkt1ParameterName);
4416
1.12k
            if (gdal_3026_hack) {
4417
0
                if (ci_equal(parameterName, "latitude_of_origin")) {
4418
0
                    parameterName = "standard_parallel_1";
4419
0
                } else if (ci_equal(parameterName, "scale_factor") &&
4420
0
                           paramValue == "1") {
4421
0
                    continue;
4422
0
                }
4423
0
            }
4424
1.12k
            auto *paramMapping =
4425
1.12k
                mapping ? getMappingFromWKT1(mapping, parameterName) : nullptr;
4426
1.12k
            if (mapping &&
4427
390
                mapping->epsg_code == EPSG_CODE_METHOD_MERCATOR_VARIANT_B &&
4428
0
                ci_equal(parameterName, "latitude_of_origin")) {
4429
                // Some illegal formulations of Mercator_2SP have a unexpected
4430
                // latitude_of_origin parameter. We accept it on import, but
4431
                // do not accept it when exporting to PROJ string, unless it is
4432
                // zero.
4433
                // No need to try to update foundParameters[] as this is a
4434
                // unexpected one.
4435
0
                parameterName = EPSG_NAME_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN;
4436
0
                propertiesParameter.set(
4437
0
                    Identifier::CODE_KEY,
4438
0
                    EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN);
4439
0
                propertiesParameter.set(Identifier::CODESPACE_KEY,
4440
0
                                        Identifier::EPSG);
4441
1.12k
            } else if (mapping && paramMapping) {
4442
14
                for (size_t idx = 0; mapping->params[idx] != nullptr; ++idx) {
4443
14
                    if (mapping->params[idx] == paramMapping) {
4444
8
                        foundParameters[idx] = true;
4445
8
                        break;
4446
8
                    }
4447
14
                }
4448
8
                parameterName = paramMapping->wkt2_name;
4449
8
                if (paramMapping->epsg_code != 0) {
4450
8
                    propertiesParameter.set(Identifier::CODE_KEY,
4451
8
                                            paramMapping->epsg_code);
4452
8
                    propertiesParameter.set(Identifier::CODESPACE_KEY,
4453
8
                                            Identifier::EPSG);
4454
8
                }
4455
8
            }
4456
1.12k
            propertiesParameter.set(IdentifiedObject::NAME_KEY, parameterName);
4457
1.12k
            parameters.push_back(
4458
1.12k
                OperationParameter::create(propertiesParameter));
4459
1.12k
            try {
4460
1.12k
                double val = io::asDouble(paramValue);
4461
1.12k
                auto unit = guessUnitForParameter(
4462
1.12k
                    wkt1ParameterName, defaultLinearUnit, defaultAngularUnit);
4463
1.12k
                values.push_back(ParameterValue::create(Measure(val, unit)));
4464
1.12k
            } catch (const std::exception &) {
4465
125
                throw ParsingException(
4466
125
                    concat("unhandled parameter value type : ", paramValue));
4467
125
            }
4468
1.12k
        }
4469
3.20k
    }
4470
4471
    // Add back important parameters that should normally be present, but
4472
    // are sometimes missing. Currently we only deal with Scale factor at
4473
    // natural origin. This is to avoid a default value of 0 to slip in later.
4474
    // But such WKT should be considered invalid.
4475
168
    if (mapping) {
4476
256
        for (size_t idx = 0; mapping->params[idx] != nullptr; ++idx) {
4477
219
            if (!foundParameters[idx] &&
4478
219
                mapping->params[idx]->epsg_code ==
4479
219
                    EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN) {
4480
4481
18
                emitRecoverableWarning(
4482
18
                    "The WKT string lacks a value "
4483
18
                    "for " EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN
4484
18
                    ". Default it to 1.");
4485
4486
18
                PropertyMap propertiesParameter;
4487
18
                propertiesParameter.set(
4488
18
                    Identifier::CODE_KEY,
4489
18
                    EPSG_CODE_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN);
4490
18
                propertiesParameter.set(Identifier::CODESPACE_KEY,
4491
18
                                        Identifier::EPSG);
4492
18
                propertiesParameter.set(
4493
18
                    IdentifiedObject::NAME_KEY,
4494
18
                    EPSG_NAME_PARAMETER_SCALE_FACTOR_AT_NATURAL_ORIGIN);
4495
18
                parameters.push_back(
4496
18
                    OperationParameter::create(propertiesParameter));
4497
18
                values.push_back(ParameterValue::create(
4498
18
                    Measure(1.0, UnitOfMeasure::SCALE_UNITY)));
4499
18
            }
4500
219
        }
4501
37
    }
4502
4503
168
    if (mapping && (mapping->epsg_code ==
4504
37
                        EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A ||
4505
31
                    mapping->epsg_code ==
4506
31
                        EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B)) {
4507
        // Special case when importing some GDAL WKT of Hotine Oblique Mercator
4508
        // that have a Azimuth parameter but lacks the Rectified Grid Angle.
4509
        // We have code in the exportToPROJString() to deal with that situation,
4510
        // but also adds the rectified grid angle from the azimuth on import.
4511
6
        bool foundAngleRecifiedToSkewGrid = false;
4512
6
        bool foundAzimuth = false;
4513
48
        for (size_t idx = 0; mapping->params[idx] != nullptr; ++idx) {
4514
42
            if (foundParameters[idx] &&
4515
0
                mapping->params[idx]->epsg_code ==
4516
0
                    EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID) {
4517
0
                foundAngleRecifiedToSkewGrid = true;
4518
42
            } else if (foundParameters[idx] &&
4519
0
                       mapping->params[idx]->epsg_code ==
4520
0
                           EPSG_CODE_PARAMETER_AZIMUTH_PROJECTION_CENTRE) {
4521
0
                foundAzimuth = true;
4522
0
            }
4523
42
        }
4524
6
        if (!foundAngleRecifiedToSkewGrid && foundAzimuth) {
4525
0
            for (size_t idx = 0; idx < parameters.size(); ++idx) {
4526
0
                if (parameters[idx]->getEPSGCode() ==
4527
0
                    EPSG_CODE_PARAMETER_AZIMUTH_PROJECTION_CENTRE) {
4528
0
                    PropertyMap propertiesParameter;
4529
0
                    propertiesParameter.set(
4530
0
                        Identifier::CODE_KEY,
4531
0
                        EPSG_CODE_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID);
4532
0
                    propertiesParameter.set(Identifier::CODESPACE_KEY,
4533
0
                                            Identifier::EPSG);
4534
0
                    propertiesParameter.set(
4535
0
                        IdentifiedObject::NAME_KEY,
4536
0
                        EPSG_NAME_PARAMETER_ANGLE_RECTIFIED_TO_SKEW_GRID);
4537
0
                    parameters.push_back(
4538
0
                        OperationParameter::create(propertiesParameter));
4539
0
                    values.push_back(values[idx]);
4540
0
                }
4541
0
            }
4542
0
        }
4543
6
    }
4544
4545
168
    return Conversion::create(
4546
168
               PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"),
4547
168
               propertiesMethod, parameters, values)
4548
168
        ->identify();
4549
345
}
4550
4551
// ---------------------------------------------------------------------------
4552
4553
static ProjectedCRSNNPtr createPseudoMercator(const PropertyMap &props,
4554
0
                                              const cs::CartesianCSNNPtr &cs) {
4555
0
    auto conversion = Conversion::createPopularVisualisationPseudoMercator(
4556
0
        PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"), Angle(0),
4557
0
        Angle(0), Length(0), Length(0));
4558
0
    return ProjectedCRS::create(props, GeographicCRS::EPSG_4326, conversion,
4559
0
                                cs);
4560
0
}
4561
4562
// ---------------------------------------------------------------------------
4563
4564
ProjectedCRSNNPtr
4565
796
WKTParser::Private::buildProjectedCRS(const WKTNodeNNPtr &node) {
4566
4567
796
    const auto *nodeP = node->GP();
4568
796
    auto &conversionNode = nodeP->lookForChild(WKTConstants::CONVERSION);
4569
796
    auto &projectionNode = nodeP->lookForChild(WKTConstants::PROJECTION);
4570
796
    if (isNull(conversionNode) && isNull(projectionNode)) {
4571
60
        ThrowMissing(WKTConstants::CONVERSION);
4572
60
    }
4573
4574
736
    auto &baseGeodCRSNode =
4575
736
        nodeP->lookForChild(WKTConstants::BASEGEODCRS,
4576
736
                            WKTConstants::BASEGEOGCRS, WKTConstants::GEOGCS);
4577
736
    if (isNull(baseGeodCRSNode)) {
4578
5
        throw ParsingException(
4579
5
            "Missing BASEGEODCRS / BASEGEOGCRS / GEOGCS node");
4580
5
    }
4581
731
    auto baseGeodCRS = buildGeodeticCRS(baseGeodCRSNode);
4582
4583
731
    auto props = buildProperties(node);
4584
4585
731
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
4586
731
    const auto &nodeValue = nodeP->value();
4587
731
    if (isNull(csNode) && !ci_equal(nodeValue, WKTConstants::PROJCS) &&
4588
0
        !ci_equal(nodeValue, WKTConstants::BASEPROJCRS)) {
4589
0
        ThrowMissing(WKTConstants::CS_);
4590
0
    }
4591
4592
731
    std::string projCRSName = stripQuotes(nodeP->children()[0]);
4593
4594
731
    auto cs = [this, &projCRSName, &nodeP, &csNode, &node, &nodeValue,
4595
731
               &conversionNode]() -> CoordinateSystemNNPtr {
4596
705
        if (isNull(csNode) && ci_equal(nodeValue, WKTConstants::BASEPROJCRS) &&
4597
0
            !isNull(conversionNode)) {
4598
            // A BASEPROJCRS (as of WKT2 18-010r11) normally lacks an explicit
4599
            // CS[] which cause issues to properly instantiate it. So we first
4600
            // start by trying to identify the BASEPROJCRS by its id or name.
4601
            // And fallback to exploring the conversion parameters to infer the
4602
            // CS AXIS unit from the linear parameter unit... Not fully bullet
4603
            // proof.
4604
0
            if (dbContext_) {
4605
                // Get official name from database if ID is present
4606
0
                auto &idNode = nodeP->lookForChild(WKTConstants::ID);
4607
0
                if (!isNull(idNode)) {
4608
0
                    try {
4609
0
                        auto id = buildId(node, idNode, false, false);
4610
0
                        auto authFactory = AuthorityFactory::create(
4611
0
                            NN_NO_CHECK(dbContext_), *id->codeSpace());
4612
0
                        auto projCRS =
4613
0
                            authFactory->createProjectedCRS(id->code());
4614
0
                        return projCRS->coordinateSystem();
4615
0
                    } catch (const std::exception &) {
4616
0
                    }
4617
0
                }
4618
4619
0
                auto authFactory = AuthorityFactory::create(
4620
0
                    NN_NO_CHECK(dbContext_), std::string());
4621
0
                auto res = authFactory->createObjectsFromName(
4622
0
                    projCRSName, {AuthorityFactory::ObjectType::PROJECTED_CRS},
4623
0
                    false, 2);
4624
0
                if (res.size() == 1) {
4625
0
                    auto projCRS =
4626
0
                        dynamic_cast<const ProjectedCRS *>(res.front().get());
4627
0
                    if (projCRS) {
4628
0
                        return projCRS->coordinateSystem();
4629
0
                    }
4630
0
                }
4631
0
            }
4632
4633
0
            auto conv = buildConversion(conversionNode, UnitOfMeasure::METRE,
4634
0
                                        UnitOfMeasure::DEGREE);
4635
0
            UnitOfMeasure linearUOM = UnitOfMeasure::NONE;
4636
0
            for (const auto &genOpParamvalue : conv->parameterValues()) {
4637
0
                auto opParamvalue =
4638
0
                    dynamic_cast<const operation::OperationParameterValue *>(
4639
0
                        genOpParamvalue.get());
4640
0
                if (opParamvalue) {
4641
0
                    const auto &parameterValue = opParamvalue->parameterValue();
4642
0
                    if (parameterValue->type() ==
4643
0
                        operation::ParameterValue::Type::MEASURE) {
4644
0
                        const auto &measure = parameterValue->value();
4645
0
                        const auto &unit = measure.unit();
4646
0
                        if (unit.type() == UnitOfMeasure::Type::LINEAR) {
4647
0
                            if (linearUOM == UnitOfMeasure::NONE) {
4648
0
                                linearUOM = unit;
4649
0
                            } else if (linearUOM != unit) {
4650
0
                                linearUOM = UnitOfMeasure::NONE;
4651
0
                                break;
4652
0
                            }
4653
0
                        }
4654
0
                    }
4655
0
                }
4656
0
            }
4657
0
            if (linearUOM != UnitOfMeasure::NONE) {
4658
0
                return CartesianCS::createEastingNorthing(linearUOM);
4659
0
            }
4660
0
        }
4661
705
        return buildCS(csNode, node, UnitOfMeasure::NONE);
4662
705
    }();
4663
731
    auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs);
4664
4665
731
    if (dbContext_ && ((!esriStyle_ && projCRSName == "ETRF2000-PL / CS92" &&
4666
0
                        baseGeodCRS->nameStr() == "ETRF2000-PL") ||
4667
623
                       (esriStyle_ && projCRSName == "ETRF2000-PL_CS92" &&
4668
0
                        (baseGeodCRS->nameStr() == "GCS_ETRF2000-PL" ||
4669
0
                         baseGeodCRS->nameStr() == "ETRF2000-PL")))) {
4670
        // Oddity: "ETRF2000-PL / CS92" (EPSG:2180) has switched back to
4671
        // "ETRS89 / PL-1992"
4672
0
        auto authFactoryEPSG =
4673
0
            io::AuthorityFactory::create(NN_NO_CHECK(dbContext_), "EPSG");
4674
0
        auto newProjCRS = authFactoryEPSG->createProjectedCRS("2180");
4675
0
        props.set(IdentifiedObject::NAME_KEY, newProjCRS->nameStr());
4676
0
        baseGeodCRS = newProjCRS->baseCRS();
4677
0
    }
4678
    // In EPSG v12.025, Norway projected systems based on ETRS89 (EPSG:4258)
4679
    // have switched to use ETRS89-NOR [EUREF89] (EPSG:10875).
4680
    // Similarly for other ETRS89-like datums in later releases
4681
731
    else if (dbContext_ &&
4682
623
             (((starts_with(projCRSName, "ETRS89 / ") ||
4683
623
                (esriStyle_ && starts_with(projCRSName, "ETRS_1989_"))) &&
4684
0
               baseGeodCRS->nameStr() == "ETRS89") ||
4685
623
              starts_with(projCRSName, "ETRF2000-PL /")) &&
4686
0
             util::isOfExactType<GeographicCRS>(*(baseGeodCRS.get())) &&
4687
0
             baseGeodCRS->coordinateSystem()->axisList().size() == 2) {
4688
0
        auto authFactoryEPSG =
4689
0
            io::AuthorityFactory::create(NN_NO_CHECK(dbContext_), "EPSG");
4690
0
        const auto objCandidates = authFactoryEPSG->createObjectsFromNameEx(
4691
0
            projCRSName, {io::AuthorityFactory::ObjectType::PROJECTED_CRS},
4692
0
            false, // approximateMatch
4693
0
            0,     // limit
4694
0
            true   // useAliases
4695
0
        );
4696
0
        for (const auto &[obj, name] : objCandidates) {
4697
0
            if (name == projCRSName) {
4698
0
                auto candidateProj =
4699
0
                    dynamic_cast<const crs::ProjectedCRS *>(obj.get());
4700
0
                if (candidateProj &&
4701
0
                    candidateProj->baseCRS()->nameStr() !=
4702
0
                        baseGeodCRS->nameStr() &&
4703
0
                    candidateProj->baseCRS()->_isEquivalentTo(
4704
0
                        baseGeodCRS.get(),
4705
0
                        util::IComparable::Criterion::
4706
0
                            EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS,
4707
0
                        dbContext_)) {
4708
0
                    props.set(IdentifiedObject::NAME_KEY,
4709
0
                              candidateProj->nameStr());
4710
0
                    baseGeodCRS = candidateProj->baseCRS();
4711
0
                    break;
4712
0
                }
4713
0
            }
4714
0
        }
4715
0
    }
4716
4717
731
    if (esriStyle_ && dbContext_) {
4718
330
        if (cartesianCS) {
4719
330
            std::string outTableName;
4720
330
            std::string authNameFromAlias;
4721
330
            std::string codeFromAlias;
4722
330
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
4723
330
                                                        std::string());
4724
330
            auto officialName = authFactory->getOfficialNameFromAlias(
4725
330
                projCRSName, "projected_crs", "ESRI", false, outTableName,
4726
330
                authNameFromAlias, codeFromAlias);
4727
330
            if (!officialName.empty()) {
4728
                // Special case for https://github.com/OSGeo/PROJ/issues/2086
4729
                // The name of the CRS to identify is
4730
                // NAD_1983_HARN_StatePlane_Colorado_North_FIPS_0501
4731
                // whereas it should be
4732
                // NAD_1983_HARN_StatePlane_Colorado_North_FIPS_0501_Feet
4733
0
                constexpr double US_FOOT_CONV_FACTOR = 12.0 / 39.37;
4734
0
                if (projCRSName.find("_FIPS_") != std::string::npos &&
4735
0
                    projCRSName.find("_Feet") == std::string::npos &&
4736
0
                    std::fabs(
4737
0
                        cartesianCS->axisList()[0]->unit().conversionToSI() -
4738
0
                        US_FOOT_CONV_FACTOR) < 1e-10 * US_FOOT_CONV_FACTOR) {
4739
0
                    auto officialNameFromFeet =
4740
0
                        authFactory->getOfficialNameFromAlias(
4741
0
                            projCRSName + "_Feet", "projected_crs", "ESRI",
4742
0
                            false, outTableName, authNameFromAlias,
4743
0
                            codeFromAlias);
4744
0
                    if (!officialNameFromFeet.empty()) {
4745
0
                        officialName = std::move(officialNameFromFeet);
4746
0
                    }
4747
0
                }
4748
4749
0
                projCRSName = officialName;
4750
0
                props.set(IdentifiedObject::NAME_KEY, officialName);
4751
0
            }
4752
330
        }
4753
330
    }
4754
4755
731
    if (isNull(conversionNode) && hasWebMercPROJ4String(node, projectionNode) &&
4756
0
        cartesianCS) {
4757
0
        toWGS84Parameters_.clear();
4758
0
        return createPseudoMercator(props, NN_NO_CHECK(cartesianCS));
4759
0
    }
4760
4761
    // WGS_84_Pseudo_Mercator: Particular case for corrupted ESRI WKT generated
4762
    // by older GDAL versions
4763
    // https://trac.osgeo.org/gdal/changeset/30732
4764
    // WGS_1984_Web_Mercator: deprecated ESRI:102113
4765
731
    if (cartesianCS && (metadata::Identifier::isEquivalentName(
4766
698
                            projCRSName.c_str(), "WGS_84_Pseudo_Mercator") ||
4767
698
                        metadata::Identifier::isEquivalentName(
4768
698
                            projCRSName.c_str(), "WGS_1984_Web_Mercator"))) {
4769
0
        toWGS84Parameters_.clear();
4770
0
        return createPseudoMercator(props, NN_NO_CHECK(cartesianCS));
4771
0
    }
4772
4773
    // For WKT2, if there is no explicit parameter unit, use metre for linear
4774
    // units and degree for angular units
4775
731
    const UnitOfMeasure linearUnit(
4776
731
        !isNull(conversionNode)
4777
731
            ? UnitOfMeasure::METRE
4778
731
            : buildUnitInSubNode(node, UnitOfMeasure::Type::LINEAR));
4779
731
    const auto &angularUnit =
4780
731
        !isNull(conversionNode)
4781
731
            ? UnitOfMeasure::DEGREE
4782
731
            : baseGeodCRS->coordinateSystem()->axisList()[0]->unit();
4783
4784
731
    auto conversion =
4785
731
        !isNull(conversionNode)
4786
731
            ? buildConversion(conversionNode, linearUnit, angularUnit)
4787
731
            : buildProjection(baseGeodCRS, node, projectionNode, linearUnit,
4788
716
                              angularUnit);
4789
4790
    // No explicit AXIS node ? (WKT1)
4791
731
    if (isNull(nodeP->lookForChild(WKTConstants::AXIS))) {
4792
502
        props.set("IMPLICIT_CS", true);
4793
502
    }
4794
4795
731
    if (isNull(csNode) && node->countChildrenOfName(WKTConstants::AXIS) == 0) {
4796
4797
502
        const auto methodCode = conversion->method()->getEPSGCode();
4798
        // Krovak south oriented ?
4799
502
        if (methodCode == EPSG_CODE_METHOD_KROVAK) {
4800
14
            cartesianCS =
4801
14
                CartesianCS::create(
4802
14
                    PropertyMap(),
4803
14
                    CoordinateSystemAxis::create(
4804
14
                        util::PropertyMap().set(IdentifiedObject::NAME_KEY,
4805
14
                                                AxisName::Southing),
4806
14
                        emptyString, AxisDirection::SOUTH, linearUnit),
4807
14
                    CoordinateSystemAxis::create(
4808
14
                        util::PropertyMap().set(IdentifiedObject::NAME_KEY,
4809
14
                                                AxisName::Westing),
4810
14
                        emptyString, AxisDirection::WEST, linearUnit))
4811
14
                    .as_nullable();
4812
488
        } else if (methodCode ==
4813
488
                       EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A ||
4814
474
                   methodCode ==
4815
474
                       EPSG_CODE_METHOD_LAMBERT_AZIMUTHAL_EQUAL_AREA) {
4816
            // It is likely that the ESRI definition of EPSG:32661 (UPS North) &
4817
            // EPSG:32761 (UPS South) uses the easting-northing order, instead
4818
            // of the EPSG northing-easting order.
4819
            // Same for WKT1_GDAL
4820
19
            const double lat0 = conversion->parameterValueNumeric(
4821
19
                EPSG_CODE_PARAMETER_LATITUDE_OF_NATURAL_ORIGIN,
4822
19
                common::UnitOfMeasure::DEGREE);
4823
19
            if (std::fabs(lat0 - 90) < 1e-10) {
4824
10
                cartesianCS =
4825
10
                    CartesianCS::createNorthPoleEastingSouthNorthingSouth(
4826
10
                        linearUnit)
4827
10
                        .as_nullable();
4828
10
            } else if (std::fabs(lat0 - -90) < 1e-10) {
4829
9
                cartesianCS =
4830
9
                    CartesianCS::createSouthPoleEastingNorthNorthingNorth(
4831
9
                        linearUnit)
4832
9
                        .as_nullable();
4833
9
            }
4834
469
        } else if (methodCode ==
4835
469
                   EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B) {
4836
3
            const double lat_ts = conversion->parameterValueNumeric(
4837
3
                EPSG_CODE_PARAMETER_LATITUDE_STD_PARALLEL,
4838
3
                common::UnitOfMeasure::DEGREE);
4839
3
            if (lat_ts > 0) {
4840
3
                cartesianCS =
4841
3
                    CartesianCS::createNorthPoleEastingSouthNorthingSouth(
4842
3
                        linearUnit)
4843
3
                        .as_nullable();
4844
3
            } else if (lat_ts < 0) {
4845
0
                cartesianCS =
4846
0
                    CartesianCS::createSouthPoleEastingNorthNorthingNorth(
4847
0
                        linearUnit)
4848
0
                        .as_nullable();
4849
0
            }
4850
466
        } else if (methodCode ==
4851
466
                   EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED) {
4852
0
            cartesianCS =
4853
0
                CartesianCS::createWestingSouthing(linearUnit).as_nullable();
4854
0
        }
4855
502
    }
4856
731
    if (!cartesianCS) {
4857
0
        ThrowNotExpectedCSType(CartesianCS::WKT2_TYPE);
4858
0
    }
4859
4860
731
    if (cartesianCS->axisList().size() == 3 &&
4861
0
        baseGeodCRS->coordinateSystem()->axisList().size() == 2) {
4862
0
        baseGeodCRS = NN_NO_CHECK(util::nn_dynamic_pointer_cast<GeodeticCRS>(
4863
0
            baseGeodCRS->promoteTo3D(std::string(), dbContext_)));
4864
0
    }
4865
4866
731
    addExtensionProj4ToProp(nodeP, props);
4867
4868
731
    return ProjectedCRS::create(props, baseGeodCRS, conversion,
4869
731
                                NN_NO_CHECK(cartesianCS));
4870
731
}
4871
4872
// ---------------------------------------------------------------------------
4873
4874
void WKTParser::Private::parseDynamic(const WKTNodeNNPtr &dynamicNode,
4875
                                      double &frameReferenceEpoch,
4876
21
                                      util::optional<std::string> &modelName) {
4877
21
    auto &frameEpochNode = dynamicNode->lookForChild(WKTConstants::FRAMEEPOCH);
4878
21
    const auto &frameEpochChildren = frameEpochNode->GP()->children();
4879
21
    if (frameEpochChildren.empty()) {
4880
4
        ThrowMissing(WKTConstants::FRAMEEPOCH);
4881
4
    }
4882
17
    try {
4883
17
        frameReferenceEpoch = asDouble(frameEpochChildren[0]);
4884
17
    } catch (const std::exception &) {
4885
3
        throw ParsingException("Invalid FRAMEEPOCH node");
4886
3
    }
4887
14
    auto &modelNode = dynamicNode->GP()->lookForChild(
4888
14
        WKTConstants::MODEL, WKTConstants::VELOCITYGRID);
4889
14
    const auto &modelChildren = modelNode->GP()->children();
4890
14
    if (modelChildren.size() == 1) {
4891
0
        modelName = stripQuotes(modelChildren[0]);
4892
0
    }
4893
14
}
4894
4895
// ---------------------------------------------------------------------------
4896
4897
VerticalReferenceFrameNNPtr WKTParser::Private::buildVerticalReferenceFrame(
4898
801
    const WKTNodeNNPtr &node, const WKTNodeNNPtr &dynamicNode) {
4899
4900
801
    if (!isNull(dynamicNode)) {
4901
0
        double frameReferenceEpoch = 0.0;
4902
0
        util::optional<std::string> modelName;
4903
0
        parseDynamic(dynamicNode, frameReferenceEpoch, modelName);
4904
0
        return DynamicVerticalReferenceFrame::create(
4905
0
            buildProperties(node), getAnchor(node),
4906
0
            optional<RealizationMethod>(),
4907
0
            common::Measure(frameReferenceEpoch, common::UnitOfMeasure::YEAR),
4908
0
            modelName);
4909
0
    }
4910
4911
    // WKT1 VERT_DATUM has a datum type after the datum name
4912
801
    const auto *nodeP = node->GP();
4913
801
    const std::string &name(nodeP->value());
4914
801
    auto &props = buildProperties(node);
4915
801
    const auto &children = nodeP->children();
4916
4917
801
    if (esriStyle_ && dbContext_ && !children.empty()) {
4918
6
        std::string outTableName;
4919
6
        std::string authNameFromAlias;
4920
6
        std::string codeFromAlias;
4921
6
        auto authFactory =
4922
6
            AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string());
4923
6
        const std::string datumName = stripQuotes(children[0]);
4924
6
        auto officialName = authFactory->getOfficialNameFromAlias(
4925
6
            datumName, "vertical_datum", "ESRI", false, outTableName,
4926
6
            authNameFromAlias, codeFromAlias);
4927
6
        if (!officialName.empty()) {
4928
0
            props.set(IdentifiedObject::NAME_KEY, officialName);
4929
0
        }
4930
6
    }
4931
4932
801
    if (ci_equal(name, WKTConstants::VERT_DATUM)) {
4933
33
        if (children.size() >= 2) {
4934
24
            props.set("VERT_DATUM_TYPE", children[1]->GP()->value());
4935
24
        }
4936
33
    }
4937
4938
801
    return VerticalReferenceFrame::create(props, getAnchor(node),
4939
801
                                          getAnchorEpoch(node));
4940
801
}
4941
4942
// ---------------------------------------------------------------------------
4943
4944
TemporalDatumNNPtr
4945
23
WKTParser::Private::buildTemporalDatum(const WKTNodeNNPtr &node) {
4946
23
    const auto *nodeP = node->GP();
4947
23
    auto &calendarNode = nodeP->lookForChild(WKTConstants::CALENDAR);
4948
23
    std::string calendar = TemporalDatum::CALENDAR_PROLEPTIC_GREGORIAN;
4949
23
    const auto &calendarChildren = calendarNode->GP()->children();
4950
23
    if (calendarChildren.size() == 1) {
4951
0
        calendar = stripQuotes(calendarChildren[0]);
4952
0
    }
4953
4954
23
    auto &timeOriginNode = nodeP->lookForChild(WKTConstants::TIMEORIGIN);
4955
23
    std::string originStr;
4956
23
    const auto &timeOriginNodeChildren = timeOriginNode->GP()->children();
4957
23
    if (timeOriginNodeChildren.size() == 1) {
4958
5
        originStr = stripQuotes(timeOriginNodeChildren[0]);
4959
5
    }
4960
23
    auto origin = DateTime::create(originStr);
4961
23
    return TemporalDatum::create(buildProperties(node), origin, calendar);
4962
23
}
4963
4964
// ---------------------------------------------------------------------------
4965
4966
EngineeringDatumNNPtr
4967
7
WKTParser::Private::buildEngineeringDatum(const WKTNodeNNPtr &node) {
4968
7
    return EngineeringDatum::create(buildProperties(node), getAnchor(node));
4969
7
}
4970
4971
// ---------------------------------------------------------------------------
4972
4973
ParametricDatumNNPtr
4974
6
WKTParser::Private::buildParametricDatum(const WKTNodeNNPtr &node) {
4975
6
    return ParametricDatum::create(buildProperties(node), getAnchor(node));
4976
6
}
4977
4978
// ---------------------------------------------------------------------------
4979
4980
static CRSNNPtr
4981
createBoundCRSSourceTransformationCRS(const crs::CRSPtr &sourceCRS,
4982
14
                                      const crs::CRSPtr &targetCRS) {
4983
14
    CRSPtr sourceTransformationCRS;
4984
14
    if (dynamic_cast<GeographicCRS *>(targetCRS.get())) {
4985
14
        GeographicCRSPtr sourceGeographicCRS =
4986
14
            sourceCRS->extractGeographicCRS();
4987
14
        sourceTransformationCRS = sourceGeographicCRS;
4988
14
        if (sourceGeographicCRS) {
4989
0
            const auto &sourceDatum = sourceGeographicCRS->datum();
4990
0
            if (sourceDatum != nullptr && sourceGeographicCRS->primeMeridian()
4991
0
                                                  ->longitude()
4992
0
                                                  .getSIValue() != 0.0) {
4993
0
                sourceTransformationCRS =
4994
0
                    GeographicCRS::create(
4995
0
                        util::PropertyMap().set(
4996
0
                            common::IdentifiedObject::NAME_KEY,
4997
0
                            sourceGeographicCRS->nameStr() +
4998
0
                                " (with Greenwich prime meridian)"),
4999
0
                        datum::GeodeticReferenceFrame::create(
5000
0
                            util::PropertyMap().set(
5001
0
                                common::IdentifiedObject::NAME_KEY,
5002
0
                                sourceDatum->nameStr() +
5003
0
                                    " (with Greenwich prime meridian)"),
5004
0
                            sourceDatum->ellipsoid(),
5005
0
                            util::optional<std::string>(),
5006
0
                            datum::PrimeMeridian::GREENWICH),
5007
0
                        sourceGeographicCRS->coordinateSystem())
5008
0
                        .as_nullable();
5009
0
            }
5010
14
        } else {
5011
14
            auto vertSourceCRS =
5012
14
                std::dynamic_pointer_cast<VerticalCRS>(sourceCRS);
5013
14
            if (!vertSourceCRS) {
5014
0
                throw ParsingException(
5015
0
                    "Cannot find GeographicCRS or VerticalCRS in sourceCRS");
5016
0
            }
5017
14
            const auto &axis = vertSourceCRS->coordinateSystem()->axisList()[0];
5018
14
            if (axis->unit() == common::UnitOfMeasure::METRE &&
5019
7
                &(axis->direction()) == &AxisDirection::UP) {
5020
7
                sourceTransformationCRS = sourceCRS;
5021
7
            } else {
5022
7
                std::string sourceTransformationCRSName(
5023
7
                    vertSourceCRS->nameStr());
5024
7
                if (ends_with(sourceTransformationCRSName, " (ftUS)")) {
5025
0
                    sourceTransformationCRSName.resize(
5026
0
                        sourceTransformationCRSName.size() - strlen(" (ftUS)"));
5027
0
                }
5028
7
                if (ends_with(sourceTransformationCRSName, " depth")) {
5029
0
                    sourceTransformationCRSName.resize(
5030
0
                        sourceTransformationCRSName.size() - strlen(" depth"));
5031
0
                }
5032
7
                if (!ends_with(sourceTransformationCRSName, " height")) {
5033
7
                    sourceTransformationCRSName += " height";
5034
7
                }
5035
7
                sourceTransformationCRS =
5036
7
                    VerticalCRS::create(
5037
7
                        PropertyMap().set(IdentifiedObject::NAME_KEY,
5038
7
                                          sourceTransformationCRSName),
5039
7
                        vertSourceCRS->datum(), vertSourceCRS->datumEnsemble(),
5040
7
                        VerticalCS::createGravityRelatedHeight(
5041
7
                            common::UnitOfMeasure::METRE))
5042
7
                        .as_nullable();
5043
7
            }
5044
14
        }
5045
14
    } else {
5046
0
        sourceTransformationCRS = sourceCRS;
5047
0
    }
5048
14
    return NN_NO_CHECK(sourceTransformationCRS);
5049
14
}
5050
5051
// ---------------------------------------------------------------------------
5052
5053
717
CRSNNPtr WKTParser::Private::buildVerticalCRS(const WKTNodeNNPtr &node) {
5054
717
    const auto *nodeP = node->GP();
5055
717
    const auto &nodeValue = nodeP->value();
5056
717
    auto &vdatumNode =
5057
717
        nodeP->lookForChild(WKTConstants::VDATUM, WKTConstants::VERT_DATUM,
5058
717
                            WKTConstants::VERTICALDATUM, WKTConstants::VRF);
5059
717
    auto &ensembleNode = nodeP->lookForChild(WKTConstants::ENSEMBLE);
5060
    // like in ESRI  VERTCS["WGS_1984",DATUM["D_WGS_1984",
5061
    //               SPHEROID["WGS_1984",6378137.0,298.257223563]],
5062
    //               PARAMETER["Vertical_Shift",0.0],
5063
    //               PARAMETER["Direction",1.0],UNIT["Meter",1.0]
5064
717
    auto &geogDatumNode = ci_equal(nodeValue, WKTConstants::VERTCS)
5065
717
                              ? nodeP->lookForChild(WKTConstants::DATUM)
5066
717
                              : null_node;
5067
717
    if (isNull(vdatumNode) && isNull(geogDatumNode) && isNull(ensembleNode)) {
5068
16
        throw ParsingException("Missing VDATUM or ENSEMBLE node");
5069
16
    }
5070
5071
3.29k
    for (const auto &childNode : nodeP->children()) {
5072
3.29k
        const auto &childNodeChildren = childNode->GP()->children();
5073
3.29k
        if (childNodeChildren.size() == 2 &&
5074
325
            ci_equal(childNode->GP()->value(), WKTConstants::PARAMETER) &&
5075
17
            childNodeChildren[0]->GP()->value() == "\"Vertical_Shift\"") {
5076
0
            esriStyle_ = true;
5077
0
            break;
5078
0
        }
5079
3.29k
    }
5080
5081
701
    auto &dynamicNode = nodeP->lookForChild(WKTConstants::DYNAMIC);
5082
701
    auto vdatum =
5083
701
        !isNull(geogDatumNode)
5084
701
            ? VerticalReferenceFrame::create(
5085
20
                  PropertyMap()
5086
20
                      .set(IdentifiedObject::NAME_KEY,
5087
20
                           buildGeodeticReferenceFrame(geogDatumNode,
5088
20
                                                       PrimeMeridian::GREENWICH,
5089
20
                                                       null_node)
5090
20
                               ->nameStr())
5091
20
                      .set("VERT_DATUM_TYPE", "2002"))
5092
20
                  .as_nullable()
5093
701
        : !isNull(vdatumNode)
5094
681
            ? buildVerticalReferenceFrame(vdatumNode, dynamicNode).as_nullable()
5095
681
            : nullptr;
5096
701
    auto datumEnsemble =
5097
701
        !isNull(ensembleNode)
5098
701
            ? buildDatumEnsemble(ensembleNode, nullptr, false).as_nullable()
5099
701
            : nullptr;
5100
5101
701
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
5102
701
    if (isNull(csNode) && !ci_equal(nodeValue, WKTConstants::VERT_CS) &&
5103
635
        !ci_equal(nodeValue, WKTConstants::VERTCS) &&
5104
1
        !ci_equal(nodeValue, WKTConstants::BASEVERTCRS)) {
5105
1
        ThrowMissing(WKTConstants::CS_);
5106
1
    }
5107
700
    auto verticalCS = nn_dynamic_pointer_cast<VerticalCS>(
5108
700
        buildCS(csNode, node, UnitOfMeasure::NONE));
5109
700
    if (!verticalCS) {
5110
0
        ThrowNotExpectedCSType(VerticalCS::WKT2_TYPE);
5111
0
    }
5112
5113
700
    if (vdatum && vdatum->getWKT1DatumType() == "2002" &&
5114
15
        &(verticalCS->axisList()[0]->direction()) == &(AxisDirection::UP)) {
5115
15
        verticalCS =
5116
15
            VerticalCS::create(
5117
15
                util::PropertyMap(),
5118
15
                CoordinateSystemAxis::create(
5119
15
                    util::PropertyMap().set(IdentifiedObject::NAME_KEY,
5120
15
                                            "ellipsoidal height"),
5121
15
                    "h", AxisDirection::UP, verticalCS->axisList()[0]->unit()))
5122
15
                .as_nullable();
5123
15
    }
5124
5125
700
    auto &props = buildProperties(node);
5126
5127
700
    if (esriStyle_ && dbContext_) {
5128
18
        std::string outTableName;
5129
18
        std::string authNameFromAlias;
5130
18
        std::string codeFromAlias;
5131
18
        auto authFactory =
5132
18
            AuthorityFactory::create(NN_NO_CHECK(dbContext_), std::string());
5133
18
        const std::string vertCRSName = stripQuotes(nodeP->children()[0]);
5134
18
        auto officialName = authFactory->getOfficialNameFromAlias(
5135
18
            vertCRSName, "vertical_crs", "ESRI", false, outTableName,
5136
18
            authNameFromAlias, codeFromAlias);
5137
18
        if (!officialName.empty()) {
5138
0
            props.set(IdentifiedObject::NAME_KEY, officialName);
5139
0
        }
5140
18
    }
5141
5142
    // Deal with Lidar WKT1 VertCRS that embeds geoid model in CRS name,
5143
    // following conventions from
5144
    // https://pubs.usgs.gov/tm/11b4/pdf/tm11-B4.pdf
5145
    // page 9
5146
700
    if (ci_equal(nodeValue, WKTConstants::VERT_CS) ||
5147
627
        ci_equal(nodeValue, WKTConstants::VERTCS)) {
5148
627
        std::string name;
5149
627
        if (props.getStringValue(IdentifiedObject::NAME_KEY, name)) {
5150
627
            std::string navd88GeoidName;
5151
627
            for (const char *prefix :
5152
627
                 {"NAVD88 - ", "NAVD88 via ", "NAVD88 height - ",
5153
2.36k
                  "NAVD88 height (ftUS) - "}) {
5154
2.36k
                if (starts_with(name, prefix)) {
5155
92
                    navd88GeoidName = name.substr(strlen(prefix));
5156
92
                    auto pos = navd88GeoidName.find_first_of(" (");
5157
92
                    if (pos != std::string::npos) {
5158
65
                        navd88GeoidName.resize(pos);
5159
65
                    }
5160
92
                    break;
5161
92
                }
5162
2.36k
            }
5163
5164
            // Deal with vertical CRS names like "Geoid 2012A"
5165
627
            if (navd88GeoidName.empty() && ci_starts_with(name, "Geoid") &&
5166
2
                geogCRSOfCompoundCRS_ &&
5167
0
                starts_with(geogCRSOfCompoundCRS_->nameStr(), "NAD83")) {
5168
                // Remove spaces
5169
0
                navd88GeoidName = replaceAll(name, " ", "");
5170
                // Morph "Geoid 20XX[Y]" to "GeoidXX[Y]"
5171
0
                if (navd88GeoidName.size() >= 9 &&
5172
0
                    ci_starts_with(navd88GeoidName, "Geoid20") &&
5173
0
                    navd88GeoidName[7] >= '0' && navd88GeoidName[7] <= '9' &&
5174
0
                    navd88GeoidName[8] >= '0' && navd88GeoidName[8] <= '9') {
5175
0
                    navd88GeoidName = "Geoid" + navd88GeoidName.substr(7);
5176
0
                }
5177
0
            }
5178
5179
627
            if (!navd88GeoidName.empty()) {
5180
92
                const auto &axis = verticalCS->axisList()[0];
5181
92
                const auto &dir = axis->direction();
5182
92
                if (dir == cs::AxisDirection::UP) {
5183
87
                    if (axis->unit() == common::UnitOfMeasure::METRE) {
5184
71
                        props.set(IdentifiedObject::NAME_KEY, "NAVD88 height");
5185
71
                        props.set(Identifier::CODE_KEY, 5703);
5186
71
                        props.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
5187
71
                    } else if (axis->unit().name() == "US survey foot") {
5188
0
                        props.set(IdentifiedObject::NAME_KEY,
5189
0
                                  "NAVD88 height (ftUS)");
5190
0
                        props.set(Identifier::CODE_KEY, 6360);
5191
0
                        props.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
5192
0
                    }
5193
87
                }
5194
92
                PropertyMap propsModel;
5195
92
                propsModel.set(IdentifiedObject::NAME_KEY,
5196
92
                               toupper(navd88GeoidName));
5197
92
                PropertyMap propsDatum;
5198
92
                propsDatum.set(IdentifiedObject::NAME_KEY,
5199
92
                               "North American Vertical Datum 1988");
5200
92
                propsDatum.set(Identifier::CODE_KEY, 5103);
5201
92
                propsDatum.set(Identifier::CODESPACE_KEY, Identifier::EPSG);
5202
92
                vdatum =
5203
92
                    VerticalReferenceFrame::create(propsDatum).as_nullable();
5204
92
                const auto dummyCRS =
5205
92
                    VerticalCRS::create(PropertyMap(), vdatum, datumEnsemble,
5206
92
                                        NN_NO_CHECK(verticalCS));
5207
92
                const auto model(Transformation::create(
5208
92
                    propsModel, dummyCRS, dummyCRS, nullptr,
5209
92
                    OperationMethod::create(
5210
92
                        PropertyMap(), std::vector<OperationParameterNNPtr>()),
5211
92
                    {}, {}));
5212
92
                props.set("GEOID_MODEL", model);
5213
92
            }
5214
627
        }
5215
627
    }
5216
5217
700
    auto &geoidModelNode = nodeP->lookForChild(WKTConstants::GEOIDMODEL);
5218
700
    if (!isNull(geoidModelNode)) {
5219
72
        ArrayOfBaseObjectNNPtr arrayModels = ArrayOfBaseObject::create();
5220
690
        for (const auto &childNode : nodeP->children()) {
5221
690
            const auto &childNodeChildren = childNode->GP()->children();
5222
690
            if (childNodeChildren.size() >= 1 &&
5223
314
                ci_equal(childNode->GP()->value(), WKTConstants::GEOIDMODEL)) {
5224
172
                auto &propsModel = buildProperties(childNode);
5225
172
                const auto dummyCRS =
5226
172
                    VerticalCRS::create(PropertyMap(), vdatum, datumEnsemble,
5227
172
                                        NN_NO_CHECK(verticalCS));
5228
172
                const auto model(Transformation::create(
5229
172
                    propsModel, dummyCRS, dummyCRS, nullptr,
5230
172
                    OperationMethod::create(
5231
172
                        PropertyMap(), std::vector<OperationParameterNNPtr>()),
5232
172
                    {}, {}));
5233
172
                arrayModels->add(model);
5234
172
            }
5235
690
        }
5236
72
        props.set("GEOID_MODEL", arrayModels);
5237
72
    }
5238
5239
700
    auto crs = nn_static_pointer_cast<CRS>(VerticalCRS::create(
5240
700
        props, vdatum, datumEnsemble, NN_NO_CHECK(verticalCS)));
5241
5242
700
    if (!isNull(vdatumNode)) {
5243
602
        auto &extensionNode = vdatumNode->lookForChild(WKTConstants::EXTENSION);
5244
602
        const auto &extensionChildren = extensionNode->GP()->children();
5245
602
        if (extensionChildren.size() == 2) {
5246
15
            if (ci_equal(stripQuotes(extensionChildren[0]), "PROJ4_GRIDS")) {
5247
14
                const auto gridName(stripQuotes(extensionChildren[1]));
5248
                // This is the expansion of EPSG:5703 by old GDAL versions.
5249
                // See
5250
                // https://trac.osgeo.org/metacrs/changeset?reponame=&new=2281%40geotiff%2Ftrunk%2Flibgeotiff%2Fcsv%2Fvertcs.override.csv&old=1893%40geotiff%2Ftrunk%2Flibgeotiff%2Fcsv%2Fvertcs.override.csv
5251
                // It is unlikely that the user really explicitly wants this.
5252
14
                if (gridName != "g2003conus.gtx,g2003alaska.gtx,"
5253
14
                                "g2003h01.gtx,g2003p01.gtx" &&
5254
14
                    gridName != "g2012a_conus.gtx,g2012a_alaska.gtx,"
5255
14
                                "g2012a_guam.gtx,g2012a_hawaii.gtx,"
5256
14
                                "g2012a_puertorico.gtx,g2012a_samoa.gtx") {
5257
14
                    auto geogCRS =
5258
14
                        geogCRSOfCompoundCRS_ &&
5259
0
                                geogCRSOfCompoundCRS_->primeMeridian()
5260
0
                                        ->longitude()
5261
0
                                        .getSIValue() == 0 &&
5262
0
                                geogCRSOfCompoundCRS_->coordinateSystem()
5263
0
                                        ->axisList()[0]
5264
0
                                        ->unit() == UnitOfMeasure::DEGREE
5265
14
                            ? geogCRSOfCompoundCRS_->promoteTo3D(std::string(),
5266
0
                                                                 dbContext_)
5267
14
                            : GeographicCRS::EPSG_4979;
5268
5269
14
                    auto sourceTransformationCRS =
5270
14
                        createBoundCRSSourceTransformationCRS(
5271
14
                            crs.as_nullable(), geogCRS.as_nullable());
5272
14
                    auto transformation = Transformation::
5273
14
                        createGravityRelatedHeightToGeographic3D(
5274
14
                            PropertyMap().set(
5275
14
                                IdentifiedObject::NAME_KEY,
5276
14
                                sourceTransformationCRS->nameStr() + " to " +
5277
14
                                    geogCRS->nameStr() + " ellipsoidal height"),
5278
14
                            sourceTransformationCRS, geogCRS, nullptr, gridName,
5279
14
                            std::vector<PositionalAccuracyNNPtr>());
5280
14
                    return nn_static_pointer_cast<CRS>(
5281
14
                        BoundCRS::create(crs, geogCRS, transformation));
5282
14
                }
5283
14
            }
5284
15
        }
5285
602
    }
5286
5287
686
    return crs;
5288
700
}
5289
5290
// ---------------------------------------------------------------------------
5291
5292
DerivedVerticalCRSNNPtr
5293
3
WKTParser::Private::buildDerivedVerticalCRS(const WKTNodeNNPtr &node) {
5294
3
    const auto *nodeP = node->GP();
5295
3
    auto &baseVertCRSNode = nodeP->lookForChild(WKTConstants::BASEVERTCRS);
5296
    // given the constraints enforced on calling code path
5297
3
    assert(!isNull(baseVertCRSNode));
5298
5299
3
    auto baseVertCRS_tmp = buildVerticalCRS(baseVertCRSNode);
5300
3
    auto baseVertCRS = NN_NO_CHECK(baseVertCRS_tmp->extractVerticalCRS());
5301
5302
3
    auto &derivingConversionNode =
5303
3
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
5304
3
    if (isNull(derivingConversionNode)) {
5305
0
        ThrowMissing(WKTConstants::DERIVINGCONVERSION);
5306
0
    }
5307
3
    auto derivingConversion = buildConversion(
5308
3
        derivingConversionNode, UnitOfMeasure::NONE, UnitOfMeasure::NONE);
5309
5310
3
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
5311
3
    if (isNull(csNode)) {
5312
0
        ThrowMissing(WKTConstants::CS_);
5313
0
    }
5314
3
    auto cs = buildCS(csNode, node, UnitOfMeasure::NONE);
5315
5316
3
    auto verticalCS = nn_dynamic_pointer_cast<VerticalCS>(cs);
5317
3
    if (!verticalCS) {
5318
0
        throw ParsingException(
5319
0
            concat("vertical CS expected, but found ", cs->getWKT2Type(true)));
5320
0
    }
5321
5322
3
    return DerivedVerticalCRS::create(buildProperties(node), baseVertCRS,
5323
3
                                      derivingConversion,
5324
3
                                      NN_NO_CHECK(verticalCS));
5325
3
}
5326
5327
// ---------------------------------------------------------------------------
5328
5329
289
CRSNNPtr WKTParser::Private::buildCompoundCRS(const WKTNodeNNPtr &node) {
5330
289
    std::vector<CRSNNPtr> components;
5331
289
    bool bFirstNode = true;
5332
2.16k
    for (const auto &child : node->GP()->children()) {
5333
2.16k
        auto crs = buildCRS(child);
5334
2.16k
        if (crs) {
5335
720
            if (bFirstNode) {
5336
234
                geogCRSOfCompoundCRS_ = crs->extractGeographicCRS();
5337
234
                bFirstNode = false;
5338
234
            }
5339
720
            components.push_back(NN_NO_CHECK(crs));
5340
720
        }
5341
2.16k
    }
5342
5343
289
    if (ci_equal(node->GP()->value(), WKTConstants::COMPD_CS)) {
5344
187
        return CompoundCRS::createLax(buildProperties(node), components,
5345
187
                                      dbContext_);
5346
187
    } else {
5347
102
        return CompoundCRS::create(buildProperties(node), components);
5348
102
    }
5349
289
}
5350
5351
// ---------------------------------------------------------------------------
5352
5353
static TransformationNNPtr buildTransformationForBoundCRS(
5354
    DatabaseContextPtr &dbContext,
5355
    const util::PropertyMap &abridgedNodeProperties,
5356
    const util::PropertyMap &methodNodeProperties, const CRSNNPtr &sourceCRS,
5357
    const CRSNNPtr &targetCRS, std::vector<OperationParameterNNPtr> &parameters,
5358
0
    std::vector<ParameterValueNNPtr> &values) {
5359
5360
0
    auto interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter(
5361
0
        dbContext, parameters, values);
5362
5363
0
    const auto sourceTransformationCRS(
5364
0
        createBoundCRSSourceTransformationCRS(sourceCRS, targetCRS));
5365
0
    auto transformation = Transformation::create(
5366
0
        abridgedNodeProperties, sourceTransformationCRS, targetCRS,
5367
0
        interpolationCRS, methodNodeProperties, parameters, values,
5368
0
        std::vector<PositionalAccuracyNNPtr>());
5369
5370
    // If the transformation is a "Geographic3D to GravityRelatedHeight" one,
5371
    // then the sourceCRS is expected to be a GeographicCRS and the target a
5372
    // VerticalCRS. Due to how things work in a BoundCRS, we have the opposite,
5373
    // so use our "GravityRelatedHeight to Geographic3D" method instead.
5374
0
    if (Transformation::isGeographic3DToGravityRelatedHeight(
5375
0
            transformation->method(), true) &&
5376
0
        dynamic_cast<VerticalCRS *>(sourceTransformationCRS.get()) &&
5377
0
        dynamic_cast<GeographicCRS *>(targetCRS.get())) {
5378
0
        auto fileParameter = transformation->parameterValue(
5379
0
            EPSG_NAME_PARAMETER_GEOID_CORRECTION_FILENAME,
5380
0
            EPSG_CODE_PARAMETER_GEOID_CORRECTION_FILENAME);
5381
0
        if (fileParameter &&
5382
0
            fileParameter->type() == ParameterValue::Type::FILENAME) {
5383
0
            const auto &filename = fileParameter->valueFile();
5384
5385
0
            transformation =
5386
0
                Transformation::createGravityRelatedHeightToGeographic3D(
5387
0
                    abridgedNodeProperties, sourceTransformationCRS, targetCRS,
5388
0
                    interpolationCRS, filename,
5389
0
                    std::vector<PositionalAccuracyNNPtr>());
5390
0
        }
5391
0
    }
5392
0
    return transformation;
5393
0
}
5394
5395
// ---------------------------------------------------------------------------
5396
5397
16
BoundCRSNNPtr WKTParser::Private::buildBoundCRS(const WKTNodeNNPtr &node) {
5398
16
    const auto *nodeP = node->GP();
5399
16
    auto &abridgedNode =
5400
16
        nodeP->lookForChild(WKTConstants::ABRIDGEDTRANSFORMATION);
5401
16
    if (isNull(abridgedNode)) {
5402
7
        ThrowNotEnoughChildren(WKTConstants::ABRIDGEDTRANSFORMATION);
5403
7
    }
5404
5405
9
    auto &methodNode = abridgedNode->GP()->lookForChild(WKTConstants::METHOD);
5406
9
    if (isNull(methodNode)) {
5407
9
        ThrowMissing(WKTConstants::METHOD);
5408
9
    }
5409
0
    if (methodNode->GP()->childrenSize() == 0) {
5410
0
        ThrowNotEnoughChildren(WKTConstants::METHOD);
5411
0
    }
5412
5413
0
    auto &sourceCRSNode = nodeP->lookForChild(WKTConstants::SOURCECRS);
5414
0
    const auto &sourceCRSNodeChildren = sourceCRSNode->GP()->children();
5415
0
    if (sourceCRSNodeChildren.size() != 1) {
5416
0
        ThrowNotEnoughChildren(WKTConstants::SOURCECRS);
5417
0
    }
5418
0
    auto sourceCRS = buildCRS(sourceCRSNodeChildren[0]);
5419
0
    if (!sourceCRS) {
5420
0
        throw ParsingException("Invalid content in SOURCECRS node");
5421
0
    }
5422
5423
0
    auto &targetCRSNode = nodeP->lookForChild(WKTConstants::TARGETCRS);
5424
0
    const auto &targetCRSNodeChildren = targetCRSNode->GP()->children();
5425
0
    if (targetCRSNodeChildren.size() != 1) {
5426
0
        ThrowNotEnoughChildren(WKTConstants::TARGETCRS);
5427
0
    }
5428
0
    auto targetCRS = buildCRS(targetCRSNodeChildren[0]);
5429
0
    if (!targetCRS) {
5430
0
        throw ParsingException("Invalid content in TARGETCRS node");
5431
0
    }
5432
5433
0
    std::vector<OperationParameterNNPtr> parameters;
5434
0
    std::vector<ParameterValueNNPtr> values;
5435
0
    const auto &defaultLinearUnit = UnitOfMeasure::NONE;
5436
0
    const auto &defaultAngularUnit = UnitOfMeasure::NONE;
5437
0
    consumeParameters(abridgedNode, true, parameters, values, defaultLinearUnit,
5438
0
                      defaultAngularUnit);
5439
5440
0
    const auto nnSourceCRS = NN_NO_CHECK(sourceCRS);
5441
0
    const auto nnTargetCRS = NN_NO_CHECK(targetCRS);
5442
0
    const auto transformation = buildTransformationForBoundCRS(
5443
0
        dbContext_, buildProperties(abridgedNode), buildProperties(methodNode),
5444
0
        nnSourceCRS, nnTargetCRS, parameters, values);
5445
5446
0
    return BoundCRS::create(buildProperties(node, false, false),
5447
0
                            NN_NO_CHECK(sourceCRS), NN_NO_CHECK(targetCRS),
5448
0
                            transformation);
5449
0
}
5450
5451
// ---------------------------------------------------------------------------
5452
5453
TemporalCSNNPtr
5454
7
WKTParser::Private::buildTemporalCS(const WKTNodeNNPtr &parentNode) {
5455
5456
7
    auto &csNode = parentNode->GP()->lookForChild(WKTConstants::CS_);
5457
7
    if (isNull(csNode) &&
5458
4
        !ci_equal(parentNode->GP()->value(), WKTConstants::BASETIMECRS)) {
5459
4
        ThrowMissing(WKTConstants::CS_);
5460
4
    }
5461
3
    auto cs = buildCS(csNode, parentNode, UnitOfMeasure::NONE);
5462
3
    auto temporalCS = nn_dynamic_pointer_cast<TemporalCS>(cs);
5463
3
    if (!temporalCS) {
5464
0
        ThrowNotExpectedCSType(TemporalCS::WKT2_2015_TYPE);
5465
0
    }
5466
3
    return NN_NO_CHECK(temporalCS);
5467
3
}
5468
5469
// ---------------------------------------------------------------------------
5470
5471
TemporalCRSNNPtr
5472
14
WKTParser::Private::buildTemporalCRS(const WKTNodeNNPtr &node) {
5473
14
    auto &datumNode =
5474
14
        node->GP()->lookForChild(WKTConstants::TDATUM, WKTConstants::TIMEDATUM);
5475
14
    if (isNull(datumNode)) {
5476
7
        throw ParsingException("Missing TDATUM / TIMEDATUM node");
5477
7
    }
5478
5479
7
    return TemporalCRS::create(buildProperties(node),
5480
7
                               buildTemporalDatum(datumNode),
5481
7
                               buildTemporalCS(node));
5482
14
}
5483
5484
// ---------------------------------------------------------------------------
5485
5486
DerivedTemporalCRSNNPtr
5487
2
WKTParser::Private::buildDerivedTemporalCRS(const WKTNodeNNPtr &node) {
5488
2
    const auto *nodeP = node->GP();
5489
2
    auto &baseCRSNode = nodeP->lookForChild(WKTConstants::BASETIMECRS);
5490
    // given the constraints enforced on calling code path
5491
2
    assert(!isNull(baseCRSNode));
5492
5493
2
    auto &derivingConversionNode =
5494
2
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
5495
2
    if (isNull(derivingConversionNode)) {
5496
2
        ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION);
5497
2
    }
5498
5499
0
    return DerivedTemporalCRS::create(
5500
0
        buildProperties(node), buildTemporalCRS(baseCRSNode),
5501
0
        buildConversion(derivingConversionNode, UnitOfMeasure::NONE,
5502
0
                        UnitOfMeasure::NONE),
5503
0
        buildTemporalCS(node));
5504
2
}
5505
5506
// ---------------------------------------------------------------------------
5507
5508
EngineeringCRSNNPtr
5509
2
WKTParser::Private::buildEngineeringCRS(const WKTNodeNNPtr &node) {
5510
2
    const auto *nodeP = node->GP();
5511
2
    auto &datumNode = nodeP->lookForChild(WKTConstants::EDATUM,
5512
2
                                          WKTConstants::ENGINEERINGDATUM);
5513
2
    if (isNull(datumNode)) {
5514
2
        throw ParsingException("Missing EDATUM / ENGINEERINGDATUM node");
5515
2
    }
5516
5517
0
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
5518
0
    if (isNull(csNode) && !ci_equal(nodeP->value(), WKTConstants::BASEENGCRS)) {
5519
0
        ThrowMissing(WKTConstants::CS_);
5520
0
    }
5521
5522
0
    auto cs = buildCS(csNode, node, UnitOfMeasure::NONE);
5523
0
    return EngineeringCRS::create(buildProperties(node),
5524
0
                                  buildEngineeringDatum(datumNode), cs);
5525
0
}
5526
5527
// ---------------------------------------------------------------------------
5528
5529
EngineeringCRSNNPtr
5530
356
WKTParser::Private::buildEngineeringCRSFromLocalCS(const WKTNodeNNPtr &node) {
5531
356
    auto &datumNode = node->GP()->lookForChild(WKTConstants::LOCAL_DATUM);
5532
356
    auto cs = buildCS(null_node, node, UnitOfMeasure::NONE);
5533
356
    auto datum = EngineeringDatum::create(
5534
356
        !isNull(datumNode)
5535
356
            ? buildProperties(datumNode)
5536
356
            :
5537
            // In theory OGC 01-009 mandates LOCAL_DATUM, but GDAL
5538
            // has a tradition of emitting just LOCAL_CS["foo"]
5539
356
            []() {
5540
271
                PropertyMap map;
5541
271
                map.set(IdentifiedObject::NAME_KEY, UNKNOWN_ENGINEERING_DATUM);
5542
271
                return map;
5543
271
            }());
5544
356
    return EngineeringCRS::create(buildProperties(node), datum, cs);
5545
356
}
5546
5547
// ---------------------------------------------------------------------------
5548
5549
DerivedEngineeringCRSNNPtr
5550
0
WKTParser::Private::buildDerivedEngineeringCRS(const WKTNodeNNPtr &node) {
5551
0
    const auto *nodeP = node->GP();
5552
0
    auto &baseEngCRSNode = nodeP->lookForChild(WKTConstants::BASEENGCRS);
5553
    // given the constraints enforced on calling code path
5554
0
    assert(!isNull(baseEngCRSNode));
5555
5556
0
    auto baseEngCRS = buildEngineeringCRS(baseEngCRSNode);
5557
5558
0
    auto &derivingConversionNode =
5559
0
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
5560
0
    if (isNull(derivingConversionNode)) {
5561
0
        ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION);
5562
0
    }
5563
0
    auto derivingConversion = buildConversion(
5564
0
        derivingConversionNode, UnitOfMeasure::NONE, UnitOfMeasure::NONE);
5565
5566
0
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
5567
0
    if (isNull(csNode)) {
5568
0
        ThrowMissing(WKTConstants::CS_);
5569
0
    }
5570
0
    auto cs = buildCS(csNode, node, UnitOfMeasure::NONE);
5571
5572
0
    return DerivedEngineeringCRS::create(buildProperties(node), baseEngCRS,
5573
0
                                         derivingConversion, cs);
5574
0
}
5575
5576
// ---------------------------------------------------------------------------
5577
5578
ParametricCSNNPtr
5579
0
WKTParser::Private::buildParametricCS(const WKTNodeNNPtr &parentNode) {
5580
5581
0
    auto &csNode = parentNode->GP()->lookForChild(WKTConstants::CS_);
5582
0
    if (isNull(csNode) &&
5583
0
        !ci_equal(parentNode->GP()->value(), WKTConstants::BASEPARAMCRS)) {
5584
0
        ThrowMissing(WKTConstants::CS_);
5585
0
    }
5586
0
    auto cs = buildCS(csNode, parentNode, UnitOfMeasure::NONE);
5587
0
    auto parametricCS = nn_dynamic_pointer_cast<ParametricCS>(cs);
5588
0
    if (!parametricCS) {
5589
0
        ThrowNotExpectedCSType(ParametricCS::WKT2_TYPE);
5590
0
    }
5591
0
    return NN_NO_CHECK(parametricCS);
5592
0
}
5593
5594
// ---------------------------------------------------------------------------
5595
5596
ParametricCRSNNPtr
5597
9
WKTParser::Private::buildParametricCRS(const WKTNodeNNPtr &node) {
5598
9
    auto &datumNode = node->GP()->lookForChild(WKTConstants::PDATUM,
5599
9
                                               WKTConstants::PARAMETRICDATUM);
5600
9
    if (isNull(datumNode)) {
5601
9
        throw ParsingException("Missing PDATUM / PARAMETRICDATUM node");
5602
9
    }
5603
5604
0
    return ParametricCRS::create(buildProperties(node),
5605
0
                                 buildParametricDatum(datumNode),
5606
0
                                 buildParametricCS(node));
5607
9
}
5608
5609
// ---------------------------------------------------------------------------
5610
5611
DerivedParametricCRSNNPtr
5612
3
WKTParser::Private::buildDerivedParametricCRS(const WKTNodeNNPtr &node) {
5613
3
    const auto *nodeP = node->GP();
5614
3
    auto &baseParamCRSNode = nodeP->lookForChild(WKTConstants::BASEPARAMCRS);
5615
    // given the constraints enforced on calling code path
5616
3
    assert(!isNull(baseParamCRSNode));
5617
5618
3
    auto &derivingConversionNode =
5619
3
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
5620
3
    if (isNull(derivingConversionNode)) {
5621
3
        ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION);
5622
3
    }
5623
5624
0
    return DerivedParametricCRS::create(
5625
0
        buildProperties(node), buildParametricCRS(baseParamCRSNode),
5626
0
        buildConversion(derivingConversionNode, UnitOfMeasure::NONE,
5627
0
                        UnitOfMeasure::NONE),
5628
0
        buildParametricCS(node));
5629
3
}
5630
5631
// ---------------------------------------------------------------------------
5632
5633
DerivedProjectedCRSNNPtr
5634
2
WKTParser::Private::buildDerivedProjectedCRS(const WKTNodeNNPtr &node) {
5635
2
    const auto *nodeP = node->GP();
5636
2
    auto &baseProjCRSNode = nodeP->lookForChild(WKTConstants::BASEPROJCRS);
5637
2
    if (isNull(baseProjCRSNode)) {
5638
2
        ThrowNotEnoughChildren(WKTConstants::BASEPROJCRS);
5639
2
    }
5640
0
    auto baseProjCRS = buildProjectedCRS(baseProjCRSNode);
5641
5642
0
    auto &conversionNode =
5643
0
        nodeP->lookForChild(WKTConstants::DERIVINGCONVERSION);
5644
0
    if (isNull(conversionNode)) {
5645
0
        ThrowNotEnoughChildren(WKTConstants::DERIVINGCONVERSION);
5646
0
    }
5647
5648
0
    auto linearUnit = buildUnitInSubNode(node);
5649
0
    const auto &angularUnit =
5650
0
        baseProjCRS->baseCRS()->coordinateSystem()->axisList()[0]->unit();
5651
5652
0
    auto conversion = buildConversion(conversionNode, linearUnit, angularUnit);
5653
5654
0
    auto &csNode = nodeP->lookForChild(WKTConstants::CS_);
5655
0
    if (isNull(csNode) && !ci_equal(nodeP->value(), WKTConstants::PROJCS)) {
5656
0
        ThrowMissing(WKTConstants::CS_);
5657
0
    }
5658
0
    auto cs = buildCS(csNode, node, UnitOfMeasure::NONE);
5659
5660
0
    if (cs->axisList().size() == 3 &&
5661
0
        baseProjCRS->coordinateSystem()->axisList().size() == 2) {
5662
0
        baseProjCRS = NN_NO_CHECK(util::nn_dynamic_pointer_cast<ProjectedCRS>(
5663
0
            baseProjCRS->promoteTo3D(std::string(), dbContext_)));
5664
0
    }
5665
5666
0
    return DerivedProjectedCRS::create(buildProperties(node), baseProjCRS,
5667
0
                                       conversion, cs);
5668
0
}
5669
5670
// ---------------------------------------------------------------------------
5671
5672
CoordinateMetadataNNPtr
5673
4
WKTParser::Private::buildCoordinateMetadata(const WKTNodeNNPtr &node) {
5674
4
    const auto *nodeP = node->GP();
5675
5676
4
    const auto &l_children = nodeP->children();
5677
4
    if (l_children.empty()) {
5678
0
        ThrowNotEnoughChildren(WKTConstants::COORDINATEMETADATA);
5679
0
    }
5680
5681
4
    auto crs = buildCRS(l_children[0]);
5682
4
    if (!crs) {
5683
1
        throw ParsingException("Invalid content in CRS node");
5684
1
    }
5685
5686
3
    auto &epochNode = nodeP->lookForChild(WKTConstants::EPOCH);
5687
3
    if (!isNull(epochNode)) {
5688
0
        const auto &epochChildren = epochNode->GP()->children();
5689
0
        if (epochChildren.empty()) {
5690
0
            ThrowMissing(WKTConstants::EPOCH);
5691
0
        }
5692
0
        double coordinateEpoch;
5693
0
        try {
5694
0
            coordinateEpoch = asDouble(epochChildren[0]);
5695
0
        } catch (const std::exception &) {
5696
0
            throw ParsingException("Invalid EPOCH node");
5697
0
        }
5698
0
        return CoordinateMetadata::create(NN_NO_CHECK(crs), coordinateEpoch,
5699
0
                                          dbContext_);
5700
0
    }
5701
5702
3
    return CoordinateMetadata::create(NN_NO_CHECK(crs));
5703
3
}
5704
5705
// ---------------------------------------------------------------------------
5706
5707
4.64k
static bool isGeodeticCRS(const std::string &name) {
5708
4.64k
    return ci_equal(name, WKTConstants::GEODCRS) ||       // WKT2
5709
4.64k
           ci_equal(name, WKTConstants::GEODETICCRS) ||   // WKT2
5710
4.64k
           ci_equal(name, WKTConstants::GEOGCRS) ||       // WKT2 2019
5711
4.64k
           ci_equal(name, WKTConstants::GEOGRAPHICCRS) || // WKT2 2019
5712
4.64k
           ci_equal(name, WKTConstants::GEOGCS) ||        // WKT1
5713
4.14k
           ci_equal(name, WKTConstants::GEOCCS);          // WKT1
5714
4.64k
}
5715
5716
// ---------------------------------------------------------------------------
5717
5718
4.64k
CRSPtr WKTParser::Private::buildCRS(const WKTNodeNNPtr &node) {
5719
4.64k
    const auto *nodeP = node->GP();
5720
4.64k
    const std::string &name(nodeP->value());
5721
5722
4.64k
    const auto applyHorizontalBoundCRSParams = [&](const CRSNNPtr &crs) {
5723
872
        if (!toWGS84Parameters_.empty()) {
5724
0
            auto ret = BoundCRS::createFromTOWGS84(crs, toWGS84Parameters_);
5725
0
            toWGS84Parameters_.clear();
5726
0
            return util::nn_static_pointer_cast<CRS>(ret);
5727
872
        } else if (!datumPROJ4Grids_.empty()) {
5728
0
            auto ret = BoundCRS::createFromNadgrids(crs, datumPROJ4Grids_);
5729
0
            datumPROJ4Grids_.clear();
5730
0
            return util::nn_static_pointer_cast<CRS>(ret);
5731
0
        }
5732
872
        return crs;
5733
872
    };
5734
5735
4.64k
    if (isGeodeticCRS(name)) {
5736
596
        if (!isNull(nodeP->lookForChild(WKTConstants::BASEGEOGCRS,
5737
596
                                        WKTConstants::BASEGEODCRS))) {
5738
0
            return util::nn_static_pointer_cast<CRS>(
5739
0
                applyHorizontalBoundCRSParams(buildDerivedGeodeticCRS(node)));
5740
596
        } else {
5741
596
            return util::nn_static_pointer_cast<CRS>(
5742
596
                applyHorizontalBoundCRSParams(buildGeodeticCRS(node)));
5743
596
        }
5744
596
    }
5745
5746
4.05k
    if (ci_equal(name, WKTConstants::PROJCS) ||
5747
3.21k
        ci_equal(name, WKTConstants::PROJCRS) ||
5748
3.20k
        ci_equal(name, WKTConstants::PROJECTEDCRS)) {
5749
        // Get the EXTENSION "PROJ4" node before attempting to call
5750
        // buildProjectedCRS() since formulations of WKT1_GDAL from GDAL 2.x
5751
        // with the netCDF driver and the lack the required UNIT[] node
5752
843
        std::string projString = getExtensionProj4(nodeP);
5753
843
        if (!projString.empty() &&
5754
129
            (starts_with(projString, "+proj=ob_tran +o_proj=longlat") ||
5755
66
             starts_with(projString, "+proj=ob_tran +o_proj=lonlat") ||
5756
66
             starts_with(projString, "+proj=ob_tran +o_proj=latlong") ||
5757
97
             starts_with(projString, "+proj=ob_tran +o_proj=latlon"))) {
5758
            // Those are not a projected CRS, but a DerivedGeographic one...
5759
97
            if (projString.find(" +type=crs") == std::string::npos) {
5760
97
                projString += " +type=crs";
5761
97
            }
5762
97
            try {
5763
97
                auto projObj =
5764
97
                    PROJStringParser().createFromPROJString(projString);
5765
97
                auto crs = nn_dynamic_pointer_cast<CRS>(projObj);
5766
97
                if (crs) {
5767
45
                    return util::nn_static_pointer_cast<CRS>(
5768
45
                        applyHorizontalBoundCRSParams(NN_NO_CHECK(crs)));
5769
45
                }
5770
97
            } catch (const io::ParsingException &) {
5771
42
            }
5772
97
        }
5773
796
        return util::nn_static_pointer_cast<CRS>(
5774
796
            applyHorizontalBoundCRSParams(buildProjectedCRS(node)));
5775
843
    }
5776
5777
3.20k
    if (ci_equal(name, WKTConstants::VERT_CS) ||
5778
3.18k
        ci_equal(name, WKTConstants::VERTCS) ||
5779
2.63k
        ci_equal(name, WKTConstants::VERTCRS) ||
5780
2.63k
        ci_equal(name, WKTConstants::VERTICALCRS)) {
5781
574
        if (!isNull(nodeP->lookForChild(WKTConstants::BASEVERTCRS))) {
5782
3
            return util::nn_static_pointer_cast<CRS>(
5783
3
                buildDerivedVerticalCRS(node));
5784
571
        } else {
5785
571
            return util::nn_static_pointer_cast<CRS>(buildVerticalCRS(node));
5786
571
        }
5787
574
    }
5788
5789
2.63k
    if (ci_equal(name, WKTConstants::COMPD_CS) ||
5790
2.34k
        ci_equal(name, WKTConstants::COMPOUNDCRS)) {
5791
289
        return util::nn_static_pointer_cast<CRS>(buildCompoundCRS(node));
5792
289
    }
5793
5794
2.34k
    if (ci_equal(name, WKTConstants::BOUNDCRS)) {
5795
16
        return util::nn_static_pointer_cast<CRS>(buildBoundCRS(node));
5796
16
    }
5797
5798
2.33k
    if (ci_equal(name, WKTConstants::TIMECRS)) {
5799
16
        if (!isNull(nodeP->lookForChild(WKTConstants::BASETIMECRS))) {
5800
2
            return util::nn_static_pointer_cast<CRS>(
5801
2
                buildDerivedTemporalCRS(node));
5802
14
        } else {
5803
14
            return util::nn_static_pointer_cast<CRS>(buildTemporalCRS(node));
5804
14
        }
5805
16
    }
5806
5807
2.31k
    if (ci_equal(name, WKTConstants::DERIVEDPROJCRS)) {
5808
2
        return util::nn_static_pointer_cast<CRS>(
5809
2
            buildDerivedProjectedCRS(node));
5810
2
    }
5811
5812
2.31k
    if (ci_equal(name, WKTConstants::ENGCRS) ||
5813
2.31k
        ci_equal(name, WKTConstants::ENGINEERINGCRS)) {
5814
2
        if (!isNull(nodeP->lookForChild(WKTConstants::BASEENGCRS))) {
5815
0
            return util::nn_static_pointer_cast<CRS>(
5816
0
                buildDerivedEngineeringCRS(node));
5817
2
        } else {
5818
2
            return util::nn_static_pointer_cast<CRS>(buildEngineeringCRS(node));
5819
2
        }
5820
2
    }
5821
5822
2.31k
    if (ci_equal(name, WKTConstants::LOCAL_CS)) {
5823
356
        return util::nn_static_pointer_cast<CRS>(
5824
356
            buildEngineeringCRSFromLocalCS(node));
5825
356
    }
5826
5827
1.95k
    if (ci_equal(name, WKTConstants::PARAMETRICCRS)) {
5828
12
        if (!isNull(nodeP->lookForChild(WKTConstants::BASEPARAMCRS))) {
5829
3
            return util::nn_static_pointer_cast<CRS>(
5830
3
                buildDerivedParametricCRS(node));
5831
9
        } else {
5832
9
            return util::nn_static_pointer_cast<CRS>(buildParametricCRS(node));
5833
9
        }
5834
12
    }
5835
5836
1.94k
    return nullptr;
5837
1.95k
}
5838
5839
// ---------------------------------------------------------------------------
5840
5841
2.23k
BaseObjectNNPtr WKTParser::Private::build(const WKTNodeNNPtr &node) {
5842
2.23k
    const auto *nodeP = node->GP();
5843
2.23k
    const std::string &name(nodeP->value());
5844
5845
2.23k
    auto crs = buildCRS(node);
5846
2.23k
    if (crs) {
5847
735
        return util::nn_static_pointer_cast<BaseObject>(NN_NO_CHECK(crs));
5848
735
    }
5849
5850
    // Datum handled by caller code WKTParser::createFromWKT()
5851
5852
1.50k
    if (ci_equal(name, WKTConstants::ENSEMBLE)) {
5853
7
        return util::nn_static_pointer_cast<BaseObject>(buildDatumEnsemble(
5854
7
            node, PrimeMeridian::GREENWICH,
5855
7
            !isNull(nodeP->lookForChild(WKTConstants::ELLIPSOID))));
5856
7
    }
5857
5858
1.49k
    if (ci_equal(name, WKTConstants::VDATUM) ||
5859
589
        ci_equal(name, WKTConstants::VERT_DATUM) ||
5860
588
        ci_equal(name, WKTConstants::VERTICALDATUM) ||
5861
588
        ci_equal(name, WKTConstants::VRF)) {
5862
154
        return util::nn_static_pointer_cast<BaseObject>(
5863
154
            buildVerticalReferenceFrame(node, null_node));
5864
154
    }
5865
5866
1.34k
    if (ci_equal(name, WKTConstants::TDATUM) ||
5867
420
        ci_equal(name, WKTConstants::TIMEDATUM)) {
5868
16
        return util::nn_static_pointer_cast<BaseObject>(
5869
16
            buildTemporalDatum(node));
5870
16
    }
5871
5872
1.32k
    if (ci_equal(name, WKTConstants::EDATUM) ||
5873
412
        ci_equal(name, WKTConstants::ENGINEERINGDATUM)) {
5874
7
        return util::nn_static_pointer_cast<BaseObject>(
5875
7
            buildEngineeringDatum(node));
5876
7
    }
5877
5878
1.31k
    if (ci_equal(name, WKTConstants::PDATUM) ||
5879
406
        ci_equal(name, WKTConstants::PARAMETRICDATUM)) {
5880
6
        return util::nn_static_pointer_cast<BaseObject>(
5881
6
            buildParametricDatum(node));
5882
6
    }
5883
5884
1.31k
    if (ci_equal(name, WKTConstants::ELLIPSOID) ||
5885
406
        ci_equal(name, WKTConstants::SPHEROID)) {
5886
4
        return util::nn_static_pointer_cast<BaseObject>(buildEllipsoid(node));
5887
4
    }
5888
5889
1.30k
    if (ci_equal(name, WKTConstants::COORDINATEOPERATION)) {
5890
11
        auto transf = buildCoordinateOperation(node);
5891
5892
11
        const char *prefixes[] = {
5893
11
            "PROJ-based operation method: ",
5894
11
            "PROJ-based operation method (approximate): "};
5895
11
        for (const char *prefix : prefixes) {
5896
0
            if (starts_with(transf->method()->nameStr(), prefix)) {
5897
0
                auto projString =
5898
0
                    transf->method()->nameStr().substr(strlen(prefix));
5899
0
                return util::nn_static_pointer_cast<BaseObject>(
5900
0
                    PROJBasedOperation::create(
5901
0
                        PropertyMap(), projString, transf->sourceCRS(),
5902
0
                        transf->targetCRS(),
5903
0
                        transf->coordinateOperationAccuracies()));
5904
0
            }
5905
0
        }
5906
5907
11
        return util::nn_static_pointer_cast<BaseObject>(transf);
5908
11
    }
5909
5910
1.29k
    if (ci_equal(name, WKTConstants::CONVERSION)) {
5911
348
        auto conv =
5912
348
            buildConversion(node, UnitOfMeasure::METRE, UnitOfMeasure::DEGREE);
5913
5914
348
        if (starts_with(conv->method()->nameStr(),
5915
348
                        "PROJ-based operation method: ")) {
5916
1
            auto projString = conv->method()->nameStr().substr(
5917
1
                strlen("PROJ-based operation method: "));
5918
1
            return util::nn_static_pointer_cast<BaseObject>(
5919
1
                PROJBasedOperation::create(PropertyMap(), projString, nullptr,
5920
1
                                           nullptr, {}));
5921
1
        }
5922
5923
347
        return util::nn_static_pointer_cast<BaseObject>(conv);
5924
348
    }
5925
5926
950
    if (ci_equal(name, WKTConstants::CONCATENATEDOPERATION)) {
5927
5
        return util::nn_static_pointer_cast<BaseObject>(
5928
5
            buildConcatenatedOperation(node));
5929
5
    }
5930
5931
945
    if (ci_equal(name, WKTConstants::POINTMOTIONOPERATION)) {
5932
1
        return util::nn_static_pointer_cast<BaseObject>(
5933
1
            buildPointMotionOperation(node));
5934
1
    }
5935
5936
944
    if (ci_equal(name, WKTConstants::ID) ||
5937
28
        ci_equal(name, WKTConstants::AUTHORITY)) {
5938
28
        return util::nn_static_pointer_cast<BaseObject>(
5939
28
            NN_NO_CHECK(buildId(node, node, false, false)));
5940
28
    }
5941
5942
916
    if (ci_equal(name, WKTConstants::COORDINATEMETADATA)) {
5943
4
        return util::nn_static_pointer_cast<BaseObject>(
5944
4
            buildCoordinateMetadata(node));
5945
4
    }
5946
5947
912
    throw ParsingException(concat("unhandled keyword: ", name));
5948
916
}
5949
//! @endcond
5950
5951
// ---------------------------------------------------------------------------
5952
5953
//! @cond Doxygen_Suppress
5954
class JSONParser {
5955
    DatabaseContextPtr dbContext_{};
5956
    std::string deformationModelName_{};
5957
    PJ_CONTEXT *ctx_ = nullptr;
5958
5959
    static std::string getString(const json &j, const char *key);
5960
    static json getObject(const json &j, const char *key);
5961
    static json getArray(const json &j, const char *key);
5962
    static int getInteger(const json &j, const char *key);
5963
    static double getNumber(const json &j, const char *key);
5964
    static UnitOfMeasure getUnit(const json &j, const char *key);
5965
    static std::string getName(const json &j);
5966
    static std::string getType(const json &j);
5967
    static Length getLength(const json &j, const char *key);
5968
    static Measure getMeasure(const json &j);
5969
5970
    IdentifierNNPtr buildId(const json &parentJ, const json &j,
5971
                            bool removeInverseOf);
5972
    static ObjectDomainPtr buildObjectDomain(const json &j);
5973
    PropertyMap buildProperties(const json &j, bool removeInverseOf = false,
5974
                                bool nameRequired = true);
5975
5976
    GeographicCRSNNPtr buildGeographicCRS(const json &j);
5977
    GeodeticCRSNNPtr buildGeodeticCRS(const json &j);
5978
    ProjectedCRSNNPtr buildProjectedCRS(const json &j);
5979
    ConversionNNPtr buildConversion(const json &j);
5980
    DatumEnsembleNNPtr buildDatumEnsemble(const json &j);
5981
    GeodeticReferenceFrameNNPtr buildGeodeticReferenceFrame(const json &j);
5982
    VerticalReferenceFrameNNPtr buildVerticalReferenceFrame(const json &j);
5983
    DynamicGeodeticReferenceFrameNNPtr
5984
    buildDynamicGeodeticReferenceFrame(const json &j);
5985
    DynamicVerticalReferenceFrameNNPtr
5986
    buildDynamicVerticalReferenceFrame(const json &j);
5987
    EllipsoidNNPtr buildEllipsoid(const json &j);
5988
    PrimeMeridianNNPtr buildPrimeMeridian(const json &j);
5989
    CoordinateSystemNNPtr buildCS(const json &j);
5990
    MeridianNNPtr buildMeridian(const json &j);
5991
    CoordinateSystemAxisNNPtr buildAxis(const json &j);
5992
    VerticalCRSNNPtr buildVerticalCRS(const json &j);
5993
    CRSNNPtr buildCRS(const json &j);
5994
    CompoundCRSNNPtr buildCompoundCRS(const json &j);
5995
    BoundCRSNNPtr buildBoundCRS(const json &j);
5996
    TransformationNNPtr buildTransformation(const json &j);
5997
    PointMotionOperationNNPtr buildPointMotionOperation(const json &j);
5998
    ConcatenatedOperationNNPtr buildConcatenatedOperation(const json &j);
5999
    CoordinateMetadataNNPtr buildCoordinateMetadata(const json &j);
6000
6001
    void buildGeodeticDatumOrDatumEnsemble(const json &j,
6002
                                           GeodeticReferenceFramePtr &datum,
6003
                                           DatumEnsemblePtr &datumEnsemble);
6004
6005
16
    static util::optional<std::string> getAnchor(const json &j) {
6006
16
        util::optional<std::string> anchor;
6007
16
        if (j.contains("anchor")) {
6008
0
            anchor = getString(j, "anchor");
6009
0
        }
6010
16
        return anchor;
6011
16
    }
6012
6013
0
    static util::optional<common::Measure> getAnchorEpoch(const json &j) {
6014
0
        if (j.contains("anchor_epoch")) {
6015
0
            return util::optional<common::Measure>(common::Measure(
6016
0
                getNumber(j, "anchor_epoch"), common::UnitOfMeasure::YEAR));
6017
0
        }
6018
0
        return util::optional<common::Measure>();
6019
0
    }
6020
6021
20
    EngineeringDatumNNPtr buildEngineeringDatum(const json &j) {
6022
20
        return EngineeringDatum::create(buildProperties(j), getAnchor(j));
6023
20
    }
6024
6025
0
    ParametricDatumNNPtr buildParametricDatum(const json &j) {
6026
0
        return ParametricDatum::create(buildProperties(j), getAnchor(j));
6027
0
    }
6028
6029
0
    TemporalDatumNNPtr buildTemporalDatum(const json &j) {
6030
0
        auto calendar = getString(j, "calendar");
6031
0
        auto origin = DateTime::create(j.contains("time_origin")
6032
0
                                           ? getString(j, "time_origin")
6033
0
                                           : std::string());
6034
0
        return TemporalDatum::create(buildProperties(j), origin, calendar);
6035
0
    }
6036
6037
    template <class TargetCRS, class DatumBuilderType,
6038
              class CSClass = CoordinateSystem>
6039
    util::nn<std::shared_ptr<TargetCRS>> buildCRS(const json &j,
6040
0
                                                  DatumBuilderType f) {
6041
0
        auto datum = (this->*f)(getObject(j, "datum"));
6042
0
        auto cs = buildCS(getObject(j, "coordinate_system"));
6043
0
        auto csCast = util::nn_dynamic_pointer_cast<CSClass>(cs);
6044
0
        if (!csCast) {
6045
0
            throw ParsingException("coordinate_system not of expected type");
6046
0
        }
6047
0
        return TargetCRS::create(buildProperties(j), datum,
6048
0
                                 NN_NO_CHECK(csCast));
6049
0
    }
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::EngineeringCRS> > osgeo::proj::io::JSONParser::buildCRS<osgeo::proj::crs::EngineeringCRS, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::EngineeringDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&), osgeo::proj::cs::CoordinateSystem>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::EngineeringDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&))
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::ParametricCRS> > osgeo::proj::io::JSONParser::buildCRS<osgeo::proj::crs::ParametricCRS, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::ParametricDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&), osgeo::proj::cs::ParametricCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::ParametricDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&))
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::TemporalCRS> > osgeo::proj::io::JSONParser::buildCRS<osgeo::proj::crs::TemporalCRS, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::TemporalDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&), osgeo::proj::cs::TemporalCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&, dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::datum::TemporalDatum> > (osgeo::proj::io::JSONParser::*)(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&))
6050
6051
    template <class TargetCRS, class BaseCRS, class CSClass = CoordinateSystem>
6052
0
    util::nn<std::shared_ptr<TargetCRS>> buildDerivedCRS(const json &j) {
6053
0
        auto baseCRSObj = create(getObject(j, "base_crs"));
6054
0
        auto baseCRS = util::nn_dynamic_pointer_cast<BaseCRS>(baseCRSObj);
6055
0
        if (!baseCRS) {
6056
0
            throw ParsingException("base_crs not of expected type");
6057
0
        }
6058
0
        auto cs = buildCS(getObject(j, "coordinate_system"));
6059
0
        auto csCast = util::nn_dynamic_pointer_cast<CSClass>(cs);
6060
0
        if (!csCast) {
6061
0
            throw ParsingException("coordinate_system not of expected type");
6062
0
        }
6063
0
        auto conv = buildConversion(getObject(j, "conversion"));
6064
0
        return TargetCRS::create(buildProperties(j), NN_NO_CHECK(baseCRS), conv,
6065
0
                                 NN_NO_CHECK(csCast));
6066
0
    }
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedGeographicCRS> > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedGeographicCRS, osgeo::proj::crs::GeodeticCRS, osgeo::proj::cs::EllipsoidalCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedProjectedCRS> > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedProjectedCRS, osgeo::proj::crs::ProjectedCRS, osgeo::proj::cs::CoordinateSystem>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedVerticalCRS> > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedVerticalCRS, osgeo::proj::crs::VerticalCRS, osgeo::proj::cs::VerticalCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedEngineeringCRSTraits> > > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedEngineeringCRSTraits>, osgeo::proj::crs::EngineeringCRS, osgeo::proj::cs::CoordinateSystem>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedParametricCRSTraits> > > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedParametricCRSTraits>, osgeo::proj::crs::ParametricCRS, osgeo::proj::cs::ParametricCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
Unexecuted instantiation: dropbox::oxygen::nn<std::__1::shared_ptr<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedTemporalCRSTraits> > > osgeo::proj::io::JSONParser::buildDerivedCRS<osgeo::proj::crs::DerivedCRSTemplate<osgeo::proj::crs::DerivedTemporalCRSTraits>, osgeo::proj::crs::TemporalCRS, osgeo::proj::cs::TemporalCS>(proj_nlohmann::basic_json<std::__1::map, std::__1::vector, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >, bool, long, unsigned long, double, std::__1::allocator, proj_nlohmann::adl_serializer, std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > > const&)
6067
6068
0
    void emitRecoverableWarning(const std::string &warningMsg) {
6069
0
        if (ctx_) {
6070
0
            proj_context_log_debug(ctx_, "PROJJSON parsing: %s",
6071
0
                                   warningMsg.c_str());
6072
0
        }
6073
0
    }
6074
6075
    JSONParser(const JSONParser &) = delete;
6076
    JSONParser &operator=(const JSONParser &) = delete;
6077
6078
  public:
6079
82
    JSONParser() = default;
6080
6081
82
    JSONParser &attachDatabaseContext(const DatabaseContextPtr &dbContext) {
6082
82
        dbContext_ = dbContext;
6083
82
        return *this;
6084
82
    }
6085
6086
82
    JSONParser &attachContext(PJ_CONTEXT *ctx) {
6087
82
        ctx_ = ctx;
6088
82
        return *this;
6089
82
    }
6090
6091
    BaseObjectNNPtr create(const json &j);
6092
};
6093
6094
// ---------------------------------------------------------------------------
6095
6096
126
std::string JSONParser::getString(const json &j, const char *key) {
6097
126
    if (!j.contains(key)) {
6098
21
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6099
21
    }
6100
105
    auto v = j[key];
6101
105
    if (!v.is_string()) {
6102
23
        throw ParsingException(std::string("The value of \"") + key +
6103
23
                               "\" should be a string");
6104
23
    }
6105
82
    return v.get<std::string>();
6106
105
}
6107
6108
// ---------------------------------------------------------------------------
6109
6110
24
json JSONParser::getObject(const json &j, const char *key) {
6111
24
    if (!j.contains(key)) {
6112
1
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6113
1
    }
6114
23
    auto v = j[key];
6115
23
    if (!v.is_object()) {
6116
0
        throw ParsingException(std::string("The value of \"") + key +
6117
0
                               "\" should be a object");
6118
0
    }
6119
23
    return v.get<json>();
6120
23
}
6121
6122
// ---------------------------------------------------------------------------
6123
6124
0
json JSONParser::getArray(const json &j, const char *key) {
6125
0
    if (!j.contains(key)) {
6126
0
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6127
0
    }
6128
0
    auto v = j[key];
6129
0
    if (!v.is_array()) {
6130
0
        throw ParsingException(std::string("The value of \"") + key +
6131
0
                               "\" should be a array");
6132
0
    }
6133
0
    return v.get<json>();
6134
0
}
6135
6136
// ---------------------------------------------------------------------------
6137
6138
0
int JSONParser::getInteger(const json &j, const char *key) {
6139
0
    if (!j.contains(key)) {
6140
0
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6141
0
    }
6142
0
    auto v = j[key];
6143
0
    if (!v.is_number()) {
6144
0
        throw ParsingException(std::string("The value of \"") + key +
6145
0
                               "\" should be an integer");
6146
0
    }
6147
0
    const double dbl = v.get<double>();
6148
0
    if (!(dbl >= std::numeric_limits<int>::min() &&
6149
0
          dbl <= std::numeric_limits<int>::max() &&
6150
0
          static_cast<int>(dbl) == dbl)) {
6151
0
        throw ParsingException(std::string("The value of \"") + key +
6152
0
                               "\" should be an integer");
6153
0
    }
6154
0
    return static_cast<int>(dbl);
6155
0
}
6156
6157
// ---------------------------------------------------------------------------
6158
6159
0
double JSONParser::getNumber(const json &j, const char *key) {
6160
0
    if (!j.contains(key)) {
6161
0
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6162
0
    }
6163
0
    auto v = j[key];
6164
0
    if (!v.is_number()) {
6165
0
        throw ParsingException(std::string("The value of \"") + key +
6166
0
                               "\" should be a number");
6167
0
    }
6168
0
    return v.get<double>();
6169
0
}
6170
6171
// ---------------------------------------------------------------------------
6172
6173
0
UnitOfMeasure JSONParser::getUnit(const json &j, const char *key) {
6174
0
    if (!j.contains(key)) {
6175
0
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6176
0
    }
6177
0
    auto v = j[key];
6178
0
    if (v.is_string()) {
6179
0
        auto vStr = v.get<std::string>();
6180
0
        for (const auto &unit : {UnitOfMeasure::METRE, UnitOfMeasure::DEGREE,
6181
0
                                 UnitOfMeasure::SCALE_UNITY}) {
6182
0
            if (vStr == unit.name())
6183
0
                return unit;
6184
0
        }
6185
0
        throw ParsingException("Unknown unit name: " + vStr);
6186
0
    }
6187
0
    if (!v.is_object()) {
6188
0
        throw ParsingException(std::string("The value of \"") + key +
6189
0
                               "\" should be a string or an object");
6190
0
    }
6191
0
    auto typeStr = getType(v);
6192
0
    UnitOfMeasure::Type type = UnitOfMeasure::Type::UNKNOWN;
6193
0
    if (typeStr == "LinearUnit") {
6194
0
        type = UnitOfMeasure::Type::LINEAR;
6195
0
    } else if (typeStr == "AngularUnit") {
6196
0
        type = UnitOfMeasure::Type::ANGULAR;
6197
0
    } else if (typeStr == "ScaleUnit") {
6198
0
        type = UnitOfMeasure::Type::SCALE;
6199
0
    } else if (typeStr == "TimeUnit") {
6200
0
        type = UnitOfMeasure::Type::TIME;
6201
0
    } else if (typeStr == "ParametricUnit") {
6202
0
        type = UnitOfMeasure::Type::PARAMETRIC;
6203
0
    } else if (typeStr == "Unit") {
6204
0
        type = UnitOfMeasure::Type::UNKNOWN;
6205
0
    } else {
6206
0
        throw ParsingException("Unsupported value of \"type\"");
6207
0
    }
6208
0
    auto nameStr = getName(v);
6209
0
    auto convFactor = getNumber(v, "conversion_factor");
6210
0
    std::string authorityStr;
6211
0
    std::string codeStr;
6212
0
    if (v.contains("authority") && v.contains("code")) {
6213
0
        authorityStr = getString(v, "authority");
6214
0
        auto code = v["code"];
6215
0
        if (code.is_string()) {
6216
0
            codeStr = code.get<std::string>();
6217
0
        } else if (code.is_number_integer()) {
6218
0
            codeStr = internal::toString(code.get<int>());
6219
0
        } else {
6220
0
            throw ParsingException("Unexpected type for value of \"code\"");
6221
0
        }
6222
0
    }
6223
0
    return UnitOfMeasure(nameStr, convFactor, type, authorityStr, codeStr);
6224
0
}
6225
6226
// ---------------------------------------------------------------------------
6227
6228
21
std::string JSONParser::getName(const json &j) { return getString(j, "name"); }
6229
6230
// ---------------------------------------------------------------------------
6231
6232
0
std::string JSONParser::getType(const json &j) { return getString(j, "type"); }
6233
6234
// ---------------------------------------------------------------------------
6235
6236
0
Length JSONParser::getLength(const json &j, const char *key) {
6237
0
    if (!j.contains(key)) {
6238
0
        throw ParsingException(std::string("Missing \"") + key + "\" key");
6239
0
    }
6240
0
    auto v = j[key];
6241
0
    if (v.is_number()) {
6242
0
        return Length(v.get<double>(), UnitOfMeasure::METRE);
6243
0
    }
6244
0
    if (v.is_object()) {
6245
0
        return Length(getMeasure(v));
6246
0
    }
6247
0
    throw ParsingException(std::string("The value of \"") + key +
6248
0
                           "\" should be a number or an object");
6249
0
}
6250
6251
// ---------------------------------------------------------------------------
6252
6253
0
Measure JSONParser::getMeasure(const json &j) {
6254
0
    return Measure(getNumber(j, "value"), getUnit(j, "unit"));
6255
0
}
6256
6257
// ---------------------------------------------------------------------------
6258
6259
16
ObjectDomainPtr JSONParser::buildObjectDomain(const json &j) {
6260
16
    optional<std::string> scope;
6261
16
    if (j.contains("scope")) {
6262
0
        scope = getString(j, "scope");
6263
0
    }
6264
16
    std::string area;
6265
16
    if (j.contains("area")) {
6266
0
        area = getString(j, "area");
6267
0
    }
6268
16
    std::vector<GeographicExtentNNPtr> geogExtent;
6269
16
    if (j.contains("bbox")) {
6270
0
        auto bbox = getObject(j, "bbox");
6271
0
        double south = getNumber(bbox, "south_latitude");
6272
0
        double west = getNumber(bbox, "west_longitude");
6273
0
        double north = getNumber(bbox, "north_latitude");
6274
0
        double east = getNumber(bbox, "east_longitude");
6275
0
        try {
6276
0
            geogExtent.emplace_back(
6277
0
                GeographicBoundingBox::create(west, south, east, north));
6278
0
        } catch (const std::exception &e) {
6279
0
            throw ParsingException(
6280
0
                std::string("Invalid bbox node: ").append(e.what()));
6281
0
        }
6282
0
    }
6283
6284
16
    std::vector<VerticalExtentNNPtr> verticalExtent;
6285
16
    if (j.contains("vertical_extent")) {
6286
0
        const auto vertical_extent = getObject(j, "vertical_extent");
6287
0
        const auto min = getNumber(vertical_extent, "minimum");
6288
0
        const auto max = getNumber(vertical_extent, "maximum");
6289
0
        const auto unit = vertical_extent.contains("unit")
6290
0
                              ? getUnit(vertical_extent, "unit")
6291
0
                              : UnitOfMeasure::METRE;
6292
0
        verticalExtent.emplace_back(VerticalExtent::create(
6293
0
            min, max, util::nn_make_shared<UnitOfMeasure>(unit)));
6294
0
    }
6295
6296
16
    std::vector<TemporalExtentNNPtr> temporalExtent;
6297
16
    if (j.contains("temporal_extent")) {
6298
0
        const auto temporal_extent = getObject(j, "temporal_extent");
6299
0
        const auto start = getString(temporal_extent, "start");
6300
0
        const auto end = getString(temporal_extent, "end");
6301
0
        temporalExtent.emplace_back(TemporalExtent::create(start, end));
6302
0
    }
6303
6304
16
    if (scope.has_value() || !area.empty() || !geogExtent.empty() ||
6305
16
        !verticalExtent.empty() || !temporalExtent.empty()) {
6306
0
        util::optional<std::string> description;
6307
0
        if (!area.empty())
6308
0
            description = area;
6309
0
        ExtentPtr extent;
6310
0
        if (description.has_value() || !geogExtent.empty() ||
6311
0
            !verticalExtent.empty() || !temporalExtent.empty()) {
6312
0
            extent = Extent::create(description, geogExtent, verticalExtent,
6313
0
                                    temporalExtent)
6314
0
                         .as_nullable();
6315
0
        }
6316
0
        return ObjectDomain::create(scope, extent).as_nullable();
6317
0
    }
6318
16
    return nullptr;
6319
16
}
6320
6321
// ---------------------------------------------------------------------------
6322
6323
IdentifierNNPtr JSONParser::buildId(const json &parentJ, const json &j,
6324
0
                                    bool removeInverseOf) {
6325
6326
0
    PropertyMap propertiesId;
6327
0
    auto codeSpace(getString(j, "authority"));
6328
0
    if (removeInverseOf && starts_with(codeSpace, "INVERSE(") &&
6329
0
        codeSpace.back() == ')') {
6330
0
        codeSpace = codeSpace.substr(strlen("INVERSE("));
6331
0
        codeSpace.resize(codeSpace.size() - 1);
6332
0
    }
6333
6334
0
    std::string version;
6335
0
    if (j.contains("version")) {
6336
0
        auto versionJ = j["version"];
6337
0
        if (versionJ.is_string()) {
6338
0
            version = versionJ.get<std::string>();
6339
0
        } else if (versionJ.is_number()) {
6340
0
            const double dblVersion = versionJ.get<double>();
6341
0
            if (dblVersion >= std::numeric_limits<int>::min() &&
6342
0
                dblVersion <= std::numeric_limits<int>::max() &&
6343
0
                static_cast<int>(dblVersion) == dblVersion) {
6344
0
                version = internal::toString(static_cast<int>(dblVersion));
6345
0
            } else {
6346
0
                version = internal::toString(dblVersion, /*precision=*/15);
6347
0
            }
6348
0
        } else {
6349
0
            throw ParsingException("Unexpected type for value of \"version\"");
6350
0
        }
6351
0
    }
6352
6353
    // IAU + 2015 -> IAU_2015
6354
0
    if (dbContext_ && !version.empty()) {
6355
0
        std::string codeSpaceOut;
6356
0
        if (dbContext_->getVersionedAuthority(codeSpace, version,
6357
0
                                              codeSpaceOut)) {
6358
0
            codeSpace = std::move(codeSpaceOut);
6359
0
            version.clear();
6360
0
        }
6361
0
    }
6362
6363
0
    propertiesId.set(metadata::Identifier::CODESPACE_KEY, codeSpace);
6364
0
    propertiesId.set(metadata::Identifier::AUTHORITY_KEY, codeSpace);
6365
0
    if (!j.contains("code")) {
6366
0
        throw ParsingException("Missing \"code\" key");
6367
0
    }
6368
0
    std::string code;
6369
0
    auto codeJ = j["code"];
6370
0
    if (codeJ.is_string()) {
6371
0
        code = codeJ.get<std::string>();
6372
0
    } else if (codeJ.is_number_integer()) {
6373
0
        code = internal::toString(codeJ.get<int>());
6374
0
    } else {
6375
0
        throw ParsingException("Unexpected type for value of \"code\"");
6376
0
    }
6377
6378
    // Prior to PROJ 9.5, when synthetizing an ID for a CONVERSION UTM Zone
6379
    // south, we generated a wrong value. Auto-fix that
6380
0
    if (parentJ.contains("type") && getType(parentJ) == "Conversion" &&
6381
0
        codeSpace == Identifier::EPSG && parentJ.contains("name")) {
6382
0
        const auto parentNodeName(getName(parentJ));
6383
0
        if (ci_starts_with(parentNodeName, "UTM Zone ") &&
6384
0
            parentNodeName.find('S') != std::string::npos) {
6385
0
            const int nZone =
6386
0
                atoi(parentNodeName.c_str() + strlen("UTM Zone "));
6387
0
            if (nZone >= 1 && nZone <= 60) {
6388
0
                code = internal::toString(16100 + nZone);
6389
0
            }
6390
0
        }
6391
0
    }
6392
6393
0
    if (!version.empty()) {
6394
0
        propertiesId.set(Identifier::VERSION_KEY, version);
6395
0
    }
6396
6397
0
    if (j.contains("authority_citation")) {
6398
0
        propertiesId.set(Identifier::AUTHORITY_KEY,
6399
0
                         getString(j, "authority_citation"));
6400
0
    }
6401
6402
0
    if (j.contains("uri")) {
6403
0
        propertiesId.set(Identifier::URI_KEY, getString(j, "uri"));
6404
0
    }
6405
6406
0
    return Identifier::create(code, propertiesId);
6407
0
}
6408
6409
// ---------------------------------------------------------------------------
6410
6411
PropertyMap JSONParser::buildProperties(const json &j, bool removeInverseOf,
6412
21
                                        bool nameRequired) {
6413
21
    PropertyMap map;
6414
6415
21
    if (j.contains("name") || nameRequired) {
6416
21
        std::string name(getName(j));
6417
21
        if (removeInverseOf && starts_with(name, "Inverse of ")) {
6418
0
            name = name.substr(strlen("Inverse of "));
6419
0
        }
6420
21
        map.set(IdentifiedObject::NAME_KEY, name);
6421
21
    }
6422
6423
21
    if (j.contains("ids")) {
6424
0
        auto idsJ = getArray(j, "ids");
6425
0
        auto identifiers = ArrayOfBaseObject::create();
6426
0
        for (const auto &idJ : idsJ) {
6427
0
            if (!idJ.is_object()) {
6428
0
                throw ParsingException(
6429
0
                    "Unexpected type for value of \"ids\" child");
6430
0
            }
6431
0
            identifiers->add(buildId(j, idJ, removeInverseOf));
6432
0
        }
6433
0
        map.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers);
6434
21
    } else if (j.contains("id")) {
6435
0
        auto idJ = getObject(j, "id");
6436
0
        auto identifiers = ArrayOfBaseObject::create();
6437
0
        identifiers->add(buildId(j, idJ, removeInverseOf));
6438
0
        map.set(IdentifiedObject::IDENTIFIERS_KEY, identifiers);
6439
0
    }
6440
6441
21
    if (j.contains("remarks")) {
6442
0
        map.set(IdentifiedObject::REMARKS_KEY, getString(j, "remarks"));
6443
0
    }
6444
6445
21
    if (j.contains("usages")) {
6446
0
        ArrayOfBaseObjectNNPtr array = ArrayOfBaseObject::create();
6447
0
        auto usages = j["usages"];
6448
0
        if (!usages.is_array()) {
6449
0
            throw ParsingException("Unexpected type for value of \"usages\"");
6450
0
        }
6451
0
        for (const auto &usage : usages) {
6452
0
            if (!usage.is_object()) {
6453
0
                throw ParsingException(
6454
0
                    "Unexpected type for value of \"usages\" child");
6455
0
            }
6456
0
            auto objectDomain = buildObjectDomain(usage);
6457
0
            if (!objectDomain) {
6458
0
                throw ParsingException("missing children in \"usages\" child");
6459
0
            }
6460
0
            array->add(NN_NO_CHECK(objectDomain));
6461
0
        }
6462
0
        if (!array->empty()) {
6463
0
            map.set(ObjectUsage::OBJECT_DOMAIN_KEY, array);
6464
0
        }
6465
21
    } else {
6466
21
        auto objectDomain = buildObjectDomain(j);
6467
21
        if (objectDomain) {
6468
0
            map.set(ObjectUsage::OBJECT_DOMAIN_KEY, NN_NO_CHECK(objectDomain));
6469
0
        }
6470
21
    }
6471
6472
21
    return map;
6473
21
}
6474
6475
// ---------------------------------------------------------------------------
6476
6477
BaseObjectNNPtr JSONParser::create(const json &j)
6478
6479
105
{
6480
105
    if (!j.is_object()) {
6481
0
        throw ParsingException("JSON object expected");
6482
0
    }
6483
105
    auto type = getString(j, "type");
6484
105
    if (type == "GeographicCRS") {
6485
24
        return buildGeographicCRS(j);
6486
24
    }
6487
81
    if (type == "GeodeticCRS") {
6488
0
        return buildGeodeticCRS(j);
6489
0
    }
6490
81
    if (type == "ProjectedCRS") {
6491
0
        return buildProjectedCRS(j);
6492
0
    }
6493
81
    if (type == "VerticalCRS") {
6494
0
        return buildVerticalCRS(j);
6495
0
    }
6496
81
    if (type == "CompoundCRS") {
6497
0
        return buildCompoundCRS(j);
6498
0
    }
6499
81
    if (type == "BoundCRS") {
6500
0
        return buildBoundCRS(j);
6501
0
    }
6502
81
    if (type == "EngineeringCRS") {
6503
0
        return buildCRS<EngineeringCRS>(j, &JSONParser::buildEngineeringDatum);
6504
0
    }
6505
81
    if (type == "ParametricCRS") {
6506
0
        return buildCRS<ParametricCRS,
6507
0
                        decltype(&JSONParser::buildParametricDatum),
6508
0
                        ParametricCS>(j, &JSONParser::buildParametricDatum);
6509
0
    }
6510
81
    if (type == "TemporalCRS") {
6511
0
        return buildCRS<TemporalCRS, decltype(&JSONParser::buildTemporalDatum),
6512
0
                        TemporalCS>(j, &JSONParser::buildTemporalDatum);
6513
0
    }
6514
81
    if (type == "DerivedGeodeticCRS") {
6515
0
        auto baseCRSObj = create(getObject(j, "base_crs"));
6516
0
        auto baseCRS = util::nn_dynamic_pointer_cast<GeodeticCRS>(baseCRSObj);
6517
0
        if (!baseCRS) {
6518
0
            throw ParsingException("base_crs not of expected type");
6519
0
        }
6520
0
        auto cs = buildCS(getObject(j, "coordinate_system"));
6521
0
        auto conv = buildConversion(getObject(j, "conversion"));
6522
0
        auto csCartesian = util::nn_dynamic_pointer_cast<CartesianCS>(cs);
6523
0
        if (csCartesian)
6524
0
            return DerivedGeodeticCRS::create(buildProperties(j),
6525
0
                                              NN_NO_CHECK(baseCRS), conv,
6526
0
                                              NN_NO_CHECK(csCartesian));
6527
0
        auto csSpherical = util::nn_dynamic_pointer_cast<SphericalCS>(cs);
6528
0
        if (csSpherical)
6529
0
            return DerivedGeodeticCRS::create(buildProperties(j),
6530
0
                                              NN_NO_CHECK(baseCRS), conv,
6531
0
                                              NN_NO_CHECK(csSpherical));
6532
0
        throw ParsingException("coordinate_system not of expected type");
6533
0
    }
6534
81
    if (type == "DerivedGeographicCRS") {
6535
0
        return buildDerivedCRS<DerivedGeographicCRS, GeodeticCRS,
6536
0
                               EllipsoidalCS>(j);
6537
0
    }
6538
81
    if (type == "DerivedProjectedCRS") {
6539
0
        return buildDerivedCRS<DerivedProjectedCRS, ProjectedCRS>(j);
6540
0
    }
6541
81
    if (type == "DerivedVerticalCRS") {
6542
0
        return buildDerivedCRS<DerivedVerticalCRS, VerticalCRS, VerticalCS>(j);
6543
0
    }
6544
81
    if (type == "DerivedEngineeringCRS") {
6545
0
        return buildDerivedCRS<DerivedEngineeringCRS, EngineeringCRS>(j);
6546
0
    }
6547
81
    if (type == "DerivedParametricCRS") {
6548
0
        return buildDerivedCRS<DerivedParametricCRS, ParametricCRS,
6549
0
                               ParametricCS>(j);
6550
0
    }
6551
81
    if (type == "DerivedTemporalCRS") {
6552
0
        return buildDerivedCRS<DerivedTemporalCRS, TemporalCRS, TemporalCS>(j);
6553
0
    }
6554
81
    if (type == "DatumEnsemble") {
6555
0
        return buildDatumEnsemble(j);
6556
0
    }
6557
81
    if (type == "GeodeticReferenceFrame") {
6558
0
        return buildGeodeticReferenceFrame(j);
6559
0
    }
6560
81
    if (type == "VerticalReferenceFrame") {
6561
1
        return buildVerticalReferenceFrame(j);
6562
1
    }
6563
80
    if (type == "DynamicGeodeticReferenceFrame") {
6564
0
        return buildDynamicGeodeticReferenceFrame(j);
6565
0
    }
6566
80
    if (type == "DynamicVerticalReferenceFrame") {
6567
0
        return buildDynamicVerticalReferenceFrame(j);
6568
0
    }
6569
80
    if (type == "EngineeringDatum") {
6570
20
        return buildEngineeringDatum(j);
6571
20
    }
6572
60
    if (type == "ParametricDatum") {
6573
0
        return buildParametricDatum(j);
6574
0
    }
6575
60
    if (type == "TemporalDatum") {
6576
0
        return buildTemporalDatum(j);
6577
0
    }
6578
60
    if (type == "Ellipsoid") {
6579
0
        return buildEllipsoid(j);
6580
0
    }
6581
60
    if (type == "PrimeMeridian") {
6582
0
        return buildPrimeMeridian(j);
6583
0
    }
6584
60
    if (type == "CoordinateSystem") {
6585
0
        return buildCS(j);
6586
0
    }
6587
60
    if (type == "Conversion") {
6588
0
        return buildConversion(j);
6589
0
    }
6590
60
    if (type == "Transformation") {
6591
0
        return buildTransformation(j);
6592
0
    }
6593
60
    if (type == "PointMotionOperation") {
6594
0
        return buildPointMotionOperation(j);
6595
0
    }
6596
60
    if (type == "ConcatenatedOperation") {
6597
0
        return buildConcatenatedOperation(j);
6598
0
    }
6599
60
    if (type == "CoordinateMetadata") {
6600
0
        return buildCoordinateMetadata(j);
6601
0
    }
6602
60
    if (type == "Axis") {
6603
0
        return buildAxis(j);
6604
0
    }
6605
60
    throw ParsingException("Unsupported value of \"type\"");
6606
60
}
6607
6608
// ---------------------------------------------------------------------------
6609
6610
void JSONParser::buildGeodeticDatumOrDatumEnsemble(
6611
    const json &j, GeodeticReferenceFramePtr &datum,
6612
24
    DatumEnsemblePtr &datumEnsemble) {
6613
24
    if (j.contains("datum")) {
6614
23
        auto datumJ = getObject(j, "datum");
6615
6616
23
        if (j.contains("deformation_models")) {
6617
0
            auto deformationModelsJ = getArray(j, "deformation_models");
6618
0
            if (!deformationModelsJ.empty()) {
6619
0
                const auto &deformationModelJ = deformationModelsJ[0];
6620
0
                deformationModelName_ = getString(deformationModelJ, "name");
6621
                // We can handle only one for now
6622
0
            }
6623
0
        }
6624
6625
23
        datum = util::nn_dynamic_pointer_cast<GeodeticReferenceFrame>(
6626
23
            create(datumJ));
6627
23
        if (!datum) {
6628
0
            throw ParsingException("datum of wrong type");
6629
0
        }
6630
6631
23
        deformationModelName_.clear();
6632
23
    } else {
6633
1
        datumEnsemble =
6634
1
            buildDatumEnsemble(getObject(j, "datum_ensemble")).as_nullable();
6635
1
    }
6636
24
}
6637
6638
// ---------------------------------------------------------------------------
6639
6640
24
GeographicCRSNNPtr JSONParser::buildGeographicCRS(const json &j) {
6641
24
    GeodeticReferenceFramePtr datum;
6642
24
    DatumEnsemblePtr datumEnsemble;
6643
24
    buildGeodeticDatumOrDatumEnsemble(j, datum, datumEnsemble);
6644
24
    auto csJ = getObject(j, "coordinate_system");
6645
24
    auto ellipsoidalCS =
6646
24
        util::nn_dynamic_pointer_cast<EllipsoidalCS>(buildCS(csJ));
6647
24
    if (!ellipsoidalCS) {
6648
0
        throw ParsingException("expected an ellipsoidal CS");
6649
0
    }
6650
24
    return GeographicCRS::create(buildProperties(j), datum, datumEnsemble,
6651
24
                                 NN_NO_CHECK(ellipsoidalCS));
6652
24
}
6653
6654
// ---------------------------------------------------------------------------
6655
6656
0
GeodeticCRSNNPtr JSONParser::buildGeodeticCRS(const json &j) {
6657
0
    GeodeticReferenceFramePtr datum;
6658
0
    DatumEnsemblePtr datumEnsemble;
6659
0
    buildGeodeticDatumOrDatumEnsemble(j, datum, datumEnsemble);
6660
0
    auto csJ = getObject(j, "coordinate_system");
6661
0
    auto cs = buildCS(csJ);
6662
0
    auto props = buildProperties(j);
6663
0
    auto cartesianCS = nn_dynamic_pointer_cast<CartesianCS>(cs);
6664
0
    if (cartesianCS) {
6665
0
        if (cartesianCS->axisList().size() != 3) {
6666
0
            throw ParsingException(
6667
0
                "Cartesian CS for a GeodeticCRS should have 3 axis");
6668
0
        }
6669
0
        try {
6670
0
            return GeodeticCRS::create(props, datum, datumEnsemble,
6671
0
                                       NN_NO_CHECK(cartesianCS));
6672
0
        } catch (const util::Exception &e) {
6673
0
            throw ParsingException(std::string("buildGeodeticCRS: ") +
6674
0
                                   e.what());
6675
0
        }
6676
0
    }
6677
6678
0
    auto sphericalCS = nn_dynamic_pointer_cast<SphericalCS>(cs);
6679
0
    if (sphericalCS) {
6680
0
        try {
6681
0
            return GeodeticCRS::create(props, datum, datumEnsemble,
6682
0
                                       NN_NO_CHECK(sphericalCS));
6683
0
        } catch (const util::Exception &e) {
6684
0
            throw ParsingException(std::string("buildGeodeticCRS: ") +
6685
0
                                   e.what());
6686
0
        }
6687
0
    }
6688
0
    throw ParsingException("expected a Cartesian or spherical CS");
6689
0
}
6690
6691
// ---------------------------------------------------------------------------
6692
6693
0
ProjectedCRSNNPtr JSONParser::buildProjectedCRS(const json &j) {
6694
0
    auto jBaseCRS = getObject(j, "base_crs");
6695
0
    auto jBaseCS = getObject(jBaseCRS, "coordinate_system");
6696
0
    auto baseCS = buildCS(jBaseCS);
6697
0
    auto baseCRS = dynamic_cast<EllipsoidalCS *>(baseCS.get()) != nullptr
6698
0
                       ? util::nn_static_pointer_cast<GeodeticCRS>(
6699
0
                             buildGeographicCRS(jBaseCRS))
6700
0
                       : buildGeodeticCRS(jBaseCRS);
6701
0
    auto csJ = getObject(j, "coordinate_system");
6702
0
    auto cartesianCS = util::nn_dynamic_pointer_cast<CartesianCS>(buildCS(csJ));
6703
0
    if (!cartesianCS) {
6704
0
        throw ParsingException("expected a Cartesian CS");
6705
0
    }
6706
0
    auto conv = buildConversion(getObject(j, "conversion"));
6707
0
    return ProjectedCRS::create(buildProperties(j), baseCRS, conv,
6708
0
                                NN_NO_CHECK(cartesianCS));
6709
0
}
6710
6711
// ---------------------------------------------------------------------------
6712
6713
0
VerticalCRSNNPtr JSONParser::buildVerticalCRS(const json &j) {
6714
0
    VerticalReferenceFramePtr datum;
6715
0
    DatumEnsemblePtr datumEnsemble;
6716
0
    if (j.contains("datum")) {
6717
0
        auto datumJ = getObject(j, "datum");
6718
6719
0
        if (j.contains("deformation_models")) {
6720
0
            auto deformationModelsJ = getArray(j, "deformation_models");
6721
0
            if (!deformationModelsJ.empty()) {
6722
0
                const auto &deformationModelJ = deformationModelsJ[0];
6723
0
                deformationModelName_ = getString(deformationModelJ, "name");
6724
                // We can handle only one for now
6725
0
            }
6726
0
        }
6727
6728
0
        datum = util::nn_dynamic_pointer_cast<VerticalReferenceFrame>(
6729
0
            create(datumJ));
6730
0
        if (!datum) {
6731
0
            throw ParsingException("datum of wrong type");
6732
0
        }
6733
0
    } else {
6734
0
        datumEnsemble =
6735
0
            buildDatumEnsemble(getObject(j, "datum_ensemble")).as_nullable();
6736
0
    }
6737
0
    auto csJ = getObject(j, "coordinate_system");
6738
0
    auto verticalCS = util::nn_dynamic_pointer_cast<VerticalCS>(buildCS(csJ));
6739
0
    if (!verticalCS) {
6740
0
        throw ParsingException("expected a vertical CS");
6741
0
    }
6742
6743
0
    const auto buildGeoidModel = [this, &datum, &datumEnsemble,
6744
0
                                  &verticalCS](const json &geoidModelJ) {
6745
0
        auto propsModel = buildProperties(geoidModelJ);
6746
0
        const auto dummyCRS = VerticalCRS::create(
6747
0
            PropertyMap(), datum, datumEnsemble, NN_NO_CHECK(verticalCS));
6748
0
        CRSPtr interpolationCRS;
6749
0
        if (geoidModelJ.contains("interpolation_crs")) {
6750
0
            auto interpolationCRSJ =
6751
0
                getObject(geoidModelJ, "interpolation_crs");
6752
0
            interpolationCRS = buildCRS(interpolationCRSJ).as_nullable();
6753
0
        }
6754
0
        return Transformation::create(
6755
0
            propsModel, dummyCRS,
6756
0
            GeographicCRS::EPSG_4979, // arbitrarily chosen. Ignored,
6757
0
            interpolationCRS,
6758
0
            OperationMethod::create(PropertyMap(),
6759
0
                                    std::vector<OperationParameterNNPtr>()),
6760
0
            {}, {});
6761
0
    };
6762
6763
0
    auto props = buildProperties(j);
6764
0
    if (j.contains("geoid_model")) {
6765
0
        auto geoidModelJ = getObject(j, "geoid_model");
6766
0
        props.set("GEOID_MODEL", buildGeoidModel(geoidModelJ));
6767
0
    } else if (j.contains("geoid_models")) {
6768
0
        auto geoidModelsJ = getArray(j, "geoid_models");
6769
0
        auto geoidModels = ArrayOfBaseObject::create();
6770
0
        for (const auto &geoidModelJ : geoidModelsJ) {
6771
0
            geoidModels->add(buildGeoidModel(geoidModelJ));
6772
0
        }
6773
0
        props.set("GEOID_MODEL", geoidModels);
6774
0
    }
6775
6776
0
    return VerticalCRS::create(props, datum, datumEnsemble,
6777
0
                               NN_NO_CHECK(verticalCS));
6778
0
}
6779
6780
// ---------------------------------------------------------------------------
6781
6782
0
CRSNNPtr JSONParser::buildCRS(const json &j) {
6783
0
    auto crs = util::nn_dynamic_pointer_cast<CRS>(create(j));
6784
0
    if (crs) {
6785
0
        return NN_NO_CHECK(crs);
6786
0
    }
6787
0
    throw ParsingException("Object is not a CRS");
6788
0
}
6789
6790
// ---------------------------------------------------------------------------
6791
6792
0
CompoundCRSNNPtr JSONParser::buildCompoundCRS(const json &j) {
6793
0
    auto componentsJ = getArray(j, "components");
6794
0
    std::vector<CRSNNPtr> components;
6795
0
    for (const auto &componentJ : componentsJ) {
6796
0
        if (!componentJ.is_object()) {
6797
0
            throw ParsingException(
6798
0
                "Unexpected type for a \"components\" child");
6799
0
        }
6800
0
        components.push_back(buildCRS(componentJ));
6801
0
    }
6802
0
    return CompoundCRS::create(buildProperties(j), components);
6803
0
}
6804
6805
// ---------------------------------------------------------------------------
6806
6807
0
ConversionNNPtr JSONParser::buildConversion(const json &j) {
6808
0
    auto methodJ = getObject(j, "method");
6809
0
    auto convProps = buildProperties(j);
6810
0
    auto methodProps = buildProperties(methodJ);
6811
0
    if (!j.contains("parameters")) {
6812
0
        return Conversion::create(convProps, methodProps, {}, {});
6813
0
    }
6814
6815
0
    auto parametersJ = getArray(j, "parameters");
6816
0
    std::vector<OperationParameterNNPtr> parameters;
6817
0
    std::vector<ParameterValueNNPtr> values;
6818
0
    for (const auto &param : parametersJ) {
6819
0
        if (!param.is_object()) {
6820
0
            throw ParsingException(
6821
0
                "Unexpected type for a \"parameters\" child");
6822
0
        }
6823
0
        parameters.emplace_back(
6824
0
            OperationParameter::create(buildProperties(param)));
6825
0
        if (isIntegerParameter(parameters.back())) {
6826
0
            values.emplace_back(
6827
0
                ParameterValue::create(getInteger(param, "value")));
6828
0
        } else {
6829
0
            values.emplace_back(ParameterValue::create(getMeasure(param)));
6830
0
        }
6831
0
    }
6832
6833
0
    auto interpolationCRS = dealWithEPSGCodeForInterpolationCRSParameter(
6834
0
        dbContext_, parameters, values);
6835
6836
0
    std::string convName;
6837
0
    std::string methodName;
6838
0
    if (convProps.getStringValue(IdentifiedObject::NAME_KEY, convName) &&
6839
0
        methodProps.getStringValue(IdentifiedObject::NAME_KEY, methodName) &&
6840
0
        starts_with(convName, "Inverse of ") &&
6841
0
        starts_with(methodName, "Inverse of ")) {
6842
6843
0
        auto invConvProps = buildProperties(j, true);
6844
0
        auto invMethodProps = buildProperties(methodJ, true);
6845
0
        auto conv = NN_NO_CHECK(util::nn_dynamic_pointer_cast<Conversion>(
6846
0
            Conversion::create(invConvProps, invMethodProps, parameters, values)
6847
0
                ->inverse()));
6848
0
        if (interpolationCRS)
6849
0
            conv->setInterpolationCRS(interpolationCRS);
6850
0
        return conv;
6851
0
    }
6852
0
    auto conv = Conversion::create(convProps, methodProps, parameters, values);
6853
0
    if (interpolationCRS)
6854
0
        conv->setInterpolationCRS(interpolationCRS);
6855
0
    return conv;
6856
0
}
6857
6858
// ---------------------------------------------------------------------------
6859
6860
0
BoundCRSNNPtr JSONParser::buildBoundCRS(const json &j) {
6861
6862
0
    auto sourceCRS = buildCRS(getObject(j, "source_crs"));
6863
0
    auto targetCRS = buildCRS(getObject(j, "target_crs"));
6864
0
    auto transformationJ = getObject(j, "transformation");
6865
0
    auto methodJ = getObject(transformationJ, "method");
6866
0
    auto parametersJ = getArray(transformationJ, "parameters");
6867
0
    std::vector<OperationParameterNNPtr> parameters;
6868
0
    std::vector<ParameterValueNNPtr> values;
6869
0
    for (const auto &param : parametersJ) {
6870
0
        if (!param.is_object()) {
6871
0
            throw ParsingException(
6872
0
                "Unexpected type for a \"parameters\" child");
6873
0
        }
6874
0
        parameters.emplace_back(
6875
0
            OperationParameter::create(buildProperties(param)));
6876
0
        if (param.contains("value")) {
6877
0
            auto v = param["value"];
6878
0
            if (v.is_string()) {
6879
0
                values.emplace_back(
6880
0
                    ParameterValue::createFilename(v.get<std::string>()));
6881
0
                continue;
6882
0
            }
6883
0
        }
6884
0
        values.emplace_back(ParameterValue::create(getMeasure(param)));
6885
0
    }
6886
6887
0
    const auto transformation = [&]() {
6888
        // Unofficial extension / mostly for testing purposes.
6889
        // Allow to explicitly specify the source_crs of the transformation of
6890
        // the boundCRS if it is not the source_crs of the BoundCRS. Cf
6891
        // https://github.com/OSGeo/PROJ/issues/3428 use case
6892
0
        if (transformationJ.contains("source_crs")) {
6893
0
            auto sourceTransformationCRS =
6894
0
                buildCRS(getObject(transformationJ, "source_crs"));
6895
0
            auto interpolationCRS =
6896
0
                dealWithEPSGCodeForInterpolationCRSParameter(
6897
0
                    dbContext_, parameters, values);
6898
0
            return Transformation::create(
6899
0
                buildProperties(transformationJ), sourceTransformationCRS,
6900
0
                targetCRS, interpolationCRS, buildProperties(methodJ),
6901
0
                parameters, values, std::vector<PositionalAccuracyNNPtr>());
6902
0
        }
6903
6904
0
        return buildTransformationForBoundCRS(
6905
0
            dbContext_, buildProperties(transformationJ),
6906
0
            buildProperties(methodJ), sourceCRS, targetCRS, parameters, values);
6907
0
    }();
6908
6909
0
    return BoundCRS::create(buildProperties(j,
6910
0
                                            /* removeInverseOf= */ false,
6911
0
                                            /* nameRequired=*/false),
6912
0
                            sourceCRS, targetCRS, transformation);
6913
0
}
6914
6915
// ---------------------------------------------------------------------------
6916
6917
0
TransformationNNPtr JSONParser::buildTransformation(const json &j) {
6918
6919
0
    auto sourceCRS = buildCRS(getObject(j, "source_crs"));
6920
0
    auto targetCRS = buildCRS(getObject(j, "target_crs"));
6921
0
    auto methodJ = getObject(j, "method");
6922
0
    auto parametersJ = getArray(j, "parameters");
6923
0
    std::vector<OperationParameterNNPtr> parameters;
6924
0
    std::vector<ParameterValueNNPtr> values;
6925
0
    for (const auto &param : parametersJ) {
6926
0
        if (!param.is_object()) {
6927
0
            throw ParsingException(
6928
0
                "Unexpected type for a \"parameters\" child");
6929
0
        }
6930
0
        parameters.emplace_back(
6931
0
            OperationParameter::create(buildProperties(param)));
6932
0
        if (param.contains("value")) {
6933
0
            auto v = param["value"];
6934
0
            if (v.is_string()) {
6935
0
                values.emplace_back(
6936
0
                    ParameterValue::createFilename(v.get<std::string>()));
6937
0
                continue;
6938
0
            }
6939
0
        }
6940
0
        values.emplace_back(ParameterValue::create(getMeasure(param)));
6941
0
    }
6942
0
    CRSPtr interpolationCRS;
6943
0
    if (j.contains("interpolation_crs")) {
6944
0
        interpolationCRS =
6945
0
            buildCRS(getObject(j, "interpolation_crs")).as_nullable();
6946
0
    }
6947
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
6948
0
    if (j.contains("accuracy")) {
6949
0
        accuracies.push_back(
6950
0
            PositionalAccuracy::create(getString(j, "accuracy")));
6951
0
    }
6952
6953
0
    return Transformation::create(buildProperties(j), sourceCRS, targetCRS,
6954
0
                                  interpolationCRS, buildProperties(methodJ),
6955
0
                                  parameters, values, accuracies);
6956
0
}
6957
6958
// ---------------------------------------------------------------------------
6959
6960
0
PointMotionOperationNNPtr JSONParser::buildPointMotionOperation(const json &j) {
6961
6962
0
    auto sourceCRS = buildCRS(getObject(j, "source_crs"));
6963
0
    auto methodJ = getObject(j, "method");
6964
0
    auto parametersJ = getArray(j, "parameters");
6965
0
    std::vector<OperationParameterNNPtr> parameters;
6966
0
    std::vector<ParameterValueNNPtr> values;
6967
0
    for (const auto &param : parametersJ) {
6968
0
        if (!param.is_object()) {
6969
0
            throw ParsingException(
6970
0
                "Unexpected type for a \"parameters\" child");
6971
0
        }
6972
0
        parameters.emplace_back(
6973
0
            OperationParameter::create(buildProperties(param)));
6974
0
        if (param.contains("value")) {
6975
0
            auto v = param["value"];
6976
0
            if (v.is_string()) {
6977
0
                values.emplace_back(
6978
0
                    ParameterValue::createFilename(v.get<std::string>()));
6979
0
                continue;
6980
0
            }
6981
0
        }
6982
0
        values.emplace_back(ParameterValue::create(getMeasure(param)));
6983
0
    }
6984
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
6985
0
    if (j.contains("accuracy")) {
6986
0
        accuracies.push_back(
6987
0
            PositionalAccuracy::create(getString(j, "accuracy")));
6988
0
    }
6989
6990
0
    return PointMotionOperation::create(buildProperties(j), sourceCRS,
6991
0
                                        buildProperties(methodJ), parameters,
6992
0
                                        values, accuracies);
6993
0
}
6994
6995
// ---------------------------------------------------------------------------
6996
6997
ConcatenatedOperationNNPtr
6998
0
JSONParser::buildConcatenatedOperation(const json &j) {
6999
7000
0
    auto sourceCRS = buildCRS(getObject(j, "source_crs"));
7001
0
    auto targetCRS = buildCRS(getObject(j, "target_crs"));
7002
0
    auto stepsJ = getArray(j, "steps");
7003
0
    std::vector<CoordinateOperationNNPtr> operations;
7004
0
    for (const auto &stepJ : stepsJ) {
7005
0
        if (!stepJ.is_object()) {
7006
0
            throw ParsingException("Unexpected type for a \"steps\" child");
7007
0
        }
7008
0
        auto op = nn_dynamic_pointer_cast<CoordinateOperation>(create(stepJ));
7009
0
        if (!op) {
7010
0
            throw ParsingException("Invalid content in a \"steps\" child");
7011
0
        }
7012
0
        operations.emplace_back(NN_NO_CHECK(op));
7013
0
    }
7014
7015
0
    ConcatenatedOperation::fixSteps(sourceCRS, targetCRS, operations,
7016
0
                                    dbContext_,
7017
0
                                    /* fixDirectionAllowed = */ true);
7018
7019
0
    std::vector<PositionalAccuracyNNPtr> accuracies;
7020
0
    if (j.contains("accuracy")) {
7021
0
        accuracies.push_back(
7022
0
            PositionalAccuracy::create(getString(j, "accuracy")));
7023
0
    }
7024
7025
0
    try {
7026
0
        return ConcatenatedOperation::create(buildProperties(j), operations,
7027
0
                                             accuracies);
7028
0
    } catch (const InvalidOperation &e) {
7029
0
        throw ParsingException(
7030
0
            std::string("Cannot build concatenated operation: ") + e.what());
7031
0
    }
7032
0
}
7033
7034
// ---------------------------------------------------------------------------
7035
7036
0
CoordinateMetadataNNPtr JSONParser::buildCoordinateMetadata(const json &j) {
7037
7038
0
    auto crs = buildCRS(getObject(j, "crs"));
7039
0
    if (j.contains("coordinateEpoch")) {
7040
0
        auto jCoordinateEpoch = j["coordinateEpoch"];
7041
0
        if (jCoordinateEpoch.is_number()) {
7042
0
            return CoordinateMetadata::create(
7043
0
                crs, jCoordinateEpoch.get<double>(), dbContext_);
7044
0
        }
7045
0
        throw ParsingException(
7046
0
            "Unexpected type for value of \"coordinateEpoch\"");
7047
0
    }
7048
0
    return CoordinateMetadata::create(crs);
7049
0
}
7050
7051
// ---------------------------------------------------------------------------
7052
7053
0
MeridianNNPtr JSONParser::buildMeridian(const json &j) {
7054
0
    if (!j.contains("longitude")) {
7055
0
        throw ParsingException("Missing \"longitude\" key");
7056
0
    }
7057
0
    auto longitude = j["longitude"];
7058
0
    if (longitude.is_number()) {
7059
0
        return Meridian::create(
7060
0
            Angle(longitude.get<double>(), UnitOfMeasure::DEGREE));
7061
0
    } else if (longitude.is_object()) {
7062
0
        return Meridian::create(Angle(getMeasure(longitude)));
7063
0
    }
7064
0
    throw ParsingException("Unexpected type for value of \"longitude\"");
7065
0
}
7066
7067
// ---------------------------------------------------------------------------
7068
7069
0
CoordinateSystemAxisNNPtr JSONParser::buildAxis(const json &j) {
7070
0
    auto dirString = getString(j, "direction");
7071
0
    auto abbreviation = getString(j, "abbreviation");
7072
0
    const UnitOfMeasure unit(
7073
0
        j.contains("unit")
7074
0
            ? getUnit(j, "unit")
7075
0
            : UnitOfMeasure(std::string(), 1.0, UnitOfMeasure::Type::NONE));
7076
0
    auto direction = AxisDirection::valueOf(dirString);
7077
0
    if (!direction) {
7078
0
        throw ParsingException(concat("unhandled axis direction: ", dirString));
7079
0
    }
7080
0
    auto meridian = j.contains("meridian")
7081
0
                        ? buildMeridian(getObject(j, "meridian")).as_nullable()
7082
0
                        : nullptr;
7083
7084
0
    util::optional<double> minVal;
7085
0
    if (j.contains("minimum_value")) {
7086
0
        minVal = getNumber(j, "minimum_value");
7087
0
    }
7088
7089
0
    util::optional<double> maxVal;
7090
0
    if (j.contains("maximum_value")) {
7091
0
        maxVal = getNumber(j, "maximum_value");
7092
0
    }
7093
7094
0
    util::optional<RangeMeaning> rangeMeaning;
7095
0
    if (j.contains("range_meaning")) {
7096
0
        const auto val = getString(j, "range_meaning");
7097
0
        const RangeMeaning *meaning = RangeMeaning::valueOf(val);
7098
0
        if (meaning == nullptr) {
7099
0
            throw ParsingException(
7100
0
                concat("buildAxis: invalid range_meaning value: ", val));
7101
0
        }
7102
0
        rangeMeaning = util::optional<RangeMeaning>(*meaning);
7103
0
    }
7104
7105
0
    return CoordinateSystemAxis::create(buildProperties(j), abbreviation,
7106
0
                                        *direction, unit, minVal, maxVal,
7107
0
                                        rangeMeaning, meridian);
7108
0
}
7109
7110
// ---------------------------------------------------------------------------
7111
7112
0
CoordinateSystemNNPtr JSONParser::buildCS(const json &j) {
7113
0
    auto subtype = getString(j, "subtype");
7114
0
    if (!j.contains("axis")) {
7115
0
        throw ParsingException("Missing \"axis\" key");
7116
0
    }
7117
0
    auto jAxisList = j["axis"];
7118
0
    if (!jAxisList.is_array()) {
7119
0
        throw ParsingException("Unexpected type for value of \"axis\"");
7120
0
    }
7121
0
    std::vector<CoordinateSystemAxisNNPtr> axisList;
7122
0
    for (const auto &axis : jAxisList) {
7123
0
        if (!axis.is_object()) {
7124
0
            throw ParsingException(
7125
0
                "Unexpected type for value of a \"axis\" member");
7126
0
        }
7127
0
        axisList.emplace_back(buildAxis(axis));
7128
0
    }
7129
0
    const PropertyMap &csMap = emptyPropertyMap;
7130
0
    const auto axisCount = axisList.size();
7131
0
    if (subtype == EllipsoidalCS::WKT2_TYPE) {
7132
0
        if (axisCount == 2) {
7133
0
            return EllipsoidalCS::create(csMap, axisList[0], axisList[1]);
7134
0
        }
7135
0
        if (axisCount == 3) {
7136
0
            return EllipsoidalCS::create(csMap, axisList[0], axisList[1],
7137
0
                                         axisList[2]);
7138
0
        }
7139
0
        throw ParsingException("Expected 2 or 3 axis");
7140
0
    }
7141
0
    if (subtype == CartesianCS::WKT2_TYPE) {
7142
0
        if (axisCount == 2) {
7143
0
            if (axisList[0]->unit() != axisList[1]->unit()) {
7144
0
                emitRecoverableWarning(
7145
0
                    "All axis of a CartesianCS must have the same unit");
7146
0
            }
7147
0
            return CartesianCS::create(csMap, axisList[0], axisList[1],
7148
0
                                       /* enforceSameUnit = */ false);
7149
0
        }
7150
0
        if (axisCount == 3) {
7151
0
            if (axisList[0]->unit() != axisList[1]->unit() ||
7152
0
                axisList[0]->unit() != axisList[2]->unit()) {
7153
0
                emitRecoverableWarning(
7154
0
                    "All axis of a CartesianCS must have the same unit");
7155
0
            }
7156
0
            return CartesianCS::create(csMap, axisList[0], axisList[1],
7157
0
                                       axisList[2],
7158
0
                                       /* enforceSameUnit = */ false);
7159
0
        }
7160
0
        throw ParsingException("Expected 2 or 3 axis");
7161
0
    }
7162
0
    if (subtype == AffineCS::WKT2_TYPE) {
7163
0
        if (axisCount == 2) {
7164
0
            return AffineCS::create(csMap, axisList[0], axisList[1]);
7165
0
        }
7166
0
        if (axisCount == 3) {
7167
0
            return AffineCS::create(csMap, axisList[0], axisList[1],
7168
0
                                    axisList[2]);
7169
0
        }
7170
0
        throw ParsingException("Expected 2 or 3 axis");
7171
0
    }
7172
0
    if (subtype == VerticalCS::WKT2_TYPE) {
7173
0
        if (axisCount == 1) {
7174
0
            return VerticalCS::create(csMap, axisList[0]);
7175
0
        }
7176
0
        throw ParsingException("Expected 1 axis");
7177
0
    }
7178
0
    if (subtype == SphericalCS::WKT2_TYPE) {
7179
0
        if (axisCount == 2) {
7180
            // Extension to ISO19111 to support (planet)-ocentric CS with
7181
            // geocentric latitude
7182
0
            return SphericalCS::create(csMap, axisList[0], axisList[1]);
7183
0
        } else if (axisCount == 3) {
7184
0
            return SphericalCS::create(csMap, axisList[0], axisList[1],
7185
0
                                       axisList[2]);
7186
0
        }
7187
0
        throw ParsingException("Expected 2 or 3 axis");
7188
0
    }
7189
0
    if (subtype == OrdinalCS::WKT2_TYPE) {
7190
0
        return OrdinalCS::create(csMap, axisList);
7191
0
    }
7192
0
    if (subtype == ParametricCS::WKT2_TYPE) {
7193
0
        if (axisCount == 1) {
7194
0
            return ParametricCS::create(csMap, axisList[0]);
7195
0
        }
7196
0
        throw ParsingException("Expected 1 axis");
7197
0
    }
7198
0
    if (subtype == DateTimeTemporalCS::WKT2_2019_TYPE) {
7199
0
        if (axisCount == 1) {
7200
0
            return DateTimeTemporalCS::create(csMap, axisList[0]);
7201
0
        }
7202
0
        throw ParsingException("Expected 1 axis");
7203
0
    }
7204
0
    if (subtype == TemporalCountCS::WKT2_2019_TYPE) {
7205
0
        if (axisCount == 1) {
7206
0
            return TemporalCountCS::create(csMap, axisList[0]);
7207
0
        }
7208
0
        throw ParsingException("Expected 1 axis");
7209
0
    }
7210
0
    if (subtype == TemporalMeasureCS::WKT2_2019_TYPE) {
7211
0
        if (axisCount == 1) {
7212
0
            return TemporalMeasureCS::create(csMap, axisList[0]);
7213
0
        }
7214
0
        throw ParsingException("Expected 1 axis");
7215
0
    }
7216
0
    throw ParsingException("Unhandled value for subtype");
7217
0
}
7218
7219
// ---------------------------------------------------------------------------
7220
7221
0
DatumEnsembleNNPtr JSONParser::buildDatumEnsemble(const json &j) {
7222
0
    std::vector<DatumNNPtr> datums;
7223
0
    if (j.contains("members")) {
7224
0
        auto membersJ = getArray(j, "members");
7225
0
        const bool hasEllipsoid(j.contains("ellipsoid"));
7226
0
        for (const auto &memberJ : membersJ) {
7227
0
            if (!memberJ.is_object()) {
7228
0
                throw ParsingException(
7229
0
                    "Unexpected type for value of a \"members\" member");
7230
0
            }
7231
0
            auto datumName(getName(memberJ));
7232
0
            bool datumAdded = false;
7233
0
            if (dbContext_ && memberJ.contains("id")) {
7234
0
                auto id = getObject(memberJ, "id");
7235
0
                auto authority = getString(id, "authority");
7236
0
                auto authFactory = AuthorityFactory::create(
7237
0
                    NN_NO_CHECK(dbContext_), authority);
7238
0
                auto code = id["code"];
7239
0
                std::string codeStr;
7240
0
                if (code.is_string()) {
7241
0
                    codeStr = code.get<std::string>();
7242
0
                } else if (code.is_number_integer()) {
7243
0
                    codeStr = internal::toString(code.get<int>());
7244
0
                } else {
7245
0
                    throw ParsingException(
7246
0
                        "Unexpected type for value of \"code\"");
7247
0
                }
7248
0
                try {
7249
0
                    datums.push_back(authFactory->createDatum(codeStr));
7250
0
                    datumAdded = true;
7251
0
                } catch (const std::exception &) {
7252
                    // Silently ignore, as this isn't necessary an error.
7253
                    // If an older PROJ version parses a DatumEnsemble object of
7254
                    // a more recent PROJ version where the datum ensemble got
7255
                    // a new member, it might be unknown from the older PROJ.
7256
0
                }
7257
0
            }
7258
7259
0
            if (dbContext_ && !datumAdded) {
7260
0
                auto authFactory = AuthorityFactory::create(
7261
0
                    NN_NO_CHECK(dbContext_), std::string());
7262
0
                auto list = authFactory->createObjectsFromName(
7263
0
                    datumName, {AuthorityFactory::ObjectType::DATUM},
7264
0
                    false /* approximate=false*/);
7265
0
                if (!list.empty()) {
7266
0
                    auto datum =
7267
0
                        util::nn_dynamic_pointer_cast<Datum>(list.front());
7268
0
                    if (!datum)
7269
0
                        throw ParsingException(
7270
0
                            "DatumEnsemble member is not a datum");
7271
0
                    datums.push_back(NN_NO_CHECK(datum));
7272
0
                    datumAdded = true;
7273
0
                }
7274
0
            }
7275
7276
0
            if (!datumAdded) {
7277
                // Fallback if no db match
7278
0
                if (hasEllipsoid) {
7279
0
                    datums.emplace_back(GeodeticReferenceFrame::create(
7280
0
                        buildProperties(memberJ),
7281
0
                        buildEllipsoid(getObject(j, "ellipsoid")),
7282
0
                        optional<std::string>(), PrimeMeridian::GREENWICH));
7283
0
                } else {
7284
0
                    datums.emplace_back(VerticalReferenceFrame::create(
7285
0
                        buildProperties(memberJ)));
7286
0
                }
7287
0
            }
7288
0
        }
7289
0
    } else {
7290
0
        auto name = getString(j, "name");
7291
0
        if (dbContext_) {
7292
0
            auto authFactory = AuthorityFactory::create(NN_NO_CHECK(dbContext_),
7293
0
                                                        std::string());
7294
0
            auto res = authFactory->createObjectsFromName(
7295
0
                name, {AuthorityFactory::ObjectType::DATUM_ENSEMBLE}, true, 1);
7296
0
            if (res.size() == 1) {
7297
0
                auto datumEnsemble =
7298
0
                    dynamic_cast<const DatumEnsemble *>(res.front().get());
7299
0
                if (datumEnsemble) {
7300
0
                    datums = datumEnsemble->datums();
7301
0
                }
7302
0
            } else {
7303
0
                throw ParsingException(
7304
0
                    "No entry for datum ensemble '" + name +
7305
0
                    "' in database, and no explicit member specified");
7306
0
            }
7307
0
        } else {
7308
0
            throw ParsingException("Datum ensemble '" + name +
7309
0
                                   "' has no explicit member specified and no "
7310
0
                                   "connection to database");
7311
0
        }
7312
0
    }
7313
7314
0
    return DatumEnsemble::create(
7315
0
        buildProperties(j), datums,
7316
0
        PositionalAccuracy::create(getString(j, "accuracy")));
7317
0
}
7318
7319
// ---------------------------------------------------------------------------
7320
7321
GeodeticReferenceFrameNNPtr
7322
0
JSONParser::buildGeodeticReferenceFrame(const json &j) {
7323
0
    auto ellipsoidJ = getObject(j, "ellipsoid");
7324
0
    auto pm = j.contains("prime_meridian")
7325
0
                  ? buildPrimeMeridian(getObject(j, "prime_meridian"))
7326
0
                  : PrimeMeridian::GREENWICH;
7327
0
    return GeodeticReferenceFrame::create(buildProperties(j),
7328
0
                                          buildEllipsoid(ellipsoidJ),
7329
0
                                          getAnchor(j), getAnchorEpoch(j), pm);
7330
0
}
7331
7332
// ---------------------------------------------------------------------------
7333
7334
DynamicGeodeticReferenceFrameNNPtr
7335
0
JSONParser::buildDynamicGeodeticReferenceFrame(const json &j) {
7336
0
    auto ellipsoidJ = getObject(j, "ellipsoid");
7337
0
    auto pm = j.contains("prime_meridian")
7338
0
                  ? buildPrimeMeridian(getObject(j, "prime_meridian"))
7339
0
                  : PrimeMeridian::GREENWICH;
7340
0
    Measure frameReferenceEpoch(getNumber(j, "frame_reference_epoch"),
7341
0
                                UnitOfMeasure::YEAR);
7342
0
    optional<std::string> deformationModel;
7343
0
    if (j.contains("deformation_model")) {
7344
        // Before PROJJSON v0.5 / PROJ 9.1
7345
0
        deformationModel = getString(j, "deformation_model");
7346
0
    } else if (!deformationModelName_.empty()) {
7347
0
        deformationModel = deformationModelName_;
7348
0
    }
7349
0
    return DynamicGeodeticReferenceFrame::create(
7350
0
        buildProperties(j), buildEllipsoid(ellipsoidJ), getAnchor(j), pm,
7351
0
        frameReferenceEpoch, deformationModel);
7352
0
}
7353
7354
// ---------------------------------------------------------------------------
7355
7356
VerticalReferenceFrameNNPtr
7357
1
JSONParser::buildVerticalReferenceFrame(const json &j) {
7358
1
    return VerticalReferenceFrame::create(buildProperties(j), getAnchor(j),
7359
1
                                          getAnchorEpoch(j));
7360
1
}
7361
7362
// ---------------------------------------------------------------------------
7363
7364
DynamicVerticalReferenceFrameNNPtr
7365
0
JSONParser::buildDynamicVerticalReferenceFrame(const json &j) {
7366
0
    Measure frameReferenceEpoch(getNumber(j, "frame_reference_epoch"),
7367
0
                                UnitOfMeasure::YEAR);
7368
0
    optional<std::string> deformationModel;
7369
0
    if (j.contains("deformation_model")) {
7370
        // Before PROJJSON v0.5 / PROJ 9.1
7371
0
        deformationModel = getString(j, "deformation_model");
7372
0
    } else if (!deformationModelName_.empty()) {
7373
0
        deformationModel = deformationModelName_;
7374
0
    }
7375
0
    return DynamicVerticalReferenceFrame::create(
7376
0
        buildProperties(j), getAnchor(j), util::optional<RealizationMethod>(),
7377
0
        frameReferenceEpoch, deformationModel);
7378
0
}
7379
7380
// ---------------------------------------------------------------------------
7381
7382
0
PrimeMeridianNNPtr JSONParser::buildPrimeMeridian(const json &j) {
7383
0
    if (!j.contains("longitude")) {
7384
0
        throw ParsingException("Missing \"longitude\" key");
7385
0
    }
7386
0
    auto longitude = j["longitude"];
7387
0
    if (longitude.is_number()) {
7388
0
        return PrimeMeridian::create(
7389
0
            buildProperties(j),
7390
0
            Angle(longitude.get<double>(), UnitOfMeasure::DEGREE));
7391
0
    } else if (longitude.is_object()) {
7392
0
        return PrimeMeridian::create(buildProperties(j),
7393
0
                                     Angle(getMeasure(longitude)));
7394
0
    }
7395
0
    throw ParsingException("Unexpected type for value of \"longitude\"");
7396
0
}
7397
7398
// ---------------------------------------------------------------------------
7399
7400
0
EllipsoidNNPtr JSONParser::buildEllipsoid(const json &j) {
7401
0
    if (j.contains("semi_major_axis")) {
7402
0
        auto semiMajorAxis = getLength(j, "semi_major_axis");
7403
0
        const auto ellpsProperties = buildProperties(j);
7404
0
        std::string ellpsName;
7405
0
        ellpsProperties.getStringValue(IdentifiedObject::NAME_KEY, ellpsName);
7406
0
        const auto celestialBody(Ellipsoid::guessBodyName(
7407
0
            dbContext_, semiMajorAxis.getSIValue(), ellpsName));
7408
0
        if (j.contains("semi_minor_axis")) {
7409
0
            return Ellipsoid::createTwoAxis(ellpsProperties, semiMajorAxis,
7410
0
                                            getLength(j, "semi_minor_axis"),
7411
0
                                            celestialBody);
7412
0
        } else if (j.contains("inverse_flattening")) {
7413
0
            return Ellipsoid::createFlattenedSphere(
7414
0
                ellpsProperties, semiMajorAxis,
7415
0
                Scale(getNumber(j, "inverse_flattening")), celestialBody);
7416
0
        } else {
7417
0
            throw ParsingException(
7418
0
                "Missing semi_minor_axis or inverse_flattening");
7419
0
        }
7420
0
    } else if (j.contains("radius")) {
7421
0
        auto radius = getLength(j, "radius");
7422
0
        const auto celestialBody(
7423
0
            Ellipsoid::guessBodyName(dbContext_, radius.getSIValue()));
7424
0
        return Ellipsoid::createSphere(buildProperties(j), radius,
7425
0
                                       celestialBody);
7426
0
    }
7427
0
    throw ParsingException("Missing semi_major_axis or radius");
7428
0
}
7429
7430
//! @endcond
7431
7432
// ---------------------------------------------------------------------------
7433
7434
//! @cond Doxygen_Suppress
7435
7436
// import a CRS encoded as OGC Best Practice document 11-135.
7437
7438
static const char *const crsURLPrefixes[] = {
7439
    "http://opengis.net/def/crs",     "https://opengis.net/def/crs",
7440
    "http://www.opengis.net/def/crs", "https://www.opengis.net/def/crs",
7441
    "www.opengis.net/def/crs",
7442
};
7443
7444
3.01k
static bool isCRSURL(const std::string &text) {
7445
14.9k
    for (const auto crsURLPrefix : crsURLPrefixes) {
7446
14.9k
        if (starts_with(text, crsURLPrefix)) {
7447
57
            return true;
7448
57
        }
7449
14.9k
    }
7450
2.95k
    return false;
7451
3.01k
}
7452
7453
static CRSNNPtr importFromCRSURL(const std::string &text,
7454
54
                                 const DatabaseContextNNPtr &dbContext) {
7455
    // e.g http://www.opengis.net/def/crs/EPSG/0/4326
7456
54
    std::vector<std::string> parts;
7457
185
    for (const auto crsURLPrefix : crsURLPrefixes) {
7458
185
        if (starts_with(text, crsURLPrefix)) {
7459
54
            parts = split(text.substr(strlen(crsURLPrefix)), '/');
7460
54
            break;
7461
54
        }
7462
185
    }
7463
7464
    // e.g
7465
    // "http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/def/crs/EPSG/0/4326&2=http://www.opengis.net/def/crs/EPSG/0/3855"
7466
54
    if (!parts.empty() && starts_with(parts[0], "-compound?")) {
7467
20
        parts = split(text.substr(text.find('?') + 1), '&');
7468
20
        std::map<int, std::string> mapParts;
7469
20
        for (const auto &part : parts) {
7470
20
            const auto queryParam = split(part, '=');
7471
20
            if (queryParam.size() != 2) {
7472
12
                throw ParsingException("invalid OGC CRS URL");
7473
12
            }
7474
8
            try {
7475
8
                mapParts[std::stoi(queryParam[0])] = queryParam[1];
7476
8
            } catch (const std::exception &) {
7477
8
                throw ParsingException("invalid OGC CRS URL");
7478
8
            }
7479
8
        }
7480
0
        std::vector<CRSNNPtr> components;
7481
0
        std::string name;
7482
0
        for (size_t i = 1; i <= mapParts.size(); ++i) {
7483
0
            const auto iter = mapParts.find(static_cast<int>(i));
7484
0
            if (iter == mapParts.end()) {
7485
0
                throw ParsingException("invalid OGC CRS URL");
7486
0
            }
7487
0
            components.emplace_back(importFromCRSURL(iter->second, dbContext));
7488
0
            if (!name.empty()) {
7489
0
                name += " + ";
7490
0
            }
7491
0
            name += components.back()->nameStr();
7492
0
        }
7493
0
        return CompoundCRS::create(
7494
0
            util::PropertyMap().set(IdentifiedObject::NAME_KEY, name),
7495
0
            components);
7496
0
    }
7497
7498
34
    if (parts.size() < 4) {
7499
23
        throw ParsingException("invalid OGC CRS URL");
7500
23
    }
7501
7502
11
    const auto &auth_name = parts[1];
7503
11
    const auto &code = parts[3];
7504
11
    try {
7505
11
        auto factoryCRS = AuthorityFactory::create(dbContext, auth_name);
7506
11
        return factoryCRS->createCoordinateReferenceSystem(code, true);
7507
11
    } catch (...) {
7508
11
        const auto &version = parts[2];
7509
11
        if (version.empty() || version == "0") {
7510
3
            const auto authoritiesFromAuthName =
7511
3
                dbContext->getVersionedAuthoritiesFromName(auth_name);
7512
3
            for (const auto &authNameVersioned : authoritiesFromAuthName) {
7513
0
                try {
7514
0
                    auto factoryCRS =
7515
0
                        AuthorityFactory::create(dbContext, authNameVersioned);
7516
0
                    return factoryCRS->createCoordinateReferenceSystem(code,
7517
0
                                                                       true);
7518
0
                } catch (...) {
7519
0
                }
7520
0
            }
7521
3
            throw;
7522
3
        }
7523
8
        std::string authNameWithVersion;
7524
8
        if (!dbContext->getVersionedAuthority(auth_name, version,
7525
8
                                              authNameWithVersion)) {
7526
8
            throw;
7527
8
        }
7528
0
        auto factoryCRS =
7529
0
            AuthorityFactory::create(dbContext, authNameWithVersion);
7530
0
        return factoryCRS->createCoordinateReferenceSystem(code, true);
7531
8
    }
7532
11
}
7533
7534
// ---------------------------------------------------------------------------
7535
7536
/* Import a CRS encoded as WMSAUTO string.
7537
 *
7538
 * Note that the WMS 1.3 specification does not include the
7539
 * units code, while apparently earlier specs do.  We try to
7540
 * guess around this.
7541
 *
7542
 * (code derived from GDAL's importFromWMSAUTO())
7543
 */
7544
7545
205
static CRSNNPtr importFromWMSAUTO(const std::string &text) {
7546
7547
205
    int nUnitsId = 9001;
7548
205
    double dfRefLong;
7549
205
    double dfRefLat = 0.0;
7550
7551
205
    assert(ci_starts_with(text, "AUTO:"));
7552
205
    const auto parts = split(text.substr(strlen("AUTO:")), ',');
7553
7554
205
    try {
7555
205
        constexpr int AUTO_MOLLWEIDE = 42005;
7556
205
        if (parts.size() == 4) {
7557
5
            nUnitsId = std::stoi(parts[1]);
7558
5
            dfRefLong = c_locale_stod(parts[2]);
7559
5
            dfRefLat = c_locale_stod(parts[3]);
7560
200
        } else if (parts.size() == 3 && std::stoi(parts[0]) == AUTO_MOLLWEIDE) {
7561
3
            nUnitsId = std::stoi(parts[1]);
7562
3
            dfRefLong = c_locale_stod(parts[2]);
7563
197
        } else if (parts.size() == 3) {
7564
115
            dfRefLong = c_locale_stod(parts[1]);
7565
115
            dfRefLat = c_locale_stod(parts[2]);
7566
115
        } else if (parts.size() == 2 && std::stoi(parts[0]) == AUTO_MOLLWEIDE) {
7567
35
            dfRefLong = c_locale_stod(parts[1]);
7568
47
        } else {
7569
47
            throw ParsingException("invalid WMS AUTO CRS definition");
7570
47
        }
7571
7572
158
        const auto getConversion = [dfRefLong, dfRefLat, &parts]() {
7573
86
            const int nProjId = std::stoi(parts[0]);
7574
86
            switch (nProjId) {
7575
4
            case 42001: // Auto UTM
7576
4
                if (!(dfRefLong >= -180 && dfRefLong < 180)) {
7577
0
                    throw ParsingException("invalid WMS AUTO CRS definition: "
7578
0
                                           "invalid longitude");
7579
0
                }
7580
4
                return Conversion::createUTM(
7581
4
                    util::PropertyMap(),
7582
4
                    static_cast<int>(floor((dfRefLong + 180.0) / 6.0)) + 1,
7583
4
                    dfRefLat >= 0.0);
7584
7585
10
            case 42002: // Auto TM (strangely very UTM-like).
7586
10
                return Conversion::createTransverseMercator(
7587
10
                    util::PropertyMap(), common::Angle(0),
7588
10
                    common::Angle(dfRefLong), common::Scale(0.9996),
7589
10
                    common::Length(500000),
7590
10
                    common::Length((dfRefLat >= 0.0) ? 0.0 : 10000000.0));
7591
7592
22
            case 42003: // Auto Orthographic.
7593
22
                return Conversion::createOrthographic(
7594
22
                    util::PropertyMap(), common::Angle(dfRefLat),
7595
22
                    common::Angle(dfRefLong), common::Length(0),
7596
22
                    common::Length(0));
7597
7598
16
            case 42004: // Auto Equirectangular
7599
16
                return Conversion::createEquidistantCylindrical(
7600
16
                    util::PropertyMap(), common::Angle(dfRefLat),
7601
16
                    common::Angle(dfRefLong), common::Length(0),
7602
16
                    common::Length(0));
7603
7604
18
            case 42005: // MSVC 2015 thinks that AUTO_MOLLWEIDE is not constant
7605
18
                return Conversion::createMollweide(
7606
18
                    util::PropertyMap(), common::Angle(dfRefLong),
7607
18
                    common::Length(0), common::Length(0));
7608
7609
16
            default:
7610
16
                throw ParsingException("invalid WMS AUTO CRS definition: "
7611
16
                                       "unsupported projection id");
7612
86
            }
7613
86
        };
7614
7615
158
        const auto getUnits = [nUnitsId]() -> const UnitOfMeasure & {
7616
70
            switch (nUnitsId) {
7617
69
            case 9001:
7618
69
                return UnitOfMeasure::METRE;
7619
7620
0
            case 9002:
7621
0
                return UnitOfMeasure::FOOT;
7622
7623
0
            case 9003:
7624
0
                return UnitOfMeasure::US_FOOT;
7625
7626
1
            default:
7627
1
                throw ParsingException("invalid WMS AUTO CRS definition: "
7628
1
                                       "unsupported units code");
7629
70
            }
7630
70
        };
7631
7632
158
        return crs::ProjectedCRS::create(
7633
158
            util::PropertyMap().set(IdentifiedObject::NAME_KEY, "unnamed"),
7634
158
            crs::GeographicCRS::EPSG_4326, getConversion(),
7635
158
            cs::CartesianCS::createEastingNorthing(getUnits()));
7636
7637
205
    } catch (const std::exception &) {
7638
136
        throw ParsingException("invalid WMS AUTO CRS definition");
7639
136
    }
7640
205
}
7641
7642
// ---------------------------------------------------------------------------
7643
7644
static BaseObjectNNPtr createFromURNPart(const DatabaseContextPtr &dbContext,
7645
                                         const std::string &type,
7646
                                         const std::string &authName,
7647
                                         const std::string &version,
7648
41
                                         const std::string &code) {
7649
41
    if (!dbContext) {
7650
4
        throw ParsingException("no database context specified");
7651
4
    }
7652
37
    try {
7653
37
        auto factory =
7654
37
            AuthorityFactory::create(NN_NO_CHECK(dbContext), authName);
7655
37
        if (type == "crs") {
7656
0
            return factory->createCoordinateReferenceSystem(code);
7657
0
        }
7658
37
        if (type == "coordinateOperation") {
7659
1
            return factory->createCoordinateOperation(code, true);
7660
1
        }
7661
36
        if (type == "datum") {
7662
0
            return factory->createDatum(code);
7663
0
        }
7664
36
        if (type == "ensemble") {
7665
0
            return factory->createDatumEnsemble(code);
7666
0
        }
7667
36
        if (type == "ellipsoid") {
7668
0
            return factory->createEllipsoid(code);
7669
0
        }
7670
36
        if (type == "meridian") {
7671
0
            return factory->createPrimeMeridian(code);
7672
0
        }
7673
        // Extension of OGC URN syntax to CoordinateMetadata
7674
36
        if (type == "coordinateMetadata") {
7675
0
            return factory->createCoordinateMetadata(code);
7676
0
        }
7677
36
        throw ParsingException(concat("unhandled object type: ", type));
7678
37
    } catch (...) {
7679
37
        if (version.empty()) {
7680
7
            const auto authoritiesFromAuthName =
7681
7
                dbContext->getVersionedAuthoritiesFromName(authName);
7682
7
            for (const auto &authNameVersioned : authoritiesFromAuthName) {
7683
0
                try {
7684
0
                    return createFromURNPart(dbContext, type, authNameVersioned,
7685
0
                                             std::string(), code);
7686
0
                } catch (...) {
7687
0
                }
7688
0
            }
7689
7
            throw;
7690
7
        }
7691
30
        std::string authNameWithVersion;
7692
30
        if (!dbContext->getVersionedAuthority(authName, version,
7693
30
                                              authNameWithVersion)) {
7694
30
            throw;
7695
30
        }
7696
0
        return createFromURNPart(dbContext, type, authNameWithVersion,
7697
0
                                 std::string(), code);
7698
30
    }
7699
37
}
7700
7701
// ---------------------------------------------------------------------------
7702
7703
static BaseObjectNNPtr createFromUserInput(const std::string &text,
7704
                                           const DatabaseContextPtr &dbContext,
7705
                                           bool usePROJ4InitRules,
7706
                                           PJ_CONTEXT *ctx,
7707
24.6k
                                           bool ignoreCoordinateEpoch) {
7708
24.6k
    std::size_t idxFirstCharNotSpace = text.find_first_not_of(" \t\r\n");
7709
24.6k
    if (idxFirstCharNotSpace > 0 && idxFirstCharNotSpace != std::string::npos) {
7710
397
        return createFromUserInput(text.substr(idxFirstCharNotSpace), dbContext,
7711
397
                                   usePROJ4InitRules, ctx,
7712
397
                                   ignoreCoordinateEpoch);
7713
397
    }
7714
7715
    // Parse strings like "ITRF2014 @ 2025.0"
7716
24.2k
    const auto posAt = text.find('@');
7717
24.2k
    if (!ignoreCoordinateEpoch && posAt != std::string::npos) {
7718
7719
        // Try first as if belonged to the name
7720
4.62k
        try {
7721
4.62k
            return createFromUserInput(text, dbContext, usePROJ4InitRules, ctx,
7722
4.62k
                                       /* ignoreCoordinateEpoch = */ true);
7723
4.62k
        } catch (...) {
7724
2.40k
        }
7725
7726
2.40k
        std::string leftPart = text.substr(0, posAt);
7727
2.62k
        while (!leftPart.empty() && leftPart.back() == ' ')
7728
218
            leftPart.resize(leftPart.size() - 1);
7729
2.40k
        const auto nonSpacePos = text.find_first_not_of(' ', posAt + 1);
7730
2.40k
        if (nonSpacePos != std::string::npos) {
7731
1.94k
            auto obj =
7732
1.94k
                createFromUserInput(leftPart, dbContext, usePROJ4InitRules, ctx,
7733
1.94k
                                    /* ignoreCoordinateEpoch = */ true);
7734
1.94k
            auto crs = nn_dynamic_pointer_cast<CRS>(obj);
7735
1.94k
            if (crs) {
7736
148
                double epoch;
7737
148
                try {
7738
148
                    epoch = c_locale_stod(text.substr(nonSpacePos));
7739
148
                } catch (const std::exception &) {
7740
61
                    throw ParsingException("non-numeric value after @");
7741
61
                }
7742
87
                try {
7743
87
                    return CoordinateMetadata::create(NN_NO_CHECK(crs), epoch,
7744
87
                                                      dbContext);
7745
87
                } catch (const std::exception &e) {
7746
10
                    throw ParsingException(
7747
10
                        std::string(
7748
10
                            "CoordinateMetadata::create() failed with: ") +
7749
10
                        e.what());
7750
10
                }
7751
87
            }
7752
1.94k
        }
7753
2.40k
    }
7754
7755
21.8k
    if (!text.empty() && text[0] == '{') {
7756
1.64k
        json j;
7757
1.64k
        try {
7758
14.7k
            j = json::parse(text, [](int depth, json::parse_event_t, json &) {
7759
14.7k
                if (depth >= 128)
7760
4
                    throw ParsingException("Too deep nesting in JSON content");
7761
14.7k
                return true;
7762
14.7k
            });
7763
1.64k
        } catch (const std::exception &e) {
7764
1.56k
            throw ParsingException(e.what());
7765
1.56k
        }
7766
82
        return JSONParser()
7767
82
            .attachContext(ctx)
7768
82
            .attachDatabaseContext(dbContext)
7769
82
            .create(j);
7770
1.64k
    }
7771
7772
20.1k
    if (!ci_starts_with(text, "step proj=") &&
7773
18.7k
        !ci_starts_with(text, "step +proj=")) {
7774
1.72M
        for (const auto &wktConstant : WKTConstants::constants()) {
7775
1.72M
            if (ci_starts_with(text, wktConstant)) {
7776
3.31k
                for (auto wkt = text.c_str() + wktConstant.size(); *wkt != '\0';
7777
3.30k
                     ++wkt) {
7778
3.30k
                    if (isspace(static_cast<unsigned char>(*wkt)))
7779
286
                        continue;
7780
3.02k
                    if (*wkt == '[') {
7781
2.89k
                        return WKTParser()
7782
2.89k
                            .attachDatabaseContext(dbContext)
7783
2.89k
                            .setStrict(false)
7784
2.89k
                            .createFromWKT(text);
7785
2.89k
                    }
7786
125
                    break;
7787
3.02k
                }
7788
3.03k
            }
7789
1.72M
        }
7790
18.7k
    }
7791
7792
17.3k
    const char *textWithoutPlusPrefix = text.c_str();
7793
17.3k
    if (textWithoutPlusPrefix[0] == '+')
7794
1.80k
        textWithoutPlusPrefix++;
7795
7796
17.3k
    if (strncmp(textWithoutPlusPrefix, "proj=", strlen("proj=")) == 0 ||
7797
6.70k
        text.find(" +proj=") != std::string::npos ||
7798
6.17k
        text.find(" proj=") != std::string::npos ||
7799
3.42k
        strncmp(textWithoutPlusPrefix, "init=", strlen("init=")) == 0 ||
7800
3.11k
        text.find(" +init=") != std::string::npos ||
7801
3.08k
        text.find(" init=") != std::string::npos ||
7802
12.8k
        strncmp(textWithoutPlusPrefix, "title=", strlen("title=")) == 0) {
7803
12.8k
        return PROJStringParser()
7804
12.8k
            .attachDatabaseContext(dbContext)
7805
12.8k
            .attachContext(ctx)
7806
12.8k
            .setUsePROJ4InitRules(ctx != nullptr
7807
12.8k
                                      ? (proj_context_get_use_proj4_init_rules(
7808
12.8k
                                             ctx, false) == TRUE)
7809
12.8k
                                      : usePROJ4InitRules)
7810
12.8k
            .createFromPROJString(text);
7811
12.8k
    }
7812
7813
4.46k
    if (isCRSURL(text) && dbContext) {
7814
54
        return importFromCRSURL(text, NN_NO_CHECK(dbContext));
7815
54
    }
7816
7817
4.40k
    if (ci_starts_with(text, "AUTO:")) {
7818
148
        return importFromWMSAUTO(text);
7819
148
    }
7820
7821
4.26k
    std::vector<std::string> tokens;
7822
4.26k
    if (text.find(' ') == std::string::npos)
7823
2.26k
        tokens = split(text, ':');
7824
4.26k
    if (tokens.size() == 2) {
7825
97
        if (!dbContext) {
7826
9
            throw ParsingException("no database context specified");
7827
9
        }
7828
88
        DatabaseContextNNPtr dbContextNNPtr(NN_NO_CHECK(dbContext));
7829
88
        const auto &authName = tokens[0];
7830
88
        const auto &code = tokens[1];
7831
88
        auto factory = AuthorityFactory::create(dbContextNNPtr, authName);
7832
88
        try {
7833
88
            return factory->createCoordinateReferenceSystem(code);
7834
88
        } catch (...) {
7835
7836
            // Convenience for well-known misused code
7837
            // See https://github.com/OSGeo/PROJ/issues/1730
7838
88
            if (ci_equal(authName, "EPSG") && code == "102100") {
7839
0
                factory = AuthorityFactory::create(dbContextNNPtr, "ESRI");
7840
0
                return factory->createCoordinateReferenceSystem(code);
7841
0
            }
7842
7843
88
            const auto authoritiesFromAuthName =
7844
88
                dbContextNNPtr->getVersionedAuthoritiesFromName(authName);
7845
88
            for (const auto &authNameVersioned : authoritiesFromAuthName) {
7846
2
                factory =
7847
2
                    AuthorityFactory::create(dbContextNNPtr, authNameVersioned);
7848
2
                try {
7849
2
                    return factory->createCoordinateReferenceSystem(code);
7850
2
                } catch (...) {
7851
2
                }
7852
2
            }
7853
7854
88
            const auto allAuthorities = dbContextNNPtr->getAuthorities();
7855
643
            for (const auto &authCandidate : allAuthorities) {
7856
643
                if (ci_equal(authCandidate, authName)) {
7857
23
                    factory =
7858
23
                        AuthorityFactory::create(dbContextNNPtr, authCandidate);
7859
23
                    try {
7860
23
                        return factory->createCoordinateReferenceSystem(code);
7861
23
                    } catch (...) {
7862
                        // EPSG:4326+3855
7863
23
                        auto tokensCode = split(code, '+');
7864
23
                        if (tokensCode.size() == 2) {
7865
5
                            auto crs1(factory->createCoordinateReferenceSystem(
7866
5
                                tokensCode[0], false));
7867
5
                            auto crs2(factory->createCoordinateReferenceSystem(
7868
5
                                tokensCode[1], false));
7869
5
                            return CompoundCRS::createLax(
7870
5
                                util::PropertyMap().set(
7871
5
                                    IdentifiedObject::NAME_KEY,
7872
5
                                    crs1->nameStr() + " + " + crs2->nameStr()),
7873
5
                                {crs1, crs2}, dbContext);
7874
5
                        }
7875
18
                        throw;
7876
23
                    }
7877
23
                }
7878
643
            }
7879
65
            throw;
7880
88
        }
7881
4.16k
    } else if (tokens.size() == 3) {
7882
        // ESRI:103668+EPSG:5703 ... compound
7883
18
        auto tokensCenter = split(tokens[1], '+');
7884
18
        if (tokensCenter.size() == 2) {
7885
3
            if (!dbContext) {
7886
2
                throw ParsingException("no database context specified");
7887
2
            }
7888
1
            DatabaseContextNNPtr dbContextNNPtr(NN_NO_CHECK(dbContext));
7889
7890
1
            const auto &authName1 = tokens[0];
7891
1
            const auto &code1 = tokensCenter[0];
7892
1
            const auto &authName2 = tokensCenter[1];
7893
1
            const auto &code2 = tokens[2];
7894
7895
1
            auto factory1 = AuthorityFactory::create(dbContextNNPtr, authName1);
7896
1
            auto crs1 = factory1->createCoordinateReferenceSystem(code1, false);
7897
1
            auto factory2 = AuthorityFactory::create(dbContextNNPtr, authName2);
7898
1
            auto crs2 = factory2->createCoordinateReferenceSystem(code2, false);
7899
1
            return CompoundCRS::createLax(
7900
1
                util::PropertyMap().set(IdentifiedObject::NAME_KEY,
7901
1
                                        crs1->nameStr() + " + " +
7902
1
                                            crs2->nameStr()),
7903
1
                {crs1, crs2}, dbContext);
7904
3
        }
7905
18
    }
7906
7907
4.16k
    if (starts_with(text, "urn:ogc:def:crs,")) {
7908
10
        if (!dbContext) {
7909
1
            throw ParsingException("no database context specified");
7910
1
        }
7911
9
        auto tokensComma = split(text, ',');
7912
9
        if (tokensComma.size() == 4 && starts_with(tokensComma[1], "crs:") &&
7913
0
            starts_with(tokensComma[2], "cs:") &&
7914
0
            starts_with(tokensComma[3], "coordinateOperation:")) {
7915
            // OGC 07-092r2: para 7.5.4
7916
            // URN combined references for projected or derived CRSs
7917
0
            const auto &crsPart = tokensComma[1];
7918
0
            const auto tokensCRS = split(crsPart, ':');
7919
0
            if (tokensCRS.size() != 4) {
7920
0
                throw ParsingException(
7921
0
                    concat("invalid crs component: ", crsPart));
7922
0
            }
7923
0
            auto factoryCRS =
7924
0
                AuthorityFactory::create(NN_NO_CHECK(dbContext), tokensCRS[1]);
7925
0
            auto baseCRS =
7926
0
                factoryCRS->createCoordinateReferenceSystem(tokensCRS[3], true);
7927
7928
0
            const auto &csPart = tokensComma[2];
7929
0
            auto tokensCS = split(csPart, ':');
7930
0
            if (tokensCS.size() != 4) {
7931
0
                throw ParsingException(
7932
0
                    concat("invalid cs component: ", csPart));
7933
0
            }
7934
0
            auto factoryCS =
7935
0
                AuthorityFactory::create(NN_NO_CHECK(dbContext), tokensCS[1]);
7936
0
            auto cs = factoryCS->createCoordinateSystem(tokensCS[3]);
7937
7938
0
            const auto &opPart = tokensComma[3];
7939
0
            auto tokensOp = split(opPart, ':');
7940
0
            if (tokensOp.size() != 4) {
7941
0
                throw ParsingException(
7942
0
                    concat("invalid coordinateOperation component: ", opPart));
7943
0
            }
7944
0
            auto factoryOp =
7945
0
                AuthorityFactory::create(NN_NO_CHECK(dbContext), tokensOp[1]);
7946
0
            auto op = factoryOp->createCoordinateOperation(tokensOp[3], true);
7947
7948
0
            const auto &baseName = baseCRS->nameStr();
7949
0
            std::string name(baseName);
7950
0
            auto geogCRS =
7951
0
                util::nn_dynamic_pointer_cast<GeographicCRS>(baseCRS);
7952
0
            if (geogCRS &&
7953
0
                geogCRS->coordinateSystem()->axisList().size() == 3 &&
7954
0
                baseName.find("3D") == std::string::npos) {
7955
0
                name += " (3D)";
7956
0
            }
7957
0
            name += " / ";
7958
0
            name += op->nameStr();
7959
0
            auto props =
7960
0
                util::PropertyMap().set(IdentifiedObject::NAME_KEY, name);
7961
7962
0
            if (auto conv = util::nn_dynamic_pointer_cast<Conversion>(op)) {
7963
0
                auto convNN = NN_NO_CHECK(conv);
7964
0
                if (geogCRS != nullptr) {
7965
0
                    auto geogCRSNN = NN_NO_CHECK(geogCRS);
7966
0
                    if (CartesianCSPtr ccs =
7967
0
                            util::nn_dynamic_pointer_cast<CartesianCS>(cs)) {
7968
0
                        return ProjectedCRS::create(props, geogCRSNN, convNN,
7969
0
                                                    NN_NO_CHECK(ccs));
7970
0
                    }
7971
0
                    if (EllipsoidalCSPtr ecs =
7972
0
                            util::nn_dynamic_pointer_cast<EllipsoidalCS>(cs)) {
7973
0
                        return DerivedGeographicCRS::create(
7974
0
                            props, geogCRSNN, convNN, NN_NO_CHECK(ecs));
7975
0
                    }
7976
0
                } else if (dynamic_cast<GeodeticCRS *>(baseCRS.get()) &&
7977
0
                           dynamic_cast<CartesianCS *>(cs.get())) {
7978
0
                    return DerivedGeodeticCRS::create(
7979
0
                        props,
7980
0
                        NN_NO_CHECK(util::nn_dynamic_pointer_cast<GeodeticCRS>(
7981
0
                            baseCRS)),
7982
0
                        convNN,
7983
0
                        NN_NO_CHECK(
7984
0
                            util::nn_dynamic_pointer_cast<CartesianCS>(cs)));
7985
0
                } else if (auto pcrs =
7986
0
                               util::nn_dynamic_pointer_cast<ProjectedCRS>(
7987
0
                                   baseCRS)) {
7988
0
                    return DerivedProjectedCRS::create(props, NN_NO_CHECK(pcrs),
7989
0
                                                       convNN, cs);
7990
0
                } else if (auto vertBaseCRS =
7991
0
                               util::nn_dynamic_pointer_cast<VerticalCRS>(
7992
0
                                   baseCRS)) {
7993
0
                    if (auto vertCS =
7994
0
                            util::nn_dynamic_pointer_cast<VerticalCS>(cs)) {
7995
0
                        const int methodCode = convNN->method()->getEPSGCode();
7996
0
                        std::string newName(baseName);
7997
0
                        std::string unitNameSuffix;
7998
0
                        for (const char *suffix : {" (ft)", " (ftUS)"}) {
7999
0
                            if (ends_with(newName, suffix)) {
8000
0
                                unitNameSuffix = suffix;
8001
0
                                newName.resize(newName.size() - strlen(suffix));
8002
0
                                break;
8003
0
                            }
8004
0
                        }
8005
0
                        bool newNameOk = false;
8006
0
                        if (methodCode ==
8007
0
                                EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT_NO_CONV_FACTOR ||
8008
0
                            methodCode ==
8009
0
                                EPSG_CODE_METHOD_CHANGE_VERTICAL_UNIT) {
8010
0
                            const auto &unitName =
8011
0
                                vertCS->axisList()[0]->unit().name();
8012
0
                            if (unitName == UnitOfMeasure::METRE.name()) {
8013
0
                                newNameOk = true;
8014
0
                            } else if (unitName == UnitOfMeasure::FOOT.name()) {
8015
0
                                newName += " (ft)";
8016
0
                                newNameOk = true;
8017
0
                            } else if (unitName ==
8018
0
                                       UnitOfMeasure::US_FOOT.name()) {
8019
0
                                newName += " (ftUS)";
8020
0
                                newNameOk = true;
8021
0
                            }
8022
0
                        } else if (methodCode ==
8023
0
                                   EPSG_CODE_METHOD_HEIGHT_DEPTH_REVERSAL) {
8024
0
                            if (ends_with(newName, " height")) {
8025
0
                                newName.resize(newName.size() -
8026
0
                                               strlen(" height"));
8027
0
                                newName += " depth";
8028
0
                                newName += unitNameSuffix;
8029
0
                                newNameOk = true;
8030
0
                            } else if (ends_with(newName, " depth")) {
8031
0
                                newName.resize(newName.size() -
8032
0
                                               strlen(" depth"));
8033
0
                                newName += " height";
8034
0
                                newName += unitNameSuffix;
8035
0
                                newNameOk = true;
8036
0
                            }
8037
0
                        }
8038
0
                        if (newNameOk) {
8039
0
                            props.set(IdentifiedObject::NAME_KEY, newName);
8040
0
                        }
8041
0
                        return DerivedVerticalCRS::create(
8042
0
                            props, NN_NO_CHECK(vertBaseCRS), convNN,
8043
0
                            NN_NO_CHECK(vertCS));
8044
0
                    }
8045
0
                }
8046
0
            }
8047
8048
0
            throw ParsingException("unsupported combination of baseCRS, CS "
8049
0
                                   "and coordinateOperation for a "
8050
0
                                   "DerivedCRS");
8051
0
        }
8052
8053
        // OGC 07-092r2: para 7.5.2
8054
        // URN combined references for compound coordinate reference systems
8055
9
        std::vector<CRSNNPtr> components;
8056
9
        std::string name;
8057
9
        for (size_t i = 1; i < tokensComma.size(); i++) {
8058
9
            tokens = split(tokensComma[i], ':');
8059
9
            if (tokens.size() != 4) {
8060
6
                throw ParsingException(
8061
6
                    concat("invalid crs component: ", tokensComma[i]));
8062
6
            }
8063
3
            const auto &type = tokens[0];
8064
3
            auto factory =
8065
3
                AuthorityFactory::create(NN_NO_CHECK(dbContext), tokens[1]);
8066
3
            const auto &code = tokens[3];
8067
3
            if (type == "crs") {
8068
0
                auto crs(factory->createCoordinateReferenceSystem(code, false));
8069
0
                components.emplace_back(crs);
8070
0
                if (!name.empty()) {
8071
0
                    name += " + ";
8072
0
                }
8073
0
                name += crs->nameStr();
8074
3
            } else {
8075
3
                throw ParsingException(
8076
3
                    concat("unexpected object type: ", type));
8077
3
            }
8078
3
        }
8079
0
        return CompoundCRS::create(
8080
0
            util::PropertyMap().set(IdentifiedObject::NAME_KEY, name),
8081
0
            components);
8082
9
    }
8083
8084
    // OGC 07-092r2: para 7.5.3
8085
    // 7.5.3 URN combined references for concatenated operations
8086
4.15k
    if (starts_with(text, "urn:ogc:def:coordinateOperation,")) {
8087
9
        if (!dbContext) {
8088
3
            throw ParsingException("no database context specified");
8089
3
        }
8090
6
        auto tokensComma = split(text, ',');
8091
6
        std::vector<CoordinateOperationNNPtr> components;
8092
6
        for (size_t i = 1; i < tokensComma.size(); i++) {
8093
6
            tokens = split(tokensComma[i], ':');
8094
6
            if (tokens.size() != 4) {
8095
3
                throw ParsingException(concat(
8096
3
                    "invalid coordinateOperation component: ", tokensComma[i]));
8097
3
            }
8098
3
            const auto &type = tokens[0];
8099
3
            auto factory =
8100
3
                AuthorityFactory::create(NN_NO_CHECK(dbContext), tokens[1]);
8101
3
            const auto &code = tokens[3];
8102
3
            if (type == "coordinateOperation") {
8103
0
                auto op(factory->createCoordinateOperation(code, false));
8104
0
                components.emplace_back(op);
8105
3
            } else {
8106
3
                throw ParsingException(
8107
3
                    concat("unexpected object type: ", type));
8108
3
            }
8109
3
        }
8110
0
        return ConcatenatedOperation::createComputeMetadata(components, true);
8111
6
    }
8112
8113
    // urn:ogc:def:crs:EPSG::4326
8114
4.14k
    if (tokens.size() == 7 && tolower(tokens[0]) == "urn") {
8115
8116
13
        const std::string type(tokens[3] == "CRS" ? "crs" : tokens[3]);
8117
13
        const auto &authName = tokens[4];
8118
13
        const auto &version = tokens[5];
8119
13
        const auto &code = tokens[6];
8120
13
        return createFromURNPart(dbContext, type, authName, version, code);
8121
13
    }
8122
8123
    // urn:ogc:def:crs:OGC::AUTO42001:-117:33
8124
4.12k
    if (tokens.size() > 7 && tokens[0] == "urn" && tokens[4] == "OGC" &&
8125
60
        ci_starts_with(tokens[6], "AUTO")) {
8126
57
        const auto textAUTO = text.substr(text.find(":AUTO") + 5);
8127
57
        return importFromWMSAUTO("AUTO:" + replaceAll(textAUTO, ":", ","));
8128
57
    }
8129
8130
    // Legacy urn:opengis:crs:EPSG:0:4326 (note the missing def: compared to
8131
    // above)
8132
4.07k
    if (tokens.size() == 6 && tokens[0] == "urn" && tokens[2] != "def") {
8133
21
        const auto &type = tokens[2];
8134
21
        const auto &authName = tokens[3];
8135
21
        const auto &version = tokens[4];
8136
21
        const auto &code = tokens[5];
8137
21
        return createFromURNPart(dbContext, type, authName, version, code);
8138
21
    }
8139
8140
    // Legacy urn:x-ogc:def:crs:EPSG:4326 (note the missing version)
8141
4.05k
    if (tokens.size() == 6 && tokens[0] == "urn") {
8142
7
        const auto &type = tokens[3];
8143
7
        const auto &authName = tokens[4];
8144
7
        const auto &code = tokens[5];
8145
7
        return createFromURNPart(dbContext, type, authName, std::string(),
8146
7
                                 code);
8147
7
    }
8148
8149
4.04k
    if (dbContext) {
8150
2.54k
        auto factory =
8151
2.54k
            AuthorityFactory::create(NN_NO_CHECK(dbContext), std::string());
8152
8153
2.54k
        const auto searchObject =
8154
2.54k
            [&factory](
8155
2.54k
                const std::string &objectName, bool approximateMatch,
8156
2.54k
                const std::vector<AuthorityFactory::ObjectType> &objectTypes)
8157
7.56k
            -> IdentifiedObjectPtr {
8158
7.56k
            constexpr size_t limitResultCount = 10;
8159
7.56k
            auto res = factory->createObjectsFromName(
8160
7.56k
                objectName, objectTypes, approximateMatch, limitResultCount);
8161
7.56k
            if (res.size() == 1) {
8162
126
                return res.front().as_nullable();
8163
126
            }
8164
7.43k
            if (res.size() > 1) {
8165
1.19k
                if (objectTypes.size() == 1 &&
8166
937
                    objectTypes[0] == AuthorityFactory::ObjectType::CRS) {
8167
1.19k
                    for (size_t ndim = 2; ndim <= 3; ndim++) {
8168
3.90k
                        for (const auto &obj : res) {
8169
3.90k
                            auto crs =
8170
3.90k
                                dynamic_cast<crs::GeographicCRS *>(obj.get());
8171
3.90k
                            if (crs &&
8172
1.36k
                                crs->coordinateSystem()->axisList().size() ==
8173
1.36k
                                    ndim) {
8174
818
                                return obj.as_nullable();
8175
818
                            }
8176
3.90k
                        }
8177
1.07k
                    }
8178
937
                }
8179
8180
                // If there's exactly only one object whose name is equivalent
8181
                // to the user input, return it.
8182
1.11k
                for (int pass = 0; pass <= 1; ++pass) {
8183
750
                    IdentifiedObjectPtr identifiedObj;
8184
5.76k
                    for (const auto &obj : res) {
8185
5.76k
                        if (Identifier::isEquivalentName(
8186
5.76k
                                obj->nameStr().c_str(), objectName.c_str(),
8187
5.76k
                                /* biggerDifferencesAllowed = */ pass == 1)) {
8188
7
                            if (identifiedObj == nullptr) {
8189
7
                                identifiedObj = obj.as_nullable();
8190
7
                            } else {
8191
0
                                identifiedObj = nullptr;
8192
0
                                break;
8193
0
                            }
8194
7
                        }
8195
5.76k
                    }
8196
750
                    if (identifiedObj) {
8197
7
                        return identifiedObj;
8198
7
                    }
8199
750
                }
8200
8201
369
                std::string msg("several objects matching this name: ");
8202
369
                bool first = true;
8203
2.43k
                for (const auto &obj : res) {
8204
2.43k
                    if (msg.size() > 200) {
8205
219
                        msg += ", ...";
8206
219
                        break;
8207
219
                    }
8208
2.21k
                    if (!first) {
8209
1.84k
                        msg += ", ";
8210
1.84k
                    }
8211
2.21k
                    first = false;
8212
2.21k
                    msg += obj->nameStr();
8213
2.21k
                }
8214
369
                throw ParsingException(msg);
8215
376
            }
8216
6.24k
            return nullptr;
8217
7.43k
        };
8218
8219
2.54k
        const auto searchCRS = [&searchObject](const std::string &objectName) {
8220
59
            const auto objectTypes = std::vector<AuthorityFactory::ObjectType>{
8221
59
                AuthorityFactory::ObjectType::CRS};
8222
59
            {
8223
59
                constexpr bool approximateMatch = false;
8224
59
                auto ret =
8225
59
                    searchObject(objectName, approximateMatch, objectTypes);
8226
59
                if (ret)
8227
0
                    return ret;
8228
59
            }
8229
8230
59
            constexpr bool approximateMatch = true;
8231
59
            return searchObject(objectName, approximateMatch, objectTypes);
8232
59
        };
8233
8234
        // strings like "WGS 84 + EGM96 height"
8235
2.54k
        CompoundCRSPtr compoundCRS;
8236
2.54k
        try {
8237
2.54k
            const auto tokensCompound = split(text, " + ");
8238
2.54k
            if (tokensCompound.size() == 2) {
8239
31
                auto obj1 = searchCRS(tokensCompound[0]);
8240
31
                auto obj2 = searchCRS(tokensCompound[1]);
8241
31
                auto crs1 = std::dynamic_pointer_cast<CRS>(obj1);
8242
31
                auto crs2 = std::dynamic_pointer_cast<CRS>(obj2);
8243
31
                if (crs1 && crs2) {
8244
3
                    compoundCRS =
8245
3
                        CompoundCRS::create(
8246
3
                            util::PropertyMap().set(IdentifiedObject::NAME_KEY,
8247
3
                                                    crs1->nameStr() + " + " +
8248
3
                                                        crs2->nameStr()),
8249
3
                            {NN_NO_CHECK(crs1), NN_NO_CHECK(crs2)})
8250
3
                            .as_nullable();
8251
3
                }
8252
31
            }
8253
2.54k
        } catch (const std::exception &) {
8254
7
        }
8255
8256
        // First pass: exact match on CRS objects
8257
        // Second pass: exact match on other objects
8258
        // Third pass: approximate match on CRS objects
8259
        // Fourth pass: approximate match on other objects
8260
        // But only allow approximate matching if the size of the text is
8261
        // large enough (>= 5), otherwise we get a lot of false positives:
8262
        // "foo" -> "Amersfoort", "bar" -> "Barbados 1938"
8263
        // Also only accept approximate matching if the ratio between the
8264
        // input and match size is not too small, so that "omerc" doesn't match
8265
        // with "WGS 84 / Pseudo-Mercator"
8266
2.54k
        const int maxNumberPasses = text.size() <= 4 ? 2 : 4;
8267
9.28k
        for (int pass = 0; pass < maxNumberPasses; ++pass) {
8268
7.44k
            const bool approximateMatch = (pass >= 2);
8269
7.44k
            auto ret = searchObject(
8270
7.44k
                text, approximateMatch,
8271
7.44k
                (pass == 0 || pass == 2)
8272
7.44k
                    ? std::vector<
8273
4.11k
                          AuthorityFactory::ObjectType>{AuthorityFactory::
8274
4.11k
                                                            ObjectType::CRS}
8275
7.44k
                    : std::vector<AuthorityFactory::ObjectType>{
8276
3.33k
                          AuthorityFactory::ObjectType::ELLIPSOID,
8277
3.33k
                          AuthorityFactory::ObjectType::DATUM,
8278
3.33k
                          AuthorityFactory::ObjectType::DATUM_ENSEMBLE,
8279
3.33k
                          AuthorityFactory::ObjectType::COORDINATE_OPERATION});
8280
7.44k
            if (ret) {
8281
934
                if (!approximateMatch ||
8282
899
                    ret->nameStr().size() < 2 * text.size())
8283
707
                    return NN_NO_CHECK(ret);
8284
934
            }
8285
6.73k
            if (compoundCRS) {
8286
0
                if (!approximateMatch ||
8287
0
                    compoundCRS->nameStr().size() < 2 * text.size())
8288
0
                    return NN_NO_CHECK(compoundCRS);
8289
0
            }
8290
6.73k
        }
8291
2.54k
    }
8292
8293
3.33k
    throw ParsingException("unrecognized format / unknown name");
8294
4.04k
}
8295
//! @endcond
8296
8297
// ---------------------------------------------------------------------------
8298
8299
/** \brief Instantiate a sub-class of BaseObject from a user specified text.
8300
 *
8301
 * The text can be a:
8302
 * <ul>
8303
 * <li>WKT string</li>
8304
 * <li>PROJ string</li>
8305
 * <li>database code, prefixed by its authority. e.g. "EPSG:4326"</li>
8306
 * <li>OGC URN. e.g. "urn:ogc:def:crs:EPSG::4326",
8307
 *     "urn:ogc:def:coordinateOperation:EPSG::1671",
8308
 *     "urn:ogc:def:ellipsoid:EPSG::7001"
8309
 *     or "urn:ogc:def:datum:EPSG::6326"</li>
8310
 * <li> OGC URN combining references for compound coordinate reference systems
8311
 *      e.g. "urn:ogc:def:crs,crs:EPSG::2393,crs:EPSG::5717"
8312
 *      We also accept a custom abbreviated syntax EPSG:2393+5717
8313
 *      or ESRI:103668+EPSG:5703
8314
 * </li>
8315
 * <li> OGC URN combining references for references for projected or derived
8316
 * CRSs
8317
 *      e.g. for Projected 3D CRS "UTM zone 31N / WGS 84 (3D)"
8318
 *      "urn:ogc:def:crs,crs:EPSG::4979,cs:PROJ::ENh,coordinateOperation:EPSG::16031"
8319
 * </li>
8320
 * <li>Extension of OGC URN for CoordinateMetadata.
8321
 *     e.g.
8322
 * "urn:ogc:def:coordinateMetadata:NRCAN::NAD83_CSRS_1997_MTM11_HT2_1997"</li>
8323
 * <li> OGC URN combining references for concatenated operations
8324
 *      e.g.
8325
 * "urn:ogc:def:coordinateOperation,coordinateOperation:EPSG::3895,coordinateOperation:EPSG::1618"</li>
8326
 * <li>OGC URL for a single CRS. e.g.
8327
 * "http://www.opengis.net/def/crs/EPSG/0/4326"</li>
8328
 * <li>OGC URL for a compound
8329
 * CRS. e.g
8330
 * "http://www.opengis.net/def/crs-compound?1=http://www.opengis.net/def/crs/EPSG/0/4326&2=http://www.opengis.net/def/crs/EPSG/0/3855"</li>
8331
 * <li>an Object name. e.g "WGS 84", "WGS 84 / UTM zone 31N". In that case as
8332
 *     uniqueness is not guaranteed, the function may apply heuristics to
8333
 *     determine the appropriate best match.</li>
8334
 * <li>a CRS name and a coordinate epoch, separated with '@'. For example
8335
 *     "ITRF2014@2025.0". (added in PROJ 9.2)</li>
8336
 * <li>a compound CRS made from two object names separated with " + ".
8337
 *     e.g. "WGS 84 + EGM96 height"</li>
8338
 * <li>PROJJSON string</li>
8339
 * </ul>
8340
 *
8341
 * @param text One of the above mentioned text format
8342
 * @param dbContext Database context, or nullptr (in which case database
8343
 * lookups will not work)
8344
 * @param usePROJ4InitRules When set to true,
8345
 * init=epsg:XXXX syntax will be allowed and will be interpreted according to
8346
 * PROJ.4 and PROJ.5 rules, that is geodeticCRS will have longitude, latitude
8347
 * order and will expect/output coordinates in radians. ProjectedCRS will have
8348
 * easting, northing axis order (except the ones with Transverse Mercator South
8349
 * Orientated projection). In that mode, the epsg:XXXX syntax will be also
8350
 * interpreted the same way.
8351
 * @throw ParsingException if the string cannot be parsed.
8352
 */
8353
BaseObjectNNPtr createFromUserInput(const std::string &text,
8354
                                    const DatabaseContextPtr &dbContext,
8355
314
                                    bool usePROJ4InitRules) {
8356
314
    return createFromUserInput(text, dbContext, usePROJ4InitRules, nullptr,
8357
314
                               /* ignoreCoordinateEpoch = */ false);
8358
314
}
8359
8360
// ---------------------------------------------------------------------------
8361
8362
/** \brief Instantiate a sub-class of BaseObject from a user specified text.
8363
 *
8364
 * The text can be a:
8365
 * <ul>
8366
 * <li>WKT string</li>
8367
 * <li>PROJ string</li>
8368
 * <li>database code, prefixed by its authority. e.g. "EPSG:4326"</li>
8369
 * <li>OGC URN. e.g. "urn:ogc:def:crs:EPSG::4326",
8370
 *     "urn:ogc:def:coordinateOperation:EPSG::1671",
8371
 *     "urn:ogc:def:ellipsoid:EPSG::7001"
8372
 *     or "urn:ogc:def:datum:EPSG::6326"</li>
8373
 * <li> OGC URN combining references for compound coordinate reference systems
8374
 *      e.g. "urn:ogc:def:crs,crs:EPSG::2393,crs:EPSG::5717"
8375
 *      We also accept a custom abbreviated syntax EPSG:2393+5717
8376
 * </li>
8377
 * <li> OGC URN combining references for references for projected or derived
8378
 * CRSs
8379
 *      e.g. for Projected 3D CRS "UTM zone 31N / WGS 84 (3D)"
8380
 *      "urn:ogc:def:crs,crs:EPSG::4979,cs:PROJ::ENh,coordinateOperation:EPSG::16031"
8381
 * </li>
8382
 * <li>Extension of OGC URN for CoordinateMetadata.
8383
 *     e.g.
8384
 * "urn:ogc:def:coordinateMetadata:NRCAN::NAD83_CSRS_1997_MTM11_HT2_1997"</li>
8385
 * <li> OGC URN combining references for concatenated operations
8386
 *      e.g.
8387
 * "urn:ogc:def:coordinateOperation,coordinateOperation:EPSG::3895,coordinateOperation:EPSG::1618"</li>
8388
 * <li>an Object name. e.g "WGS 84", "WGS 84 / UTM zone 31N". In that case as
8389
 *     uniqueness is not guaranteed, the function may apply heuristics to
8390
 *     determine the appropriate best match.</li>
8391
 * <li>a compound CRS made from two object names separated with " + ".
8392
 *     e.g. "WGS 84 + EGM96 height"</li>
8393
 * <li>PROJJSON string</li>
8394
 * </ul>
8395
 *
8396
 * @param text One of the above mentioned text format
8397
 * @param ctx PROJ context
8398
 * @throw ParsingException if the string cannot be parsed.
8399
 */
8400
17.3k
BaseObjectNNPtr createFromUserInput(const std::string &text, PJ_CONTEXT *ctx) {
8401
17.3k
    DatabaseContextPtr dbContext;
8402
17.3k
    try {
8403
17.3k
        if (ctx != nullptr) {
8404
            // Only connect to proj.db if needed
8405
17.3k
            if (text.find("proj=") == std::string::npos ||
8406
11.7k
                text.find("init=") != std::string::npos) {
8407
6.18k
                dbContext =
8408
6.18k
                    ctx->get_cpp_context()->getDatabaseContext().as_nullable();
8409
6.18k
            }
8410
17.3k
        }
8411
17.3k
    } catch (const std::exception &) {
8412
0
    }
8413
17.3k
    return createFromUserInput(text, dbContext, false, ctx,
8414
17.3k
                               /* ignoreCoordinateEpoch = */ false);
8415
17.3k
}
8416
8417
// ---------------------------------------------------------------------------
8418
8419
/** \brief Instantiate a sub-class of BaseObject from a WKT string.
8420
 *
8421
 * By default, validation is strict (to the extent of the checks that are
8422
 * actually implemented. Currently only WKT1 strict grammar is checked), and
8423
 * any issue detected will cause an exception to be thrown, unless
8424
 * setStrict(false) is called priorly.
8425
 *
8426
 * In non-strict mode, non-fatal issues will be recovered and simply listed
8427
 * in warningList(). This does not prevent more severe errors to cause an
8428
 * exception to be thrown.
8429
 *
8430
 * @throw ParsingException if the string cannot be parsed.
8431
 */
8432
2.89k
BaseObjectNNPtr WKTParser::createFromWKT(const std::string &wkt) {
8433
8434
2.89k
    const auto dialect = guessDialect(wkt);
8435
2.89k
    d->maybeEsriStyle_ = (dialect == WKTGuessedDialect::WKT1_ESRI);
8436
2.89k
    if (d->maybeEsriStyle_) {
8437
1.67k
        if (wkt.find("PARAMETER[\"X_Scale\",") != std::string::npos) {
8438
58
            d->esriStyle_ = true;
8439
58
            d->maybeEsriStyle_ = false;
8440
58
        }
8441
1.67k
    }
8442
8443
2.89k
    const auto build = [this, &wkt]() -> BaseObjectNNPtr {
8444
2.89k
        size_t indexEnd;
8445
2.89k
        WKTNodeNNPtr root = WKTNode::createFrom(wkt, 0, 0, indexEnd);
8446
2.89k
        const std::string &name(root->GP()->value());
8447
2.89k
        if (ci_equal(name, WKTConstants::DATUM) ||
8448
2.50k
            ci_equal(name, WKTConstants::GEODETICDATUM) ||
8449
2.50k
            ci_equal(name, WKTConstants::TRF)) {
8450
8451
90
            auto primeMeridian = PrimeMeridian::GREENWICH;
8452
90
            if (indexEnd < wkt.size()) {
8453
81
                indexEnd = skipSpace(wkt, indexEnd);
8454
81
                if (indexEnd < wkt.size() && wkt[indexEnd] == ',') {
8455
63
                    ++indexEnd;
8456
63
                    indexEnd = skipSpace(wkt, indexEnd);
8457
63
                    if (indexEnd < wkt.size() &&
8458
59
                        ci_starts_with(wkt.c_str() + indexEnd,
8459
59
                                       WKTConstants::PRIMEM.c_str())) {
8460
23
                        primeMeridian = d->buildPrimeMeridian(
8461
23
                            WKTNode::createFrom(wkt, indexEnd, 0, indexEnd),
8462
23
                            UnitOfMeasure::DEGREE);
8463
23
                    }
8464
63
                }
8465
81
            }
8466
90
            return d->buildGeodeticReferenceFrame(root, primeMeridian,
8467
90
                                                  null_node);
8468
2.80k
        } else if (ci_equal(name, WKTConstants::GEOGCS) ||
8469
2.03k
                   ci_equal(name, WKTConstants::PROJCS)) {
8470
            // Parse implicit compoundCRS from ESRI that is
8471
            // "PROJCS[...],VERTCS[...]" or "GEOGCS[...],VERTCS[...]"
8472
1.20k
            if (indexEnd < wkt.size()) {
8473
860
                indexEnd = skipSpace(wkt, indexEnd);
8474
860
                if (indexEnd < wkt.size() && wkt[indexEnd] == ',') {
8475
333
                    ++indexEnd;
8476
333
                    indexEnd = skipSpace(wkt, indexEnd);
8477
333
                    if (indexEnd < wkt.size() &&
8478
328
                        ci_starts_with(wkt.c_str() + indexEnd,
8479
328
                                       WKTConstants::VERTCS.c_str())) {
8480
239
                        auto horizCRS = d->buildCRS(root);
8481
239
                        if (horizCRS) {
8482
211
                            auto vertCRS =
8483
211
                                d->buildVerticalCRS(WKTNode::createFrom(
8484
211
                                    wkt, indexEnd, 0, indexEnd));
8485
211
                            return CompoundCRS::createLax(
8486
211
                                util::PropertyMap().set(
8487
211
                                    IdentifiedObject::NAME_KEY,
8488
211
                                    horizCRS->nameStr() + " + " +
8489
211
                                        vertCRS->nameStr()),
8490
211
                                {NN_NO_CHECK(horizCRS), vertCRS},
8491
211
                                d->dbContext_);
8492
211
                        }
8493
239
                    }
8494
333
                }
8495
860
            }
8496
1.20k
        }
8497
2.59k
        return d->build(root);
8498
2.89k
    };
8499
8500
2.89k
    auto obj = build();
8501
8502
2.89k
    if (dialect == WKTGuessedDialect::WKT1_GDAL ||
8503
1.32k
        dialect == WKTGuessedDialect::WKT1_ESRI) {
8504
867
        auto errorMsg = pj_wkt1_parse(wkt);
8505
867
        if (!errorMsg.empty()) {
8506
543
            d->emitGrammarError(errorMsg);
8507
543
        }
8508
2.02k
    } else if (dialect == WKTGuessedDialect::WKT2_2015 ||
8509
533
               dialect == WKTGuessedDialect::WKT2_2019) {
8510
533
        auto errorMsg = pj_wkt2_parse(wkt);
8511
533
        if (!errorMsg.empty()) {
8512
475
            d->emitGrammarError(errorMsg);
8513
475
        }
8514
533
    }
8515
8516
2.89k
    return obj;
8517
2.89k
}
8518
8519
// ---------------------------------------------------------------------------
8520
8521
/** \brief Attach a database context, to allow queries in it if needed.
8522
 */
8523
WKTParser &
8524
2.89k
WKTParser::attachDatabaseContext(const DatabaseContextPtr &dbContext) {
8525
2.89k
    d->dbContext_ = dbContext;
8526
2.89k
    return *this;
8527
2.89k
}
8528
8529
// ---------------------------------------------------------------------------
8530
8531
/** \brief Guess the "dialect" of the WKT string.
8532
 */
8533
WKTParser::WKTGuessedDialect
8534
2.89k
WKTParser::guessDialect(const std::string &inputWkt) noexcept {
8535
8536
    // cppcheck complains (rightly) that the method could be static
8537
2.89k
    (void)this;
8538
8539
2.89k
    std::string wkt = inputWkt;
8540
2.89k
    std::size_t idxFirstCharNotSpace = wkt.find_first_not_of(" \t\r\n");
8541
2.89k
    if (idxFirstCharNotSpace > 0 && idxFirstCharNotSpace != std::string::npos) {
8542
0
        wkt = wkt.substr(idxFirstCharNotSpace);
8543
0
    }
8544
2.89k
    if (ci_starts_with(wkt, WKTConstants::VERTCS)) {
8545
178
        return WKTGuessedDialect::WKT1_ESRI;
8546
178
    }
8547
2.71k
    const std::string *const wkt1_keywords[] = {
8548
2.71k
        &WKTConstants::GEOCCS, &WKTConstants::GEOGCS,  &WKTConstants::COMPD_CS,
8549
2.71k
        &WKTConstants::PROJCS, &WKTConstants::VERT_CS, &WKTConstants::LOCAL_CS};
8550
11.4k
    for (const auto &pointerKeyword : wkt1_keywords) {
8551
11.4k
        if (ci_starts_with(wkt, *pointerKeyword)) {
8552
8553
1.80k
            if ((ci_find(wkt, "GEOGCS[\"GCS_") != std::string::npos ||
8554
1.48k
                 (!ci_starts_with(wkt, WKTConstants::LOCAL_CS) &&
8555
1.33k
                  ci_find(wkt, "AXIS[") == std::string::npos &&
8556
1.22k
                  ci_find(wkt, "AUTHORITY[") == std::string::npos)) &&
8557
                // WKT1:GDAL and WKT1:ESRI have both a
8558
                // Hotine_Oblique_Mercator_Azimuth_Center If providing a
8559
                // WKT1:GDAL without AXIS, we may wrongly detect it as WKT1:ESRI
8560
                // and skip the rectified_grid_angle parameter cf
8561
                // https://github.com/OSGeo/PROJ/issues/3279
8562
1.50k
                ci_find(wkt, "PARAMETER[\"rectified_grid_angle") ==
8563
1.50k
                    std::string::npos) {
8564
1.49k
                return WKTGuessedDialect::WKT1_ESRI;
8565
1.49k
            }
8566
8567
308
            return WKTGuessedDialect::WKT1_GDAL;
8568
1.80k
        }
8569
11.4k
    }
8570
8571
918
    const std::string *const wkt2_2019_only_keywords[] = {
8572
918
        &WKTConstants::GEOGCRS,
8573
        // contained in previous one
8574
        // &WKTConstants::BASEGEOGCRS,
8575
918
        &WKTConstants::CONCATENATEDOPERATION, &WKTConstants::USAGE,
8576
918
        &WKTConstants::DYNAMIC, &WKTConstants::FRAMEEPOCH, &WKTConstants::MODEL,
8577
918
        &WKTConstants::VELOCITYGRID, &WKTConstants::ENSEMBLE,
8578
918
        &WKTConstants::DERIVEDPROJCRS, &WKTConstants::BASEPROJCRS,
8579
918
        &WKTConstants::GEOGRAPHICCRS, &WKTConstants::TRF, &WKTConstants::VRF,
8580
918
        &WKTConstants::POINTMOTIONOPERATION};
8581
8582
12.3k
    for (const auto &pointerKeyword : wkt2_2019_only_keywords) {
8583
12.3k
        auto pos = ci_find(wkt, *pointerKeyword);
8584
12.3k
        if (pos != std::string::npos &&
8585
308
            wkt[pos + pointerKeyword->size()] == '[') {
8586
242
            return WKTGuessedDialect::WKT2_2019;
8587
242
        }
8588
12.3k
    }
8589
676
    static const char *const wkt2_2019_only_substrings[] = {
8590
676
        "CS[TemporalDateTime,",
8591
676
        "CS[TemporalCount,",
8592
676
        "CS[TemporalMeasure,",
8593
676
    };
8594
2.01k
    for (const auto &substrings : wkt2_2019_only_substrings) {
8595
2.01k
        if (ci_find(wkt, substrings) != std::string::npos) {
8596
17
            return WKTGuessedDialect::WKT2_2019;
8597
17
        }
8598
2.01k
    }
8599
8600
23.9k
    for (const auto &wktConstant : WKTConstants::constants()) {
8601
23.9k
        if (ci_starts_with(wkt, wktConstant)) {
8602
660
            for (auto wktPtr = wkt.c_str() + wktConstant.size();
8603
899
                 *wktPtr != '\0'; ++wktPtr) {
8604
899
                if (isspace(static_cast<unsigned char>(*wktPtr)))
8605
239
                    continue;
8606
660
                if (*wktPtr == '[') {
8607
659
                    return WKTGuessedDialect::WKT2_2015;
8608
659
                }
8609
1
                break;
8610
660
            }
8611
660
        }
8612
23.9k
    }
8613
8614
0
    return WKTGuessedDialect::NOT_WKT;
8615
659
}
8616
8617
// ---------------------------------------------------------------------------
8618
8619
//! @cond Doxygen_Suppress
8620
FormattingException::FormattingException(const char *message)
8621
198
    : Exception(message) {}
8622
8623
// ---------------------------------------------------------------------------
8624
8625
FormattingException::FormattingException(const std::string &message)
8626
567
    : Exception(message) {}
8627
8628
// ---------------------------------------------------------------------------
8629
8630
0
FormattingException::FormattingException(const FormattingException &) = default;
8631
8632
// ---------------------------------------------------------------------------
8633
8634
765
FormattingException::~FormattingException() = default;
8635
8636
// ---------------------------------------------------------------------------
8637
8638
4
void FormattingException::Throw(const char *msg) {
8639
4
    throw FormattingException(msg);
8640
4
}
8641
8642
// ---------------------------------------------------------------------------
8643
8644
0
void FormattingException::Throw(const std::string &msg) {
8645
0
    throw FormattingException(msg);
8646
0
}
8647
8648
// ---------------------------------------------------------------------------
8649
8650
4.38k
ParsingException::ParsingException(const char *message) : Exception(message) {}
8651
8652
// ---------------------------------------------------------------------------
8653
8654
ParsingException::ParsingException(const std::string &message)
8655
3.38k
    : Exception(message) {}
8656
8657
// ---------------------------------------------------------------------------
8658
8659
0
ParsingException::ParsingException(const ParsingException &) = default;
8660
8661
// ---------------------------------------------------------------------------
8662
8663
7.76k
ParsingException::~ParsingException() = default;
8664
8665
// ---------------------------------------------------------------------------
8666
8667
1.28M
IPROJStringExportable::~IPROJStringExportable() = default;
8668
8669
// ---------------------------------------------------------------------------
8670
8671
std::string IPROJStringExportable::exportToPROJString(
8672
126k
    PROJStringFormatter *formatter) const {
8673
126k
    const bool bIsCRS = dynamic_cast<const crs::CRS *>(this) != nullptr;
8674
126k
    if (bIsCRS) {
8675
0
        formatter->setCRSExport(true);
8676
0
    }
8677
126k
    _exportToPROJString(formatter);
8678
126k
    if (formatter->getAddNoDefs() && bIsCRS) {
8679
0
        if (!formatter->hasParam("no_defs")) {
8680
0
            formatter->addParam("no_defs");
8681
0
        }
8682
0
    }
8683
126k
    if (bIsCRS) {
8684
0
        if (!formatter->hasParam("type")) {
8685
0
            formatter->addParam("type", "crs");
8686
0
        }
8687
0
        formatter->setCRSExport(false);
8688
0
    }
8689
126k
    return formatter->toString();
8690
126k
}
8691
//! @endcond
8692
8693
// ---------------------------------------------------------------------------
8694
8695
//! @cond Doxygen_Suppress
8696
8697
struct Step {
8698
    std::string name{};
8699
    bool isInit = false;
8700
    bool inverted{false};
8701
8702
    struct KeyValue {
8703
        std::string key{};
8704
        std::string value{};
8705
        bool usedByParser = false; // only for PROJStringParser used
8706
8707
3.31M
        explicit KeyValue(const std::string &keyIn) : key(keyIn) {}
8708
8709
        KeyValue(const char *keyIn, const std::string &valueIn);
8710
8711
        KeyValue(const std::string &keyIn, const std::string &valueIn)
8712
8.20M
            : key(keyIn), value(valueIn) {}
8713
8714
        // cppcheck-suppress functionStatic
8715
6.50M
        bool keyEquals(const char *otherKey) const noexcept {
8716
6.50M
            return key == otherKey;
8717
6.50M
        }
8718
8719
        // cppcheck-suppress functionStatic
8720
2.07M
        bool equals(const char *otherKey, const char *otherVal) const noexcept {
8721
2.07M
            return key == otherKey && value == otherVal;
8722
2.07M
        }
8723
8724
596
        bool operator==(const KeyValue &other) const noexcept {
8725
596
            return key == other.key && value == other.value;
8726
596
        }
8727
8728
120k
        bool operator!=(const KeyValue &other) const noexcept {
8729
120k
            return key != other.key || value != other.value;
8730
120k
        }
8731
    };
8732
8733
    std::vector<KeyValue> paramValues{};
8734
8735
57.2k
    bool hasKey(const char *keyName) const {
8736
634k
        for (const auto &kv : paramValues) {
8737
634k
            if (kv.key == keyName) {
8738
35
                return true;
8739
35
            }
8740
634k
        }
8741
57.2k
        return false;
8742
57.2k
    }
8743
};
8744
8745
Step::KeyValue::KeyValue(const char *keyIn, const std::string &valueIn)
8746
107k
    : key(keyIn), value(valueIn) {}
8747
8748
struct PROJStringFormatter::Private {
8749
    PROJStringFormatter::Convention convention_ =
8750
        PROJStringFormatter::Convention::PROJ_5;
8751
    std::vector<double> toWGS84Parameters_{};
8752
    std::string vDatumExtension_{};
8753
    std::string geoidCRSValue_{};
8754
    std::string hDatumExtension_{};
8755
    crs::GeographicCRSPtr geogCRSOfCompoundCRS_{};
8756
8757
    std::list<Step> steps_{};
8758
    std::vector<Step::KeyValue> globalParamValues_{};
8759
8760
    struct InversionStackElt {
8761
        std::list<Step>::iterator startIter{};
8762
        bool iterValid = false;
8763
        bool currentInversionState = false;
8764
    };
8765
    std::vector<InversionStackElt> inversionStack_{InversionStackElt()};
8766
    bool omitProjLongLatIfPossible_ = false;
8767
    std::vector<bool> omitZUnitConversion_{false};
8768
    std::vector<bool> omitHorizontalConversionInVertTransformation_{false};
8769
    DatabaseContextPtr dbContext_{};
8770
    bool useApproxTMerc_ = false;
8771
    bool addNoDefs_ = true;
8772
    bool coordOperationOptimizations_ = false;
8773
    bool crsExport_ = false;
8774
    bool legacyCRSToCRSContext_ = false;
8775
    bool multiLine_ = false;
8776
    bool normalizeOutput_ = false;
8777
    int indentWidth_ = 2;
8778
    int indentLevel_ = 0;
8779
    int maxLineLength_ = 80;
8780
8781
    std::string result_{};
8782
8783
    // cppcheck-suppress functionStatic
8784
    void appendToResult(const char *str);
8785
8786
    // cppcheck-suppress functionStatic
8787
    void addStep();
8788
};
8789
8790
//! @endcond
8791
8792
// ---------------------------------------------------------------------------
8793
8794
//! @cond Doxygen_Suppress
8795
PROJStringFormatter::PROJStringFormatter(Convention conventionIn,
8796
                                         const DatabaseContextPtr &dbContext)
8797
372k
    : d(std::make_unique<Private>()) {
8798
372k
    d->convention_ = conventionIn;
8799
372k
    d->dbContext_ = dbContext;
8800
372k
}
8801
//! @endcond
8802
8803
// ---------------------------------------------------------------------------
8804
8805
//! @cond Doxygen_Suppress
8806
372k
PROJStringFormatter::~PROJStringFormatter() = default;
8807
//! @endcond
8808
8809
// ---------------------------------------------------------------------------
8810
8811
/** \brief Constructs a new formatter.
8812
 *
8813
 * A formatter can be used only once (its internal state is mutated)
8814
 *
8815
 * Its default behavior can be adjusted with the different setters.
8816
 *
8817
 * @param conventionIn PROJ string flavor. Defaults to Convention::PROJ_5
8818
 * @param dbContext Database context (can help to find alternative grid names).
8819
 * May be nullptr
8820
 * @return new formatter.
8821
 */
8822
PROJStringFormatterNNPtr
8823
PROJStringFormatter::create(Convention conventionIn,
8824
372k
                            DatabaseContextPtr dbContext) {
8825
372k
    return NN_NO_CHECK(PROJStringFormatter::make_unique<PROJStringFormatter>(
8826
372k
        conventionIn, dbContext));
8827
372k
}
8828
8829
// ---------------------------------------------------------------------------
8830
8831
/** \brief Set whether approximate Transverse Mercator or UTM should be used */
8832
0
void PROJStringFormatter::setUseApproxTMerc(bool flag) {
8833
0
    d->useApproxTMerc_ = flag;
8834
0
}
8835
8836
// ---------------------------------------------------------------------------
8837
8838
/** \brief Whether to use multi line output or not. */
8839
PROJStringFormatter &
8840
0
PROJStringFormatter::setMultiLine(bool multiLine) noexcept {
8841
0
    d->multiLine_ = multiLine;
8842
0
    return *this;
8843
0
}
8844
8845
// ---------------------------------------------------------------------------
8846
8847
/** \brief Set number of spaces for each indentation level (defaults to 2).
8848
 */
8849
PROJStringFormatter &
8850
0
PROJStringFormatter::setIndentationWidth(int width) noexcept {
8851
0
    d->indentWidth_ = width;
8852
0
    return *this;
8853
0
}
8854
8855
// ---------------------------------------------------------------------------
8856
8857
/** \brief Set the maximum size of a line (when multiline output is enable).
8858
 * Can be set to 0 for unlimited length.
8859
 */
8860
PROJStringFormatter &
8861
0
PROJStringFormatter::setMaxLineLength(int maxLineLength) noexcept {
8862
0
    d->maxLineLength_ = maxLineLength;
8863
0
    return *this;
8864
0
}
8865
8866
// ---------------------------------------------------------------------------
8867
8868
/** \brief Returns the PROJ string. */
8869
253k
const std::string &PROJStringFormatter::toString() const {
8870
8871
253k
    assert(d->inversionStack_.size() == 1);
8872
8873
253k
    d->result_.clear();
8874
8875
253k
    auto &steps = d->steps_;
8876
8877
253k
    if (d->normalizeOutput_) {
8878
        // Sort +key=value options of each step in lexicographic order.
8879
14.5k
        for (auto &step : steps) {
8880
12.7k
            std::sort(step.paramValues.begin(), step.paramValues.end(),
8881
4.89M
                      [](const Step::KeyValue &a, const Step::KeyValue &b) {
8882
4.89M
                          return a.key < b.key;
8883
4.89M
                      });
8884
12.7k
        }
8885
14.5k
    }
8886
8887
3.86M
    for (auto iter = steps.begin(); iter != steps.end();) {
8888
        // Remove no-op helmert
8889
3.61M
        auto &step = *iter;
8890
3.61M
        const auto paramCount = step.paramValues.size();
8891
3.61M
        if (step.name == "helmert" && (paramCount == 3 || paramCount == 8) &&
8892
174k
            step.paramValues[0].equals("x", "0") &&
8893
26.1k
            step.paramValues[1].equals("y", "0") &&
8894
15.0k
            step.paramValues[2].equals("z", "0") &&
8895
14.7k
            (paramCount == 3 ||
8896
404
             (step.paramValues[3].equals("rx", "0") &&
8897
113
              step.paramValues[4].equals("ry", "0") &&
8898
103
              step.paramValues[5].equals("rz", "0") &&
8899
99
              step.paramValues[6].equals("s", "0") &&
8900
14.4k
              step.paramValues[7].keyEquals("convention")))) {
8901
14.4k
            iter = steps.erase(iter);
8902
3.59M
        } else if (d->coordOperationOptimizations_ &&
8903
3.18M
                   step.name == "unitconvert" && paramCount == 2 &&
8904
884k
                   step.paramValues[0].keyEquals("xy_in") &&
8905
872k
                   step.paramValues[1].keyEquals("xy_out") &&
8906
872k
                   step.paramValues[0].value == step.paramValues[1].value) {
8907
44
            iter = steps.erase(iter);
8908
3.59M
        } else if (step.name == "push" && step.inverted) {
8909
28.0k
            step.name = "pop";
8910
28.0k
            step.inverted = false;
8911
28.0k
            ++iter;
8912
3.56M
        } else if (step.name == "pop" && step.inverted) {
8913
35.9k
            step.name = "push";
8914
35.9k
            step.inverted = false;
8915
35.9k
            ++iter;
8916
3.53M
        } else if (step.name == "noop" && steps.size() > 1) {
8917
1.66k
            iter = steps.erase(iter);
8918
3.53M
        } else {
8919
3.53M
            ++iter;
8920
3.53M
        }
8921
3.61M
    }
8922
8923
3.59M
    for (auto &step : steps) {
8924
3.59M
        if (!step.inverted) {
8925
2.02M
            continue;
8926
2.02M
        }
8927
8928
1.56M
        const auto paramCount = step.paramValues.size();
8929
8930
        // axisswap order=2,1 (or 1,-2) is its own inverse
8931
1.56M
        if (step.name == "axisswap" && paramCount == 1 &&
8932
334k
            (step.paramValues[0].equals("order", "2,1") ||
8933
323k
             step.paramValues[0].equals("order", "1,-2"))) {
8934
323k
            step.inverted = false;
8935
323k
            continue;
8936
323k
        }
8937
8938
        // axisswap inv order=2,-1 ==> axisswap order -2,1
8939
1.24M
        if (step.name == "axisswap" && paramCount == 1 &&
8940
11.2k
            step.paramValues[0].equals("order", "2,-1")) {
8941
509
            step.inverted = false;
8942
509
            step.paramValues[0] = Step::KeyValue("order", "-2,1");
8943
509
            continue;
8944
509
        }
8945
8946
        // axisswap order=1,2,-3 is its own inverse
8947
1.24M
        if (step.name == "axisswap" && paramCount == 1 &&
8948
10.7k
            step.paramValues[0].equals("order", "1,2,-3")) {
8949
0
            step.inverted = false;
8950
0
            continue;
8951
0
        }
8952
8953
        // handle unitconvert inverse
8954
1.24M
        if (step.name == "unitconvert" && paramCount == 2 &&
8955
472k
            step.paramValues[0].keyEquals("xy_in") &&
8956
462k
            step.paramValues[1].keyEquals("xy_out")) {
8957
462k
            std::swap(step.paramValues[0].value, step.paramValues[1].value);
8958
462k
            step.inverted = false;
8959
462k
            continue;
8960
462k
        }
8961
8962
781k
        if (step.name == "unitconvert" && paramCount == 2 &&
8963
10.5k
            step.paramValues[0].keyEquals("z_in") &&
8964
9.30k
            step.paramValues[1].keyEquals("z_out")) {
8965
8.45k
            std::swap(step.paramValues[0].value, step.paramValues[1].value);
8966
8.45k
            step.inverted = false;
8967
8.45k
            continue;
8968
8.45k
        }
8969
8970
772k
        if (step.name == "unitconvert" && paramCount == 4 &&
8971
39.7k
            step.paramValues[0].keyEquals("xy_in") &&
8972
38.9k
            step.paramValues[1].keyEquals("z_in") &&
8973
38.6k
            step.paramValues[2].keyEquals("xy_out") &&
8974
38.4k
            step.paramValues[3].keyEquals("z_out")) {
8975
38.3k
            std::swap(step.paramValues[0].value, step.paramValues[2].value);
8976
38.3k
            std::swap(step.paramValues[1].value, step.paramValues[3].value);
8977
38.3k
            step.inverted = false;
8978
38.3k
            continue;
8979
38.3k
        }
8980
8981
        // set does the same in forward and inverse paths
8982
734k
        if (step.name == "set") {
8983
7.25k
            step.inverted = false;
8984
7.25k
        }
8985
734k
    }
8986
8987
253k
    {
8988
253k
        auto iterCur = steps.begin();
8989
253k
        if (iterCur != steps.end()) {
8990
245k
            ++iterCur;
8991
245k
        }
8992
4.18M
        while (iterCur != steps.end()) {
8993
8994
3.93M
            assert(iterCur != steps.begin());
8995
3.93M
            auto iterPrev = std::prev(iterCur);
8996
3.93M
            auto &prevStep = *iterPrev;
8997
3.93M
            auto &curStep = *iterCur;
8998
8999
3.93M
            const auto curStepParamCount = curStep.paramValues.size();
9000
3.93M
            const auto prevStepParamCount = prevStep.paramValues.size();
9001
9002
3.93M
            const auto deletePrevAndCurIter = [&steps, &iterPrev, &iterCur]() {
9003
774k
                iterCur = steps.erase(iterPrev, std::next(iterCur));
9004
774k
                if (iterCur != steps.begin())
9005
698k
                    iterCur = std::prev(iterCur);
9006
774k
                if (iterCur == steps.begin() && iterCur != steps.end())
9007
150k
                    ++iterCur;
9008
774k
            };
9009
9010
            // longlat (or its inverse) with ellipsoid only is a no-op
9011
            // do that only for an internal step
9012
3.93M
            if (std::next(iterCur) != steps.end() &&
9013
3.69M
                curStep.name == "longlat" && curStepParamCount == 1 &&
9014
410k
                curStep.paramValues[0].keyEquals("ellps")) {
9015
384k
                iterCur = steps.erase(iterCur);
9016
384k
                continue;
9017
384k
            }
9018
9019
            // push v_x followed by pop v_x is a no-op.
9020
3.54M
            if (curStep.name == "pop" && prevStep.name == "push" &&
9021
10.2k
                !curStep.inverted && !prevStep.inverted &&
9022
10.2k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9023
9.29k
                curStep.paramValues[0].key == prevStep.paramValues[0].key) {
9024
9.00k
                deletePrevAndCurIter();
9025
9.00k
                continue;
9026
9.00k
            }
9027
9028
            // pop v_x followed by push v_x is, almost, a no-op. For our
9029
            // purposes,
9030
            // we consider it as a no-op for better pipeline optimizations.
9031
3.53M
            if (curStep.name == "push" && prevStep.name == "pop" &&
9032
7.20k
                !curStep.inverted && !prevStep.inverted &&
9033
7.20k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9034
6.07k
                curStep.paramValues[0].key == prevStep.paramValues[0].key) {
9035
5.78k
                deletePrevAndCurIter();
9036
5.78k
                continue;
9037
5.78k
            }
9038
9039
            // unitconvert (xy) followed by its inverse is a no-op
9040
3.53M
            if (curStep.name == "unitconvert" &&
9041
1.28M
                prevStep.name == "unitconvert" && !curStep.inverted &&
9042
408k
                !prevStep.inverted && curStepParamCount == 2 &&
9043
370k
                prevStepParamCount == 2 &&
9044
337k
                curStep.paramValues[0].keyEquals("xy_in") &&
9045
332k
                prevStep.paramValues[0].keyEquals("xy_in") &&
9046
323k
                curStep.paramValues[1].keyEquals("xy_out") &&
9047
323k
                prevStep.paramValues[1].keyEquals("xy_out") &&
9048
323k
                curStep.paramValues[0].value == prevStep.paramValues[1].value &&
9049
323k
                curStep.paramValues[1].value == prevStep.paramValues[0].value) {
9050
323k
                deletePrevAndCurIter();
9051
323k
                continue;
9052
323k
            }
9053
9054
            // unitconvert (z) followed by its inverse is a no-op
9055
3.21M
            if (curStep.name == "unitconvert" &&
9056
959k
                prevStep.name == "unitconvert" && !curStep.inverted &&
9057
85.6k
                !prevStep.inverted && curStepParamCount == 2 &&
9058
47.3k
                prevStepParamCount == 2 &&
9059
14.0k
                curStep.paramValues[0].keyEquals("z_in") &&
9060
4.60k
                prevStep.paramValues[0].keyEquals("z_in") &&
9061
1.92k
                curStep.paramValues[1].keyEquals("z_out") &&
9062
1.72k
                prevStep.paramValues[1].keyEquals("z_out") &&
9063
1.64k
                curStep.paramValues[0].value == prevStep.paramValues[1].value &&
9064
1.51k
                curStep.paramValues[1].value == prevStep.paramValues[0].value) {
9065
1.34k
                deletePrevAndCurIter();
9066
1.34k
                continue;
9067
1.34k
            }
9068
9069
            // unitconvert (xyz) followed by its inverse is a no-op
9070
3.20M
            if (curStep.name == "unitconvert" &&
9071
957k
                prevStep.name == "unitconvert" && !curStep.inverted &&
9072
84.2k
                !prevStep.inverted && curStepParamCount == 4 &&
9073
36.2k
                prevStepParamCount == 4 &&
9074
20.1k
                curStep.paramValues[0].keyEquals("xy_in") &&
9075
19.8k
                prevStep.paramValues[0].keyEquals("xy_in") &&
9076
19.6k
                curStep.paramValues[1].keyEquals("z_in") &&
9077
19.5k
                prevStep.paramValues[1].keyEquals("z_in") &&
9078
19.4k
                curStep.paramValues[2].keyEquals("xy_out") &&
9079
19.3k
                prevStep.paramValues[2].keyEquals("xy_out") &&
9080
19.3k
                curStep.paramValues[3].keyEquals("z_out") &&
9081
19.3k
                prevStep.paramValues[3].keyEquals("z_out") &&
9082
19.2k
                curStep.paramValues[0].value == prevStep.paramValues[2].value &&
9083
18.5k
                curStep.paramValues[1].value == prevStep.paramValues[3].value &&
9084
18.2k
                curStep.paramValues[2].value == prevStep.paramValues[0].value &&
9085
17.8k
                curStep.paramValues[3].value == prevStep.paramValues[1].value) {
9086
15.6k
                deletePrevAndCurIter();
9087
15.6k
                continue;
9088
15.6k
            }
9089
9090
3.19M
            const auto deletePrevIter = [&steps, &iterPrev, &iterCur]() {
9091
23.7k
                steps.erase(iterPrev, iterCur);
9092
23.7k
                if (iterCur != steps.begin())
9093
20.0k
                    iterCur = std::prev(iterCur);
9094
23.7k
                if (iterCur == steps.begin())
9095
6.03k
                    ++iterCur;
9096
23.7k
            };
9097
9098
            // combine unitconvert (xy) and unitconvert (z)
9099
3.19M
            bool changeDone = false;
9100
9.56M
            for (int k = 0; k < 2; ++k) {
9101
6.38M
                auto &first = (k == 0) ? curStep : prevStep;
9102
6.38M
                auto &second = (k == 0) ? prevStep : curStep;
9103
6.38M
                if (first.name == "unitconvert" &&
9104
1.56M
                    second.name == "unitconvert" && !first.inverted &&
9105
134k
                    !second.inverted && first.paramValues.size() == 2 &&
9106
72.4k
                    second.paramValues.size() == 2 &&
9107
22.9k
                    second.paramValues[0].keyEquals("xy_in") &&
9108
12.2k
                    second.paramValues[1].keyEquals("xy_out") &&
9109
11.6k
                    first.paramValues[0].keyEquals("z_in") &&
9110
11.0k
                    first.paramValues[1].keyEquals("z_out")) {
9111
9112
10.6k
                    const std::string xy_in(second.paramValues[0].value);
9113
10.6k
                    const std::string xy_out(second.paramValues[1].value);
9114
10.6k
                    const std::string z_in(first.paramValues[0].value);
9115
10.6k
                    const std::string z_out(first.paramValues[1].value);
9116
9117
10.6k
                    iterCur->paramValues.clear();
9118
10.6k
                    iterCur->paramValues.emplace_back(
9119
10.6k
                        Step::KeyValue("xy_in", xy_in));
9120
10.6k
                    iterCur->paramValues.emplace_back(
9121
10.6k
                        Step::KeyValue("z_in", z_in));
9122
10.6k
                    iterCur->paramValues.emplace_back(
9123
10.6k
                        Step::KeyValue("xy_out", xy_out));
9124
10.6k
                    iterCur->paramValues.emplace_back(
9125
10.6k
                        Step::KeyValue("z_out", z_out));
9126
9127
10.6k
                    deletePrevIter();
9128
10.6k
                    changeDone = true;
9129
10.6k
                    break;
9130
10.6k
                }
9131
6.38M
            }
9132
3.19M
            if (changeDone) {
9133
10.6k
                continue;
9134
10.6k
            }
9135
9136
            // +step +proj=unitconvert +xy_in=X1 +xy_out=X2
9137
            //  +step +proj=unitconvert +xy_in=X2 +z_in=Z1 +xy_out=X1 +z_out=Z2
9138
            // ==> step +proj=unitconvert +z_in=Z1 +z_out=Z2
9139
9.48M
            for (int k = 0; k < 2; ++k) {
9140
6.35M
                auto &first = (k == 0) ? curStep : prevStep;
9141
6.35M
                auto &second = (k == 0) ? prevStep : curStep;
9142
6.35M
                if (first.name == "unitconvert" &&
9143
1.52M
                    second.name == "unitconvert" && !first.inverted &&
9144
101k
                    !second.inverted && first.paramValues.size() == 4 &&
9145
58.2k
                    second.paramValues.size() == 2 &&
9146
49.0k
                    first.paramValues[0].keyEquals("xy_in") &&
9147
48.6k
                    first.paramValues[1].keyEquals("z_in") &&
9148
48.4k
                    first.paramValues[2].keyEquals("xy_out") &&
9149
48.2k
                    first.paramValues[3].keyEquals("z_out") &&
9150
48.2k
                    second.paramValues[0].keyEquals("xy_in") &&
9151
46.8k
                    second.paramValues[1].keyEquals("xy_out") &&
9152
46.7k
                    first.paramValues[0].value == second.paramValues[1].value &&
9153
46.0k
                    first.paramValues[2].value == second.paramValues[0].value) {
9154
45.9k
                    const std::string z_in(first.paramValues[1].value);
9155
45.9k
                    const std::string z_out(first.paramValues[3].value);
9156
45.9k
                    if (z_in != z_out) {
9157
9.33k
                        iterCur->paramValues.clear();
9158
9.33k
                        iterCur->paramValues.emplace_back(
9159
9.33k
                            Step::KeyValue("z_in", z_in));
9160
9.33k
                        iterCur->paramValues.emplace_back(
9161
9.33k
                            Step::KeyValue("z_out", z_out));
9162
9.33k
                        deletePrevIter();
9163
36.6k
                    } else {
9164
36.6k
                        deletePrevAndCurIter();
9165
36.6k
                    }
9166
45.9k
                    changeDone = true;
9167
45.9k
                    break;
9168
45.9k
                }
9169
6.35M
            }
9170
3.18M
            if (changeDone) {
9171
45.9k
                continue;
9172
45.9k
            }
9173
9174
            // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2
9175
            // +step +proj=unitconvert +z_in=Z2 +z_out=Z3
9176
            // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2
9177
            // +z_out=Z3
9178
3.13M
            if (prevStep.name == "unitconvert" &&
9179
566k
                curStep.name == "unitconvert" && !prevStep.inverted &&
9180
11.7k
                !curStep.inverted && prevStep.paramValues.size() == 4 &&
9181
6.20k
                curStep.paramValues.size() == 2 &&
9182
1.64k
                prevStep.paramValues[0].keyEquals("xy_in") &&
9183
1.35k
                prevStep.paramValues[1].keyEquals("z_in") &&
9184
1.27k
                prevStep.paramValues[2].keyEquals("xy_out") &&
9185
1.20k
                prevStep.paramValues[3].keyEquals("z_out") &&
9186
1.19k
                curStep.paramValues[0].keyEquals("z_in") &&
9187
673
                curStep.paramValues[1].keyEquals("z_out") &&
9188
580
                prevStep.paramValues[3].value == curStep.paramValues[0].value) {
9189
504
                const std::string xy_in(prevStep.paramValues[0].value);
9190
504
                const std::string z_in(prevStep.paramValues[1].value);
9191
504
                const std::string xy_out(prevStep.paramValues[2].value);
9192
504
                const std::string z_out(curStep.paramValues[1].value);
9193
9194
504
                iterCur->paramValues.clear();
9195
504
                iterCur->paramValues.emplace_back(
9196
504
                    Step::KeyValue("xy_in", xy_in));
9197
504
                iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in));
9198
504
                iterCur->paramValues.emplace_back(
9199
504
                    Step::KeyValue("xy_out", xy_out));
9200
504
                iterCur->paramValues.emplace_back(
9201
504
                    Step::KeyValue("z_out", z_out));
9202
9203
504
                deletePrevIter();
9204
504
                continue;
9205
504
            }
9206
9207
            // +step +proj=unitconvert +z_in=Z1 +z_out=Z2
9208
            // +step +proj=unitconvert +xy_in=X1 +z_in=Z2 +xy_out=X2 +z_out=Z3
9209
            // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2
9210
            // +z_out=Z3
9211
3.13M
            if (prevStep.name == "unitconvert" &&
9212
566k
                curStep.name == "unitconvert" && !prevStep.inverted &&
9213
11.2k
                !curStep.inverted && prevStep.paramValues.size() == 2 &&
9214
3.65k
                curStep.paramValues.size() == 4 &&
9215
1.46k
                prevStep.paramValues[0].keyEquals("z_in") &&
9216
701
                prevStep.paramValues[1].keyEquals("z_out") &&
9217
617
                curStep.paramValues[0].keyEquals("xy_in") &&
9218
578
                curStep.paramValues[1].keyEquals("z_in") &&
9219
561
                curStep.paramValues[2].keyEquals("xy_out") &&
9220
550
                curStep.paramValues[3].keyEquals("z_out") &&
9221
550
                prevStep.paramValues[1].value == curStep.paramValues[1].value) {
9222
103
                const std::string xy_in(curStep.paramValues[0].value);
9223
103
                const std::string z_in(prevStep.paramValues[0].value);
9224
103
                const std::string xy_out(curStep.paramValues[2].value);
9225
103
                const std::string z_out(curStep.paramValues[3].value);
9226
9227
103
                iterCur->paramValues.clear();
9228
103
                iterCur->paramValues.emplace_back(
9229
103
                    Step::KeyValue("xy_in", xy_in));
9230
103
                iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in));
9231
103
                iterCur->paramValues.emplace_back(
9232
103
                    Step::KeyValue("xy_out", xy_out));
9233
103
                iterCur->paramValues.emplace_back(
9234
103
                    Step::KeyValue("z_out", z_out));
9235
9236
103
                deletePrevIter();
9237
103
                continue;
9238
103
            }
9239
9240
            // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2
9241
            // +step +proj=unitconvert +xy_in=X2 +xy_out=X3
9242
            // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X3
9243
            // +z_out=Z2
9244
3.13M
            if (prevStep.name == "unitconvert" &&
9245
565k
                curStep.name == "unitconvert" && !prevStep.inverted &&
9246
11.1k
                !curStep.inverted && prevStep.paramValues.size() == 4 &&
9247
5.69k
                curStep.paramValues.size() == 2 &&
9248
1.13k
                prevStep.paramValues[0].keyEquals("xy_in") &&
9249
847
                prevStep.paramValues[1].keyEquals("z_in") &&
9250
770
                prevStep.paramValues[2].keyEquals("xy_out") &&
9251
701
                prevStep.paramValues[3].keyEquals("z_out") &&
9252
687
                curStep.paramValues[0].keyEquals("xy_in") &&
9253
473
                curStep.paramValues[1].keyEquals("xy_out") &&
9254
418
                prevStep.paramValues[2].value == curStep.paramValues[0].value) {
9255
30
                const std::string xy_in(prevStep.paramValues[0].value);
9256
30
                const std::string z_in(prevStep.paramValues[1].value);
9257
30
                const std::string xy_out(curStep.paramValues[1].value);
9258
30
                const std::string z_out(prevStep.paramValues[3].value);
9259
9260
30
                iterCur->paramValues.clear();
9261
30
                iterCur->paramValues.emplace_back(
9262
30
                    Step::KeyValue("xy_in", xy_in));
9263
30
                iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in));
9264
30
                iterCur->paramValues.emplace_back(
9265
30
                    Step::KeyValue("xy_out", xy_out));
9266
30
                iterCur->paramValues.emplace_back(
9267
30
                    Step::KeyValue("z_out", z_out));
9268
9269
30
                deletePrevIter();
9270
30
                continue;
9271
30
            }
9272
9273
            // clang-format off
9274
            // A bit odd. Used to simplify geog3d_feet -> EPSG:6318+6360
9275
            // of https://github.com/OSGeo/PROJ/issues/3938
9276
            // where we get originally
9277
            // +step +proj=unitconvert +xy_in=deg +z_in=ft +xy_out=rad +z_out=us-ft
9278
            // +step +proj=unitconvert +xy_in=rad +z_in=m +xy_out=deg +z_out=m
9279
            // and want it simplified as:
9280
            // +step +proj=unitconvert +xy_in=deg +z_in=ft +xy_out=deg +z_out=us-ft
9281
            //
9282
            // More generally:
9283
            // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z2
9284
            // +step +proj=unitconvert +xy_in=X2 +z_in=Z3 +xy_out=X3 +z_out=Z3
9285
            // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X3 +z_out=Z2
9286
            // clang-format on
9287
3.13M
            if (prevStep.name == "unitconvert" &&
9288
565k
                curStep.name == "unitconvert" && !prevStep.inverted &&
9289
11.1k
                !curStep.inverted && prevStep.paramValues.size() == 4 &&
9290
5.66k
                curStep.paramValues.size() == 4 &&
9291
4.48k
                prevStep.paramValues[0].keyEquals("xy_in") &&
9292
4.19k
                prevStep.paramValues[1].keyEquals("z_in") &&
9293
3.98k
                prevStep.paramValues[2].keyEquals("xy_out") &&
9294
3.91k
                prevStep.paramValues[3].keyEquals("z_out") &&
9295
3.80k
                curStep.paramValues[0].keyEquals("xy_in") &&
9296
3.70k
                curStep.paramValues[1].keyEquals("z_in") &&
9297
3.67k
                curStep.paramValues[2].keyEquals("xy_out") &&
9298
3.64k
                curStep.paramValues[3].keyEquals("z_out") &&
9299
3.64k
                prevStep.paramValues[2].value == curStep.paramValues[0].value &&
9300
2.97k
                curStep.paramValues[1].value == curStep.paramValues[3].value) {
9301
1.79k
                const std::string xy_in(prevStep.paramValues[0].value);
9302
1.79k
                const std::string z_in(prevStep.paramValues[1].value);
9303
1.79k
                const std::string xy_out(curStep.paramValues[2].value);
9304
1.79k
                const std::string z_out(prevStep.paramValues[3].value);
9305
9306
1.79k
                iterCur->paramValues.clear();
9307
1.79k
                iterCur->paramValues.emplace_back(
9308
1.79k
                    Step::KeyValue("xy_in", xy_in));
9309
1.79k
                iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in));
9310
1.79k
                iterCur->paramValues.emplace_back(
9311
1.79k
                    Step::KeyValue("xy_out", xy_out));
9312
1.79k
                iterCur->paramValues.emplace_back(
9313
1.79k
                    Step::KeyValue("z_out", z_out));
9314
9315
1.79k
                deletePrevIter();
9316
1.79k
                continue;
9317
1.79k
            }
9318
9319
            // clang-format off
9320
            // Variant of above
9321
            // +step +proj=unitconvert +xy_in=X1 +z_in=Z1 +xy_out=X2 +z_out=Z1
9322
            // +step +proj=unitconvert +xy_in=X2 +z_in=Z2 +xy_out=X3 +z_out=Z3
9323
            // ==> +step +proj=unitconvert +xy_in=X1 +z_in=Z2 +xy_out=X3 +z_out=Z3
9324
            // clang-format on
9325
3.13M
            if (prevStep.name == "unitconvert" &&
9326
564k
                curStep.name == "unitconvert" && !prevStep.inverted &&
9327
9.35k
                !curStep.inverted && prevStep.paramValues.size() == 4 &&
9328
3.87k
                curStep.paramValues.size() == 4 &&
9329
2.68k
                prevStep.paramValues[0].keyEquals("xy_in") &&
9330
2.39k
                prevStep.paramValues[1].keyEquals("z_in") &&
9331
2.18k
                prevStep.paramValues[2].keyEquals("xy_out") &&
9332
2.12k
                prevStep.paramValues[3].keyEquals("z_out") &&
9333
2.01k
                curStep.paramValues[0].keyEquals("xy_in") &&
9334
1.91k
                curStep.paramValues[1].keyEquals("z_in") &&
9335
1.87k
                curStep.paramValues[2].keyEquals("xy_out") &&
9336
1.85k
                curStep.paramValues[3].keyEquals("z_out") &&
9337
1.85k
                prevStep.paramValues[1].value ==
9338
1.85k
                    prevStep.paramValues[3].value &&
9339
1.59k
                curStep.paramValues[0].value == prevStep.paramValues[2].value) {
9340
1.05k
                const std::string xy_in(prevStep.paramValues[0].value);
9341
1.05k
                const std::string z_in(curStep.paramValues[1].value);
9342
1.05k
                const std::string xy_out(curStep.paramValues[2].value);
9343
1.05k
                const std::string z_out(curStep.paramValues[3].value);
9344
9345
1.05k
                iterCur->paramValues.clear();
9346
1.05k
                iterCur->paramValues.emplace_back(
9347
1.05k
                    Step::KeyValue("xy_in", xy_in));
9348
1.05k
                iterCur->paramValues.emplace_back(Step::KeyValue("z_in", z_in));
9349
1.05k
                iterCur->paramValues.emplace_back(
9350
1.05k
                    Step::KeyValue("xy_out", xy_out));
9351
1.05k
                iterCur->paramValues.emplace_back(
9352
1.05k
                    Step::KeyValue("z_out", z_out));
9353
9354
1.05k
                deletePrevIter();
9355
1.05k
                continue;
9356
1.05k
            }
9357
9358
            // unitconvert (1), axisswap order=2,1, unitconvert(2)  ==>
9359
            // axisswap order=2,1, unitconvert (1), unitconvert(2) which
9360
            // will get further optimized by previous case
9361
3.13M
            if (std::next(iterCur) != steps.end() &&
9362
2.89M
                prevStep.name == "unitconvert" && curStep.name == "axisswap" &&
9363
307k
                curStepParamCount == 1 &&
9364
307k
                curStep.paramValues[0].equals("order", "2,1")) {
9365
297k
                auto iterNext = std::next(iterCur);
9366
297k
                auto &nextStep = *iterNext;
9367
297k
                if (nextStep.name == "unitconvert") {
9368
2.41k
                    std::swap(*iterPrev, *iterCur);
9369
2.41k
                    ++iterCur;
9370
2.41k
                    continue;
9371
2.41k
                }
9372
297k
            }
9373
9374
            // axisswap order=2,1 followed by itself is a no-op
9375
3.13M
            if (curStep.name == "axisswap" && prevStep.name == "axisswap" &&
9376
338k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9377
337k
                curStep.paramValues[0].equals("order", "2,1") &&
9378
334k
                prevStep.paramValues[0].equals("order", "2,1")) {
9379
334k
                deletePrevAndCurIter();
9380
334k
                continue;
9381
334k
            }
9382
9383
            // axisswap order=2,-1 followed by axisswap order=-2,1 is a no-op
9384
2.79M
            if (curStep.name == "axisswap" && prevStep.name == "axisswap" &&
9385
3.86k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9386
3.63k
                !prevStep.inverted &&
9387
3.45k
                prevStep.paramValues[0].equals("order", "2,-1") &&
9388
267
                !curStep.inverted &&
9389
267
                curStep.paramValues[0].equals("order", "-2,1")) {
9390
267
                deletePrevAndCurIter();
9391
267
                continue;
9392
267
            }
9393
9394
            // axisswap order=2,-1 followed by axisswap order=1,-2 is
9395
            // equivalent to axisswap order=2,1
9396
2.79M
            if (curStep.name == "axisswap" && prevStep.name == "axisswap" &&
9397
3.59k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9398
3.36k
                !prevStep.inverted &&
9399
3.18k
                prevStep.paramValues[0].equals("order", "2,-1") &&
9400
0
                !curStep.inverted &&
9401
0
                curStep.paramValues[0].equals("order", "1,-2")) {
9402
0
                prevStep.inverted = false;
9403
0
                prevStep.paramValues[0] = Step::KeyValue("order", "2,1");
9404
                // Delete this iter
9405
0
                iterCur = steps.erase(iterCur);
9406
0
                continue;
9407
0
            }
9408
9409
            // axisswap order=2,1 followed by axisswap order=2,-1 is
9410
            // equivalent to axisswap order=1,-2
9411
            // Same for axisswap order=-2,1 followed by axisswap order=2,1
9412
2.79M
            if (curStep.name == "axisswap" && prevStep.name == "axisswap" &&
9413
3.59k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9414
3.36k
                ((prevStep.paramValues[0].equals("order", "2,1") &&
9415
13
                  !curStep.inverted &&
9416
13
                  curStep.paramValues[0].equals("order", "2,-1")) ||
9417
3.36k
                 (prevStep.paramValues[0].equals("order", "-2,1") &&
9418
175
                  !prevStep.inverted &&
9419
173
                  curStep.paramValues[0].equals("order", "2,1")))) {
9420
9421
16
                prevStep.inverted = false;
9422
16
                prevStep.paramValues[0] = Step::KeyValue("order", "1,-2");
9423
                // Delete this iter
9424
16
                iterCur = steps.erase(iterCur);
9425
16
                continue;
9426
16
            }
9427
9428
            // axisswap order=2,1, unitconvert, axisswap order=2,1 -> can
9429
            // suppress axisswap
9430
2.79M
            if (std::next(iterCur) != steps.end() &&
9431
2.58M
                prevStep.name == "axisswap" && curStep.name == "unitconvert" &&
9432
66.9k
                prevStepParamCount == 1 &&
9433
66.7k
                prevStep.paramValues[0].equals("order", "2,1")) {
9434
53.0k
                auto iterNext = std::next(iterCur);
9435
53.0k
                auto &nextStep = *iterNext;
9436
53.0k
                if (nextStep.name == "axisswap" &&
9437
1.79k
                    nextStep.paramValues.size() == 1 &&
9438
1.79k
                    nextStep.paramValues[0].equals("order", "2,1")) {
9439
1.79k
                    steps.erase(iterPrev);
9440
1.79k
                    steps.erase(iterNext);
9441
                    // Coverity complains about invalid usage of iterCur
9442
                    // due to the above erase(iterNext). To the best of our
9443
                    // understanding, this is a false-positive.
9444
                    // coverity[use_iterator]
9445
1.79k
                    if (iterCur != steps.begin())
9446
1.54k
                        iterCur = std::prev(iterCur);
9447
1.79k
                    if (iterCur == steps.begin())
9448
245
                        ++iterCur;
9449
1.79k
                    continue;
9450
1.79k
                }
9451
53.0k
            }
9452
9453
            // "+proj=set +v_4=X" followed by "+proj=set +v_4=X +omit_fwd"
9454
            // can be optimized as "+proj=set +v_4=X"
9455
2.79M
            if (curStep.name == "set" && prevStep.name == "set" &&
9456
9.20k
                !curStep.inverted && !prevStep.inverted &&
9457
9.20k
                curStepParamCount == 2 && prevStepParamCount == 1 &&
9458
0
                curStep.paramValues[0].keyEquals("v_4") &&
9459
0
                prevStep.paramValues[0].keyEquals("v_4") &&
9460
0
                curStep.paramValues[1].keyEquals("omit_fwd") &&
9461
0
                curStep.paramValues[0].value == prevStep.paramValues[0].value) {
9462
9463
0
                iterCur = steps.erase(iterCur);
9464
0
                continue;
9465
0
            }
9466
9467
            // "+proj=set +v_4=X +omit_inv" followed by "+proj=set +v_4=X"
9468
            // can be optimized as "+proj=set +v_4=X"
9469
2.79M
            if (curStep.name == "set" && prevStep.name == "set" &&
9470
9.20k
                !curStep.inverted && !prevStep.inverted &&
9471
9.20k
                curStepParamCount == 1 && prevStepParamCount == 2 &&
9472
0
                curStep.paramValues[0].keyEquals("v_4") &&
9473
0
                prevStep.paramValues[0].keyEquals("v_4") &&
9474
0
                prevStep.paramValues[1].keyEquals("omit_inv") &&
9475
0
                curStep.paramValues[0].value == prevStep.paramValues[0].value) {
9476
9477
0
                deletePrevIter();
9478
0
                continue;
9479
0
            }
9480
9481
            // for practical purposes WGS84 and GRS80 ellipsoids are
9482
            // equivalents (cartesian transform between both lead to differences
9483
            // of the order of 1e-14 deg..).
9484
            // No need to do a cart roundtrip for that...
9485
            // and actually IGNF uses the GRS80 definition for the WGS84 datum
9486
2.79M
            if (curStep.name == "cart" && prevStep.name == "cart" &&
9487
35.7k
                curStep.inverted == !prevStep.inverted &&
9488
35.7k
                curStepParamCount == 1 && prevStepParamCount == 1 &&
9489
35.4k
                ((curStep.paramValues[0].equals("ellps", "WGS84") &&
9490
15.5k
                  prevStep.paramValues[0].equals("ellps", "GRS80")) ||
9491
28.2k
                 (curStep.paramValues[0].equals("ellps", "GRS80") &&
9492
7.98k
                  prevStep.paramValues[0].equals("ellps", "WGS84")))) {
9493
7.98k
                deletePrevAndCurIter();
9494
7.98k
                continue;
9495
7.98k
            }
9496
9497
2.78M
            if (curStep.name == "helmert" && prevStep.name == "helmert" &&
9498
16.7k
                curStepParamCount == 3 &&
9499
13.8k
                curStepParamCount == prevStepParamCount) {
9500
12.7k
                std::map<std::string, double> leftParamsMap;
9501
12.7k
                std::map<std::string, double> rightParamsMap;
9502
12.7k
                try {
9503
37.8k
                    for (const auto &kv : prevStep.paramValues) {
9504
37.8k
                        leftParamsMap[kv.key] = c_locale_stod(kv.value);
9505
37.8k
                    }
9506
37.4k
                    for (const auto &kv : curStep.paramValues) {
9507
37.4k
                        rightParamsMap[kv.key] = c_locale_stod(kv.value);
9508
37.4k
                    }
9509
12.7k
                } catch (const std::invalid_argument &) {
9510
316
                    break;
9511
316
                }
9512
12.4k
                const std::string x("x");
9513
12.4k
                const std::string y("y");
9514
12.4k
                const std::string z("z");
9515
12.4k
                if (leftParamsMap.find(x) != leftParamsMap.end() &&
9516
12.3k
                    leftParamsMap.find(y) != leftParamsMap.end() &&
9517
12.2k
                    leftParamsMap.find(z) != leftParamsMap.end() &&
9518
11.8k
                    rightParamsMap.find(x) != rightParamsMap.end() &&
9519
11.8k
                    rightParamsMap.find(y) != rightParamsMap.end() &&
9520
11.7k
                    rightParamsMap.find(z) != rightParamsMap.end()) {
9521
9522
11.7k
                    const double signLeft = prevStep.inverted ? -1 : 1;
9523
11.7k
                    const double signRight = curStep.inverted ? -1 : 1;
9524
11.7k
                    const double xSum = signLeft * leftParamsMap[x] +
9525
11.7k
                                        signRight * rightParamsMap[x];
9526
11.7k
                    const double ySum = signLeft * leftParamsMap[y] +
9527
11.7k
                                        signRight * rightParamsMap[y];
9528
11.7k
                    const double zSum = signLeft * leftParamsMap[z] +
9529
11.7k
                                        signRight * rightParamsMap[z];
9530
11.7k
                    if (xSum == 0.0 && ySum == 0.0 && zSum == 0.0) {
9531
1.24k
                        deletePrevAndCurIter();
9532
10.4k
                    } else {
9533
10.4k
                        prevStep.inverted = false;
9534
10.4k
                        prevStep.paramValues[0] =
9535
10.4k
                            Step::KeyValue("x", internal::toString(xSum));
9536
10.4k
                        prevStep.paramValues[1] =
9537
10.4k
                            Step::KeyValue("y", internal::toString(ySum));
9538
10.4k
                        prevStep.paramValues[2] =
9539
10.4k
                            Step::KeyValue("z", internal::toString(zSum));
9540
9541
                        // Delete this iter
9542
10.4k
                        iterCur = steps.erase(iterCur);
9543
10.4k
                    }
9544
11.7k
                    continue;
9545
11.7k
                }
9546
12.4k
            }
9547
9548
            // Helmert followed by its inverse is a no-op
9549
2.77M
            if (curStep.name == "helmert" && prevStep.name == "helmert" &&
9550
4.66k
                (curStep.inverted == prevStep.inverted) &&
9551
3.14k
                curStepParamCount == prevStepParamCount) {
9552
1.18k
                std::set<std::string> leftParamsSet;
9553
1.18k
                std::set<std::string> rightParamsSet;
9554
1.18k
                std::map<std::string, std::string> leftParamsMap;
9555
1.18k
                std::map<std::string, std::string> rightParamsMap;
9556
4.52k
                for (const auto &kv : prevStep.paramValues) {
9557
4.52k
                    leftParamsSet.insert(kv.key);
9558
4.52k
                    leftParamsMap[kv.key] = kv.value;
9559
4.52k
                }
9560
4.52k
                for (const auto &kv : curStep.paramValues) {
9561
4.52k
                    rightParamsSet.insert(kv.key);
9562
4.52k
                    rightParamsMap[kv.key] = kv.value;
9563
4.52k
                }
9564
1.18k
                if (leftParamsSet == rightParamsSet) {
9565
385
                    bool doErase = true;
9566
385
                    try {
9567
815
                        for (const auto &param : leftParamsSet) {
9568
815
                            if (param == "convention" || param == "t_epoch" ||
9569
605
                                param == "t_obs") {
9570
210
                                if (leftParamsMap[param] !=
9571
210
                                    rightParamsMap[param]) {
9572
173
                                    doErase = false;
9573
173
                                    break;
9574
173
                                }
9575
605
                            } else if (c_locale_stod(leftParamsMap[param]) !=
9576
605
                                       -c_locale_stod(rightParamsMap[param])) {
9577
156
                                doErase = false;
9578
156
                                break;
9579
156
                            }
9580
815
                        }
9581
385
                    } catch (const std::invalid_argument &) {
9582
45
                        break;
9583
45
                    }
9584
340
                    if (doErase) {
9585
11
                        deletePrevAndCurIter();
9586
11
                        continue;
9587
11
                    }
9588
340
                }
9589
1.18k
            }
9590
9591
            // The following should be optimized as a no-op
9592
            // +step +proj=helmert +x=25 +y=-141 +z=-78.5 +rx=0 +ry=-0.35
9593
            // +rz=-0.736 +s=0 +convention=coordinate_frame
9594
            // +step +inv +proj=helmert +x=25 +y=-141 +z=-78.5 +rx=0 +ry=0.35
9595
            // +rz=0.736 +s=0 +convention=position_vector
9596
2.77M
            if (curStep.name == "helmert" && prevStep.name == "helmert" &&
9597
4.60k
                ((curStep.inverted && !prevStep.inverted) ||
9598
3.84k
                 (!curStep.inverted && prevStep.inverted)) &&
9599
1.51k
                curStepParamCount == prevStepParamCount) {
9600
836
                std::set<std::string> leftParamsSet;
9601
836
                std::set<std::string> rightParamsSet;
9602
836
                std::map<std::string, std::string> leftParamsMap;
9603
836
                std::map<std::string, std::string> rightParamsMap;
9604
9.70k
                for (const auto &kv : prevStep.paramValues) {
9605
9.70k
                    leftParamsSet.insert(kv.key);
9606
9.70k
                    leftParamsMap[kv.key] = kv.value;
9607
9.70k
                }
9608
9.70k
                for (const auto &kv : curStep.paramValues) {
9609
9.70k
                    rightParamsSet.insert(kv.key);
9610
9.70k
                    rightParamsMap[kv.key] = kv.value;
9611
9.70k
                }
9612
836
                if (leftParamsSet == rightParamsSet) {
9613
609
                    bool doErase = true;
9614
609
                    try {
9615
2.53k
                        for (const auto &param : leftParamsSet) {
9616
2.53k
                            if (param == "convention") {
9617
                                // Convention must be different
9618
403
                                if (leftParamsMap[param] ==
9619
403
                                    rightParamsMap[param]) {
9620
364
                                    doErase = false;
9621
364
                                    break;
9622
364
                                }
9623
2.13k
                            } else if (param == "rx" || param == "ry" ||
9624
1.94k
                                       param == "rz" || param == "drx" ||
9625
1.94k
                                       param == "dry" || param == "drz") {
9626
                                // Rotational parameters should have opposite
9627
                                // value
9628
186
                                if (c_locale_stod(leftParamsMap[param]) !=
9629
186
                                    -c_locale_stod(rightParamsMap[param])) {
9630
88
                                    doErase = false;
9631
88
                                    break;
9632
88
                                }
9633
1.94k
                            } else {
9634
                                // Non rotational parameters should have the
9635
                                // same value
9636
1.94k
                                if (leftParamsMap[param] !=
9637
1.94k
                                    rightParamsMap[param]) {
9638
42
                                    doErase = false;
9639
42
                                    break;
9640
42
                                }
9641
1.94k
                            }
9642
2.53k
                        }
9643
609
                    } catch (const std::invalid_argument &) {
9644
60
                        break;
9645
60
                    }
9646
549
                    if (doErase) {
9647
55
                        deletePrevAndCurIter();
9648
55
                        continue;
9649
55
                    }
9650
549
                }
9651
836
            }
9652
9653
            // Optimize patterns like Krovak (South West) to Krovak East North
9654
            // (also applies to Modified Krovak)
9655
            //   +step +inv +proj=krovak +axis=swu +lat_0=49.5
9656
            //   +lon_0=24.8333333333333
9657
            //     +alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel
9658
            //   +step +proj=krovak +lat_0=49.5 +lon_0=24.8333333333333
9659
            //     +alpha=30.2881397527778 +k=0.9999 +x_0=0 +y_0=0 +ellps=bessel
9660
            // as:
9661
            //   +step +proj=axisswap +order=-2,-1
9662
            // Also applies for the symmetrical case where +axis=swu is on the
9663
            // second step.
9664
2.77M
            if (curStep.inverted != prevStep.inverted &&
9665
1.20M
                curStep.name == prevStep.name &&
9666
86.7k
                ((curStepParamCount + 1 == prevStepParamCount &&
9667
883
                  prevStep.paramValues[0].equals("axis", "swu")) ||
9668
86.5k
                 (prevStepParamCount + 1 == curStepParamCount &&
9669
1.60k
                  curStep.paramValues[0].equals("axis", "swu")))) {
9670
369
                const auto &swStep = (curStepParamCount < prevStepParamCount)
9671
369
                                         ? prevStep
9672
369
                                         : curStep;
9673
369
                const auto &enStep = (curStepParamCount < prevStepParamCount)
9674
369
                                         ? curStep
9675
369
                                         : prevStep;
9676
                // Check if all remaining parameters (except leading axis=swu
9677
                // in swStep) are identical.
9678
369
                bool allSame = true;
9679
369
                for (size_t j = 0;
9680
403
                     j < std::min(curStepParamCount, prevStepParamCount); j++) {
9681
208
                    if (enStep.paramValues[j] != swStep.paramValues[j + 1]) {
9682
174
                        allSame = false;
9683
174
                        break;
9684
174
                    }
9685
208
                }
9686
369
                if (allSame) {
9687
195
                    iterCur->inverted = false;
9688
195
                    iterCur->name = "axisswap";
9689
195
                    iterCur->paramValues.clear();
9690
195
                    iterCur->paramValues.emplace_back(
9691
195
                        Step::KeyValue("order", "-2,-1"));
9692
9693
195
                    deletePrevIter();
9694
195
                    continue;
9695
195
                }
9696
369
            }
9697
9698
            // detect a step and its inverse
9699
2.77M
            if (curStep.inverted != prevStep.inverted &&
9700
1.20M
                curStep.name == prevStep.name &&
9701
86.5k
                curStepParamCount == prevStepParamCount) {
9702
76.3k
                bool allSame = true;
9703
137k
                for (size_t j = 0; j < curStepParamCount; j++) {
9704
98.7k
                    if (curStep.paramValues[j] != prevStep.paramValues[j]) {
9705
37.4k
                        allSame = false;
9706
37.4k
                        break;
9707
37.4k
                    }
9708
98.7k
                }
9709
76.3k
                if (allSame) {
9710
38.8k
                    deletePrevAndCurIter();
9711
38.8k
                    continue;
9712
38.8k
                }
9713
76.3k
            }
9714
9715
2.73M
            ++iterCur;
9716
2.73M
        }
9717
253k
    }
9718
9719
253k
    {
9720
253k
        auto iterCur = steps.begin();
9721
253k
        if (iterCur != steps.end()) {
9722
243k
            ++iterCur;
9723
243k
        }
9724
1.63M
        while (iterCur != steps.end()) {
9725
9726
1.38M
            assert(iterCur != steps.begin());
9727
1.38M
            auto iterPrev = std::prev(iterCur);
9728
1.38M
            auto &prevStep = *iterPrev;
9729
1.38M
            auto &curStep = *iterCur;
9730
9731
1.38M
            const auto curStepParamCount = curStep.paramValues.size();
9732
1.38M
            const auto prevStepParamCount = prevStep.paramValues.size();
9733
9734
            // +step +proj=hgridshift +grids=grid_A
9735
            // +step +proj=vgridshift [...] <== curStep
9736
            // +step +inv +proj=hgridshift +grids=grid_A
9737
            // ==>
9738
            // +step +proj=push +v_1 +v_2
9739
            // +step +proj=hgridshift +grids=grid_A +omit_inv
9740
            // +step +proj=vgridshift [...]
9741
            // +step +inv +proj=hgridshift +grids=grid_A +omit_fwd
9742
            // +step +proj=pop +v_1 +v_2
9743
1.38M
            if (std::next(iterCur) != steps.end() &&
9744
1.16M
                prevStep.name == "hgridshift" && prevStepParamCount == 1 &&
9745
8.88k
                curStep.name == "vgridshift") {
9746
2.07k
                auto iterNext = std::next(iterCur);
9747
2.07k
                auto &nextStep = *iterNext;
9748
2.07k
                if (nextStep.name == "hgridshift" &&
9749
660
                    nextStep.inverted != prevStep.inverted &&
9750
626
                    nextStep.paramValues.size() == 1 &&
9751
596
                    prevStep.paramValues[0] == nextStep.paramValues[0]) {
9752
436
                    Step pushStep;
9753
436
                    pushStep.name = "push";
9754
436
                    pushStep.paramValues.emplace_back("v_1");
9755
436
                    pushStep.paramValues.emplace_back("v_2");
9756
436
                    steps.insert(iterPrev, pushStep);
9757
9758
436
                    prevStep.paramValues.emplace_back("omit_inv");
9759
9760
436
                    nextStep.paramValues.emplace_back("omit_fwd");
9761
9762
436
                    Step popStep;
9763
436
                    popStep.name = "pop";
9764
436
                    popStep.paramValues.emplace_back("v_1");
9765
436
                    popStep.paramValues.emplace_back("v_2");
9766
436
                    steps.insert(std::next(iterNext), popStep);
9767
9768
436
                    continue;
9769
436
                }
9770
2.07k
            }
9771
9772
            // +step +proj=unitconvert +xy_in=rad +xy_out=deg
9773
            // +step +proj=axisswap +order=2,1
9774
            // +step +proj=push +v_1 +v_2
9775
            // +step +proj=axisswap +order=2,1
9776
            // +step +proj=unitconvert +xy_in=deg +xy_out=rad
9777
            // +step +proj=vgridshift ...
9778
            // +step +proj=unitconvert +xy_in=rad +xy_out=deg
9779
            // +step +proj=axisswap +order=2,1
9780
            // +step +proj=pop +v_1 +v_2
9781
            // ==>
9782
            // +step +proj=vgridshift ...
9783
            // +step +proj=unitconvert +xy_in=rad +xy_out=deg
9784
            // +step +proj=axisswap +order=2,1
9785
1.38M
            if (prevStep.name == "unitconvert" && prevStepParamCount == 2 &&
9786
174k
                prevStep.paramValues[0].equals("xy_in", "rad") &&
9787
36.3k
                prevStep.paramValues[1].equals("xy_out", "deg") &&
9788
36.3k
                curStep.name == "axisswap" && curStepParamCount == 1 &&
9789
22.9k
                curStep.paramValues[0].equals("order", "2,1")) {
9790
14.7k
                auto iterNext = std::next(iterCur);
9791
14.7k
                bool ok = false;
9792
14.7k
                if (iterNext != steps.end()) {
9793
1.90k
                    auto &nextStep = *iterNext;
9794
1.90k
                    if (nextStep.name == "push" &&
9795
100
                        nextStep.paramValues.size() == 2 &&
9796
0
                        nextStep.paramValues[0].keyEquals("v_1") &&
9797
0
                        nextStep.paramValues[1].keyEquals("v_2")) {
9798
0
                        ok = true;
9799
0
                        iterNext = std::next(iterNext);
9800
0
                    }
9801
1.90k
                }
9802
14.7k
                ok &= iterNext != steps.end();
9803
14.7k
                if (ok) {
9804
0
                    ok = false;
9805
0
                    auto &nextStep = *iterNext;
9806
0
                    if (nextStep.name == "axisswap" &&
9807
0
                        nextStep.paramValues.size() == 1 &&
9808
0
                        nextStep.paramValues[0].equals("order", "2,1")) {
9809
0
                        ok = true;
9810
0
                        iterNext = std::next(iterNext);
9811
0
                    }
9812
0
                }
9813
14.7k
                ok &= iterNext != steps.end();
9814
14.7k
                if (ok) {
9815
0
                    ok = false;
9816
0
                    auto &nextStep = *iterNext;
9817
0
                    if (nextStep.name == "unitconvert" &&
9818
0
                        nextStep.paramValues.size() == 2 &&
9819
0
                        nextStep.paramValues[0].equals("xy_in", "deg") &&
9820
0
                        nextStep.paramValues[1].equals("xy_out", "rad")) {
9821
0
                        ok = true;
9822
0
                        iterNext = std::next(iterNext);
9823
0
                    }
9824
0
                }
9825
14.7k
                auto iterVgridshift = iterNext;
9826
14.7k
                ok &= iterNext != steps.end();
9827
14.7k
                if (ok) {
9828
0
                    ok = false;
9829
0
                    auto &nextStep = *iterNext;
9830
0
                    if (nextStep.name == "vgridshift") {
9831
0
                        ok = true;
9832
0
                        iterNext = std::next(iterNext);
9833
0
                    }
9834
0
                }
9835
14.7k
                ok &= iterNext != steps.end();
9836
14.7k
                if (ok) {
9837
0
                    ok = false;
9838
0
                    auto &nextStep = *iterNext;
9839
0
                    if (nextStep.name == "unitconvert" &&
9840
0
                        nextStep.paramValues.size() == 2 &&
9841
0
                        nextStep.paramValues[0].equals("xy_in", "rad") &&
9842
0
                        nextStep.paramValues[1].equals("xy_out", "deg")) {
9843
0
                        ok = true;
9844
0
                        iterNext = std::next(iterNext);
9845
0
                    }
9846
0
                }
9847
14.7k
                ok &= iterNext != steps.end();
9848
14.7k
                if (ok) {
9849
0
                    ok = false;
9850
0
                    auto &nextStep = *iterNext;
9851
0
                    if (nextStep.name == "axisswap" &&
9852
0
                        nextStep.paramValues.size() == 1 &&
9853
0
                        nextStep.paramValues[0].equals("order", "2,1")) {
9854
0
                        ok = true;
9855
0
                        iterNext = std::next(iterNext);
9856
0
                    }
9857
0
                }
9858
14.7k
                ok &= iterNext != steps.end();
9859
14.7k
                if (ok) {
9860
0
                    ok = false;
9861
0
                    auto &nextStep = *iterNext;
9862
0
                    if (nextStep.name == "pop" &&
9863
0
                        nextStep.paramValues.size() == 2 &&
9864
0
                        nextStep.paramValues[0].keyEquals("v_1") &&
9865
0
                        nextStep.paramValues[1].keyEquals("v_2")) {
9866
0
                        ok = true;
9867
                        // iterNext = std::next(iterNext);
9868
0
                    }
9869
0
                }
9870
14.7k
                if (ok) {
9871
0
                    steps.erase(iterPrev, iterVgridshift);
9872
0
                    steps.erase(iterNext, std::next(iterNext));
9873
0
                    iterPrev = std::prev(iterVgridshift);
9874
0
                    iterCur = iterVgridshift;
9875
0
                    continue;
9876
0
                }
9877
14.7k
            }
9878
9879
            // +step +proj=axisswap +order=2,1
9880
            // +step +proj=unitconvert +xy_in=deg +xy_out=rad
9881
            // +step +proj=vgridshift ...
9882
            // +step +proj=unitconvert +xy_in=rad +xy_out=deg
9883
            // +step +proj=axisswap +order=2,1
9884
            // +step +proj=push +v_1 +v_2
9885
            // +step +proj=axisswap +order=2,1
9886
            // +step +proj=unitconvert +xy_in=deg +xy_out=rad
9887
            // ==>
9888
            // +step +proj=push +v_1 +v_2
9889
            // +step +proj=axisswap +order=2,1
9890
            // +step +proj=unitconvert +xy_in=deg +xy_out=rad
9891
            // +step +proj=vgridshift ...
9892
9893
1.38M
            if (prevStep.name == "axisswap" && prevStepParamCount == 1 &&
9894
49.0k
                prevStep.paramValues[0].equals("order", "2,1") &&
9895
32.1k
                curStep.name == "unitconvert" && curStepParamCount == 2 &&
9896
27.2k
                !curStep.inverted &&
9897
27.2k
                curStep.paramValues[0].equals("xy_in", "deg") &&
9898
26.6k
                curStep.paramValues[1].equals("xy_out", "rad")) {
9899
26.6k
                auto iterNext = std::next(iterCur);
9900
26.6k
                bool ok = false;
9901
26.6k
                auto iterVgridshift = iterNext;
9902
26.6k
                if (iterNext != steps.end()) {
9903
26.6k
                    auto &nextStep = *iterNext;
9904
26.6k
                    if (nextStep.name == "vgridshift") {
9905
2.28k
                        ok = true;
9906
2.28k
                        iterNext = std::next(iterNext);
9907
2.28k
                    }
9908
26.6k
                }
9909
26.6k
                ok &= iterNext != steps.end();
9910
26.6k
                if (ok) {
9911
2.27k
                    ok = false;
9912
2.27k
                    auto &nextStep = *iterNext;
9913
2.27k
                    if (nextStep.name == "unitconvert" && !nextStep.inverted &&
9914
780
                        nextStep.paramValues.size() == 2 &&
9915
734
                        nextStep.paramValues[0].equals("xy_in", "rad") &&
9916
442
                        nextStep.paramValues[1].equals("xy_out", "deg")) {
9917
442
                        ok = true;
9918
442
                        iterNext = std::next(iterNext);
9919
442
                    }
9920
2.27k
                }
9921
26.6k
                ok &= iterNext != steps.end();
9922
26.6k
                if (ok) {
9923
108
                    ok = false;
9924
108
                    auto &nextStep = *iterNext;
9925
108
                    if (nextStep.name == "axisswap" &&
9926
99
                        nextStep.paramValues.size() == 1 &&
9927
99
                        nextStep.paramValues[0].equals("order", "2,1")) {
9928
96
                        ok = true;
9929
96
                        iterNext = std::next(iterNext);
9930
96
                    }
9931
108
                }
9932
26.6k
                auto iterPush = iterNext;
9933
26.6k
                ok &= iterNext != steps.end();
9934
26.6k
                if (ok) {
9935
67
                    ok = false;
9936
67
                    auto &nextStep = *iterNext;
9937
67
                    if (nextStep.name == "push" &&
9938
2
                        nextStep.paramValues.size() == 2 &&
9939
0
                        nextStep.paramValues[0].keyEquals("v_1") &&
9940
0
                        nextStep.paramValues[1].keyEquals("v_2")) {
9941
0
                        ok = true;
9942
0
                        iterNext = std::next(iterNext);
9943
0
                    }
9944
67
                }
9945
26.6k
                ok &= iterNext != steps.end();
9946
26.6k
                if (ok) {
9947
0
                    ok = false;
9948
0
                    auto &nextStep = *iterNext;
9949
0
                    if (nextStep.name == "axisswap" &&
9950
0
                        nextStep.paramValues.size() == 1 &&
9951
0
                        nextStep.paramValues[0].equals("order", "2,1")) {
9952
0
                        ok = true;
9953
0
                        iterNext = std::next(iterNext);
9954
0
                    }
9955
0
                }
9956
26.6k
                ok &= iterNext != steps.end();
9957
26.6k
                if (ok) {
9958
0
                    ok = false;
9959
0
                    auto &nextStep = *iterNext;
9960
0
                    if (nextStep.name == "unitconvert" &&
9961
0
                        nextStep.paramValues.size() == 2 &&
9962
0
                        !nextStep.inverted &&
9963
0
                        nextStep.paramValues[0].equals("xy_in", "deg") &&
9964
0
                        nextStep.paramValues[1].equals("xy_out", "rad")) {
9965
0
                        ok = true;
9966
                        // iterNext = std::next(iterNext);
9967
0
                    }
9968
0
                }
9969
9970
26.6k
                if (ok) {
9971
0
                    Step stepVgridshift(*iterVgridshift);
9972
0
                    steps.erase(iterPrev, iterPush);
9973
0
                    steps.insert(std::next(iterNext),
9974
0
                                 std::move(stepVgridshift));
9975
0
                    iterPrev = iterPush;
9976
0
                    iterCur = std::next(iterPush);
9977
0
                    continue;
9978
0
                }
9979
26.6k
            }
9980
9981
1.38M
            ++iterCur;
9982
1.38M
        }
9983
253k
    }
9984
9985
253k
    {
9986
253k
        auto iterCur = steps.begin();
9987
253k
        if (iterCur != steps.end()) {
9988
243k
            ++iterCur;
9989
243k
        }
9990
1.63M
        while (iterCur != steps.end()) {
9991
9992
1.38M
            assert(iterCur != steps.begin());
9993
1.38M
            auto iterPrev = std::prev(iterCur);
9994
1.38M
            auto &prevStep = *iterPrev;
9995
1.38M
            auto &curStep = *iterCur;
9996
9997
1.38M
            const auto curStepParamCount = curStep.paramValues.size();
9998
1.38M
            const auto prevStepParamCount = prevStep.paramValues.size();
9999
10000
1.38M
            const auto deletePrevAndCurIter = [&steps, &iterPrev, &iterCur]() {
10001
212
                iterCur = steps.erase(iterPrev, std::next(iterCur));
10002
212
                if (iterCur != steps.begin())
10003
212
                    iterCur = std::prev(iterCur);
10004
212
                if (iterCur == steps.begin() && iterCur != steps.end())
10005
54
                    ++iterCur;
10006
212
            };
10007
10008
            // axisswap order=2,1 followed by itself is a no-op
10009
1.38M
            if (curStep.name == "axisswap" && prevStep.name == "axisswap" &&
10010
632
                curStepParamCount == 1 && prevStepParamCount == 1 &&
10011
422
                curStep.paramValues[0].equals("order", "2,1") &&
10012
36
                prevStep.paramValues[0].equals("order", "2,1")) {
10013
23
                deletePrevAndCurIter();
10014
23
                continue;
10015
23
            }
10016
10017
            // detect a step and its inverse
10018
1.38M
            if (curStep.inverted != prevStep.inverted &&
10019
602k
                curStep.name == prevStep.name &&
10020
25.9k
                curStepParamCount == prevStepParamCount) {
10021
18.4k
                bool allSame = true;
10022
21.6k
                for (size_t j = 0; j < curStepParamCount; j++) {
10023
21.5k
                    if (curStep.paramValues[j] != prevStep.paramValues[j]) {
10024
18.2k
                        allSame = false;
10025
18.2k
                        break;
10026
18.2k
                    }
10027
21.5k
                }
10028
18.4k
                if (allSame) {
10029
189
                    deletePrevAndCurIter();
10030
189
                    continue;
10031
189
                }
10032
18.4k
            }
10033
10034
1.38M
            ++iterCur;
10035
1.38M
        }
10036
253k
    }
10037
10038
253k
    if (steps.size() > 1 ||
10039
40.0k
        (steps.size() == 1 &&
10040
30.7k
         (steps.front().inverted || steps.front().hasKey("omit_inv") ||
10041
28.6k
          steps.front().hasKey("omit_fwd") ||
10042
215k
          !d->globalParamValues_.empty()))) {
10043
215k
        d->appendToResult("+proj=pipeline");
10044
10045
650k
        for (const auto &paramValue : d->globalParamValues_) {
10046
650k
            d->appendToResult("+");
10047
650k
            d->result_ += paramValue.key;
10048
650k
            if (!paramValue.value.empty()) {
10049
360k
                d->result_ += '=';
10050
360k
                d->result_ +=
10051
360k
                    pj_double_quote_string_param_if_needed(paramValue.value);
10052
360k
            }
10053
650k
        }
10054
10055
215k
        if (d->multiLine_) {
10056
0
            d->indentLevel_++;
10057
0
        }
10058
215k
    }
10059
10060
1.62M
    for (const auto &step : steps) {
10061
1.62M
        std::string curLine;
10062
1.62M
        if (!d->result_.empty()) {
10063
1.59M
            if (d->multiLine_) {
10064
0
                curLine = std::string(static_cast<size_t>(d->indentLevel_) *
10065
0
                                          d->indentWidth_,
10066
0
                                      ' ');
10067
0
                curLine += "+step";
10068
1.59M
            } else {
10069
1.59M
                curLine = " +step";
10070
1.59M
            }
10071
1.59M
        }
10072
1.62M
        if (step.inverted) {
10073
489k
            curLine += " +inv";
10074
489k
        }
10075
1.62M
        if (!step.name.empty()) {
10076
1.60M
            if (!curLine.empty())
10077
1.57M
                curLine += ' ';
10078
1.60M
            curLine += step.isInit ? "+init=" : "+proj=";
10079
1.60M
            curLine += step.name;
10080
1.60M
        }
10081
4.93M
        for (const auto &paramValue : step.paramValues) {
10082
4.93M
            std::string newKV = "+";
10083
4.93M
            newKV += paramValue.key;
10084
4.93M
            if (!paramValue.value.empty()) {
10085
3.12M
                newKV += '=';
10086
3.12M
                newKV +=
10087
3.12M
                    pj_double_quote_string_param_if_needed(paramValue.value);
10088
3.12M
            }
10089
4.93M
            if (d->maxLineLength_ > 0 && d->multiLine_ &&
10090
0
                curLine.size() + newKV.size() >
10091
0
                    static_cast<size_t>(d->maxLineLength_)) {
10092
0
                if (!d->result_.empty())
10093
0
                    d->result_ += '\n';
10094
0
                d->result_ += curLine;
10095
0
                curLine = std::string(static_cast<size_t>(d->indentLevel_) *
10096
0
                                              d->indentWidth_ +
10097
0
                                          strlen("+step "),
10098
0
                                      ' ');
10099
4.93M
            } else {
10100
4.93M
                if (!curLine.empty())
10101
4.93M
                    curLine += ' ';
10102
4.93M
            }
10103
4.93M
            curLine += newKV;
10104
4.93M
        }
10105
1.62M
        if (d->multiLine_ && !d->result_.empty())
10106
0
            d->result_ += '\n';
10107
1.62M
        d->result_ += curLine;
10108
1.62M
    }
10109
10110
253k
    if (d->result_.empty()) {
10111
9.34k
        d->appendToResult("+proj=noop");
10112
9.34k
    }
10113
10114
253k
    return d->result_;
10115
253k
}
10116
10117
// ---------------------------------------------------------------------------
10118
10119
//! @cond Doxygen_Suppress
10120
10121
621k
PROJStringFormatter::Convention PROJStringFormatter::convention() const {
10122
621k
    return d->convention_;
10123
621k
}
10124
10125
// ---------------------------------------------------------------------------
10126
10127
// Return the number of steps in the pipeline.
10128
// Note: this value will change after calling toString() that will run
10129
// optimizations.
10130
36.6k
size_t PROJStringFormatter::getStepCount() const { return d->steps_.size(); }
10131
10132
// ---------------------------------------------------------------------------
10133
10134
8.37k
bool PROJStringFormatter::getUseApproxTMerc() const {
10135
8.37k
    return d->useApproxTMerc_;
10136
8.37k
}
10137
10138
// ---------------------------------------------------------------------------
10139
10140
388k
void PROJStringFormatter::setCoordinateOperationOptimizations(bool enable) {
10141
388k
    d->coordOperationOptimizations_ = enable;
10142
388k
}
10143
10144
// ---------------------------------------------------------------------------
10145
10146
875k
void PROJStringFormatter::Private::appendToResult(const char *str) {
10147
875k
    if (!result_.empty()) {
10148
650k
        result_ += ' ';
10149
650k
    }
10150
875k
    result_ += str;
10151
875k
}
10152
10153
// ---------------------------------------------------------------------------
10154
10155
static void
10156
PROJStringSyntaxParser(const std::string &projString, std::vector<Step> &steps,
10157
                       std::vector<Step::KeyValue> &globalParamValues,
10158
295k
                       std::string &title) {
10159
295k
    std::vector<std::string> tokens;
10160
10161
295k
    bool hasProj = false;
10162
295k
    bool hasInit = false;
10163
295k
    bool hasPipeline = false;
10164
10165
295k
    std::string projStringModified(projString);
10166
10167
    // Special case for "+title=several words +foo=bar"
10168
295k
    if (starts_with(projStringModified, "+title=") &&
10169
157
        projStringModified.size() > 7 && projStringModified[7] != '"') {
10170
152
        const auto plusPos = projStringModified.find(" +", 1);
10171
152
        const auto spacePos = projStringModified.find(' ');
10172
152
        if (plusPos != std::string::npos && spacePos != std::string::npos &&
10173
123
            spacePos < plusPos) {
10174
100
            std::string tmp("+title=");
10175
100
            tmp += pj_double_quote_string_param_if_needed(
10176
100
                projStringModified.substr(7, plusPos - 7));
10177
100
            tmp += projStringModified.substr(plusPos);
10178
100
            projStringModified = std::move(tmp);
10179
100
        }
10180
152
    }
10181
10182
295k
    size_t argc = pj_trim_argc(&projStringModified[0]);
10183
295k
    char **argv = pj_trim_argv(argc, &projStringModified[0]);
10184
9.69M
    for (size_t i = 0; i < argc; i++) {
10185
9.40M
        std::string token(argv[i]);
10186
9.40M
        if (!hasPipeline && token == "proj=pipeline") {
10187
239k
            hasPipeline = true;
10188
9.16M
        } else if (!hasProj && starts_with(token, "proj=")) {
10189
286k
            hasProj = true;
10190
8.87M
        } else if (!hasInit && starts_with(token, "init=")) {
10191
6.02k
            hasInit = true;
10192
6.02k
        }
10193
9.40M
        tokens.emplace_back(token);
10194
9.40M
    }
10195
295k
    free(argv);
10196
10197
295k
    if (!hasPipeline) {
10198
55.7k
        if (hasProj || hasInit) {
10199
48.3k
            steps.push_back(Step());
10200
48.3k
        }
10201
10202
698k
        for (auto &word : tokens) {
10203
698k
            if (starts_with(word, "proj=") && !hasInit &&
10204
74.9k
                steps.back().name.empty()) {
10205
47.0k
                assert(hasProj);
10206
47.0k
                auto stepName = word.substr(strlen("proj="));
10207
47.0k
                steps.back().name = std::move(stepName);
10208
651k
            } else if (starts_with(word, "init=")) {
10209
1.49k
                assert(hasInit);
10210
1.49k
                auto initName = word.substr(strlen("init="));
10211
1.49k
                steps.back().name = std::move(initName);
10212
1.49k
                steps.back().isInit = true;
10213
650k
            } else if (word == "inv") {
10214
4.80k
                if (!steps.empty()) {
10215
4.80k
                    steps.back().inverted = true;
10216
4.80k
                }
10217
645k
            } else if (starts_with(word, "title=")) {
10218
1.09k
                title = word.substr(strlen("title="));
10219
644k
            } else if (word != "step") {
10220
632k
                const auto pos = word.find('=');
10221
632k
                const auto key = word.substr(0, pos);
10222
10223
632k
                Step::KeyValue pair(
10224
632k
                    (pos != std::string::npos)
10225
632k
                        ? Step::KeyValue(key, word.substr(pos + 1))
10226
632k
                        : Step::KeyValue(key));
10227
632k
                if (steps.empty()) {
10228
332
                    globalParamValues.push_back(std::move(pair));
10229
632k
                } else {
10230
632k
                    steps.back().paramValues.push_back(std::move(pair));
10231
632k
                }
10232
632k
            }
10233
698k
        }
10234
55.7k
        return;
10235
55.7k
    }
10236
10237
239k
    bool inPipeline = false;
10238
239k
    bool invGlobal = false;
10239
8.70M
    for (auto &word : tokens) {
10240
8.70M
        if (word == "proj=pipeline") {
10241
239k
            if (inPipeline) {
10242
43
                throw ParsingException("nested pipeline not supported");
10243
43
            }
10244
239k
            inPipeline = true;
10245
8.46M
        } else if (word == "step") {
10246
1.23M
            if (!inPipeline) {
10247
11
                throw ParsingException("+step found outside pipeline");
10248
11
            }
10249
1.23M
            steps.push_back(Step());
10250
7.22M
        } else if (word == "inv") {
10251
360k
            if (steps.empty()) {
10252
4.04k
                invGlobal = true;
10253
356k
            } else {
10254
356k
                steps.back().inverted = true;
10255
356k
            }
10256
6.86M
        } else if (inPipeline && !steps.empty() && starts_with(word, "proj=") &&
10257
1.36M
                   steps.back().name.empty()) {
10258
1.20M
            auto stepName = word.substr(strlen("proj="));
10259
1.20M
            steps.back().name = std::move(stepName);
10260
5.66M
        } else if (inPipeline && !steps.empty() && starts_with(word, "init=") &&
10261
2.84k
                   steps.back().name.empty()) {
10262
739
            auto initName = word.substr(strlen("init="));
10263
739
            steps.back().name = std::move(initName);
10264
739
            steps.back().isInit = true;
10265
5.66M
        } else if (!inPipeline && starts_with(word, "title=")) {
10266
438
            title = word.substr(strlen("title="));
10267
5.66M
        } else {
10268
5.66M
            const auto pos = word.find('=');
10269
5.66M
            auto key = word.substr(0, pos);
10270
5.66M
            Step::KeyValue pair((pos != std::string::npos)
10271
5.66M
                                    ? Step::KeyValue(key, word.substr(pos + 1))
10272
5.66M
                                    : Step::KeyValue(key));
10273
5.66M
            if (steps.empty()) {
10274
1.06M
                globalParamValues.emplace_back(std::move(pair));
10275
4.59M
            } else {
10276
4.59M
                steps.back().paramValues.emplace_back(std::move(pair));
10277
4.59M
            }
10278
5.66M
        }
10279
8.70M
    }
10280
239k
    if (invGlobal && !steps.empty()) {
10281
33.7k
        for (auto &step : steps) {
10282
33.7k
            step.inverted = !step.inverted;
10283
33.7k
        }
10284
3.29k
        std::reverse(steps.begin(), steps.end());
10285
3.29k
    }
10286
239k
}
10287
10288
// ---------------------------------------------------------------------------
10289
10290
void PROJStringFormatter::ingestPROJString(
10291
    const std::string &str) // throw ParsingException
10292
281k
{
10293
281k
    std::vector<Step> steps;
10294
281k
    std::string title;
10295
281k
    PROJStringSyntaxParser(str, steps, d->globalParamValues_, title);
10296
281k
    d->steps_.insert(d->steps_.end(), steps.begin(), steps.end());
10297
281k
}
10298
10299
// ---------------------------------------------------------------------------
10300
10301
14.4k
void PROJStringFormatter::setCRSExport(bool b) { d->crsExport_ = b; }
10302
10303
// ---------------------------------------------------------------------------
10304
10305
2.20M
bool PROJStringFormatter::getCRSExport() const { return d->crsExport_; }
10306
10307
// ---------------------------------------------------------------------------
10308
10309
692k
void PROJStringFormatter::startInversion() {
10310
692k
    PROJStringFormatter::Private::InversionStackElt elt;
10311
692k
    elt.startIter = d->steps_.end();
10312
692k
    if (elt.startIter != d->steps_.begin()) {
10313
469k
        elt.iterValid = true;
10314
469k
        --elt.startIter; // point to the last valid element
10315
469k
    } else {
10316
222k
        elt.iterValid = false;
10317
222k
    }
10318
692k
    elt.currentInversionState =
10319
692k
        !d->inversionStack_.back().currentInversionState;
10320
692k
    d->inversionStack_.push_back(elt);
10321
692k
}
10322
10323
// ---------------------------------------------------------------------------
10324
10325
691k
void PROJStringFormatter::stopInversion() {
10326
691k
    assert(!d->inversionStack_.empty());
10327
691k
    auto startIter = d->inversionStack_.back().startIter;
10328
691k
    if (!d->inversionStack_.back().iterValid) {
10329
222k
        startIter = d->steps_.begin();
10330
469k
    } else {
10331
469k
        ++startIter; // advance after the last valid element we marked above
10332
469k
    }
10333
    // Invert the inversion status of the steps between the start point and
10334
    // the current end of steps
10335
2.96M
    for (auto iter = startIter; iter != d->steps_.end(); ++iter) {
10336
2.27M
        iter->inverted = !iter->inverted;
10337
4.55M
        for (auto &paramValue : iter->paramValues) {
10338
4.55M
            if (paramValue.key == "omit_fwd")
10339
172
                paramValue.key = "omit_inv";
10340
4.55M
            else if (paramValue.key == "omit_inv")
10341
136
                paramValue.key = "omit_fwd";
10342
4.55M
        }
10343
2.27M
    }
10344
    // And reverse the order of steps in that range as well.
10345
691k
    std::reverse(startIter, d->steps_.end());
10346
691k
    d->inversionStack_.pop_back();
10347
691k
}
10348
10349
// ---------------------------------------------------------------------------
10350
10351
0
bool PROJStringFormatter::isInverted() const {
10352
0
    return d->inversionStack_.back().currentInversionState;
10353
0
}
10354
10355
// ---------------------------------------------------------------------------
10356
10357
3.07M
void PROJStringFormatter::Private::addStep() { steps_.emplace_back(Step()); }
10358
10359
// ---------------------------------------------------------------------------
10360
10361
3.03M
void PROJStringFormatter::addStep(const char *stepName) {
10362
3.03M
    d->addStep();
10363
3.03M
    d->steps_.back().name.assign(stepName);
10364
3.03M
}
10365
10366
// ---------------------------------------------------------------------------
10367
10368
47.5k
void PROJStringFormatter::addStep(const std::string &stepName) {
10369
47.5k
    d->addStep();
10370
47.5k
    d->steps_.back().name = stepName;
10371
47.5k
}
10372
10373
// ---------------------------------------------------------------------------
10374
10375
167k
void PROJStringFormatter::setCurrentStepInverted(bool inverted) {
10376
167k
    assert(!d->steps_.empty());
10377
167k
    d->steps_.back().inverted = inverted;
10378
167k
}
10379
10380
// ---------------------------------------------------------------------------
10381
10382
0
bool PROJStringFormatter::hasParam(const char *paramName) const {
10383
0
    if (!d->steps_.empty()) {
10384
0
        for (const auto &paramValue : d->steps_.back().paramValues) {
10385
0
            if (paramValue.keyEquals(paramName)) {
10386
0
                return true;
10387
0
            }
10388
0
        }
10389
0
    }
10390
0
    return false;
10391
0
}
10392
10393
// ---------------------------------------------------------------------------
10394
10395
27.0k
void PROJStringFormatter::addNoDefs(bool b) { d->addNoDefs_ = b; }
10396
10397
// ---------------------------------------------------------------------------
10398
10399
125k
bool PROJStringFormatter::getAddNoDefs() const { return d->addNoDefs_; }
10400
10401
// ---------------------------------------------------------------------------
10402
10403
369k
void PROJStringFormatter::addParam(const std::string &paramName) {
10404
369k
    if (d->steps_.empty()) {
10405
0
        d->addStep();
10406
0
    }
10407
369k
    d->steps_.back().paramValues.push_back(Step::KeyValue(paramName));
10408
369k
}
10409
10410
// ---------------------------------------------------------------------------
10411
10412
15
void PROJStringFormatter::addParam(const char *paramName, int val) {
10413
15
    addParam(std::string(paramName), val);
10414
15
}
10415
10416
15
void PROJStringFormatter::addParam(const std::string &paramName, int val) {
10417
15
    addParam(paramName, internal::toString(val));
10418
15
}
10419
10420
// ---------------------------------------------------------------------------
10421
10422
1.00M
static std::string formatToString(double val, double precision) {
10423
1.00M
    if (std::abs(val * 10 - std::round(val * 10)) < precision) {
10424
        // For the purpose of
10425
        // https://www.epsg-registry.org/export.htm?wkt=urn:ogc:def:crs:EPSG::27561
10426
        // Latitude of natural of origin to be properly rounded from 55 grad
10427
        // to
10428
        // 49.5 deg
10429
830k
        val = std::round(val * 10) / 10;
10430
830k
    }
10431
1.00M
    return normalizeSerializedString(internal::toString(val));
10432
1.00M
}
10433
10434
// ---------------------------------------------------------------------------
10435
10436
980k
void PROJStringFormatter::addParam(const char *paramName, double val) {
10437
980k
    addParam(std::string(paramName), val);
10438
980k
}
10439
10440
1.00M
void PROJStringFormatter::addParam(const std::string &paramName, double val) {
10441
1.00M
    if (paramName == "dt") {
10442
0
        addParam(paramName,
10443
0
                 normalizeSerializedString(internal::toString(val, 7)));
10444
1.00M
    } else {
10445
1.00M
        addParam(paramName, formatToString(val, 1e-8));
10446
1.00M
    }
10447
1.00M
}
10448
10449
// ---------------------------------------------------------------------------
10450
10451
void PROJStringFormatter::addParam(const char *paramName,
10452
40
                                   const std::vector<double> &vals) {
10453
40
    std::string paramValue;
10454
320
    for (size_t i = 0; i < vals.size(); ++i) {
10455
280
        if (i > 0) {
10456
240
            paramValue += ',';
10457
240
        }
10458
280
        paramValue += formatToString(vals[i], 1e-8);
10459
280
    }
10460
40
    addParam(paramName, paramValue);
10461
40
}
10462
10463
// ---------------------------------------------------------------------------
10464
10465
1.77M
void PROJStringFormatter::addParam(const char *paramName, const char *val) {
10466
1.77M
    addParam(std::string(paramName), val);
10467
1.77M
}
10468
10469
void PROJStringFormatter::addParam(const char *paramName,
10470
2.00M
                                   const std::string &val) {
10471
2.00M
    addParam(std::string(paramName), val);
10472
2.00M
}
10473
10474
void PROJStringFormatter::addParam(const std::string &paramName,
10475
1.77M
                                   const char *val) {
10476
1.77M
    addParam(paramName, std::string(val));
10477
1.77M
}
10478
10479
// ---------------------------------------------------------------------------
10480
10481
void PROJStringFormatter::addParam(const std::string &paramName,
10482
4.85M
                                   const std::string &val) {
10483
4.85M
    if (d->steps_.empty()) {
10484
545
        d->addStep();
10485
545
    }
10486
4.85M
    d->steps_.back().paramValues.push_back(Step::KeyValue(paramName, val));
10487
4.85M
}
10488
10489
// ---------------------------------------------------------------------------
10490
10491
void PROJStringFormatter::setTOWGS84Parameters(
10492
618
    const std::vector<double> &params) {
10493
618
    d->toWGS84Parameters_ = params;
10494
618
}
10495
10496
// ---------------------------------------------------------------------------
10497
10498
523k
const std::vector<double> &PROJStringFormatter::getTOWGS84Parameters() const {
10499
523k
    return d->toWGS84Parameters_;
10500
523k
}
10501
10502
// ---------------------------------------------------------------------------
10503
10504
32.0k
std::set<std::string> PROJStringFormatter::getUsedGridNames() const {
10505
32.0k
    std::set<std::string> res;
10506
205k
    for (const auto &step : d->steps_) {
10507
552k
        for (const auto &param : step.paramValues) {
10508
552k
            if (param.keyEquals("grids") || param.keyEquals("file")) {
10509
22.0k
                const auto gridNames = split(param.value, ",");
10510
70.7k
                for (const auto &gridName : gridNames) {
10511
70.7k
                    res.insert(gridName);
10512
70.7k
                }
10513
22.0k
            }
10514
552k
        }
10515
205k
    }
10516
32.0k
    return res;
10517
32.0k
}
10518
10519
// ---------------------------------------------------------------------------
10520
10521
123k
bool PROJStringFormatter::requiresPerCoordinateInputTime() const {
10522
704k
    for (const auto &step : d->steps_) {
10523
704k
        if (step.name == "set" && !step.inverted) {
10524
58.1k
            for (const auto &param : step.paramValues) {
10525
58.1k
                if (param.keyEquals("v_4")) {
10526
1
                    return false;
10527
1
                }
10528
58.1k
            }
10529
687k
        } else if (step.name == "helmert") {
10530
166k
            for (const auto &param : step.paramValues) {
10531
166k
                if (param.keyEquals("t_epoch")) {
10532
58
                    return true;
10533
58
                }
10534
166k
            }
10535
640k
        } else if (step.name == "deformation") {
10536
12.0k
            for (const auto &param : step.paramValues) {
10537
12.0k
                if (param.keyEquals("t_epoch")) {
10538
751
                    return true;
10539
751
                }
10540
12.0k
            }
10541
636k
        } else if (step.name == "defmodel") {
10542
0
            return true;
10543
0
        }
10544
704k
    }
10545
123k
    return false;
10546
123k
}
10547
10548
// ---------------------------------------------------------------------------
10549
10550
void PROJStringFormatter::setVDatumExtension(const std::string &filename,
10551
772
                                             const std::string &geoidCRSValue) {
10552
772
    d->vDatumExtension_ = filename;
10553
772
    d->geoidCRSValue_ = geoidCRSValue;
10554
772
}
10555
10556
// ---------------------------------------------------------------------------
10557
10558
754
const std::string &PROJStringFormatter::getVDatumExtension() const {
10559
754
    return d->vDatumExtension_;
10560
754
}
10561
10562
// ---------------------------------------------------------------------------
10563
10564
754
const std::string &PROJStringFormatter::getGeoidCRSValue() const {
10565
754
    return d->geoidCRSValue_;
10566
754
}
10567
10568
// ---------------------------------------------------------------------------
10569
10570
419
void PROJStringFormatter::setHDatumExtension(const std::string &filename) {
10571
419
    d->hDatumExtension_ = filename;
10572
419
}
10573
10574
// ---------------------------------------------------------------------------
10575
10576
523k
const std::string &PROJStringFormatter::getHDatumExtension() const {
10577
523k
    return d->hDatumExtension_;
10578
523k
}
10579
10580
// ---------------------------------------------------------------------------
10581
10582
void PROJStringFormatter::setGeogCRSOfCompoundCRS(
10583
391
    const crs::GeographicCRSPtr &crs) {
10584
391
    d->geogCRSOfCompoundCRS_ = crs;
10585
391
}
10586
10587
// ---------------------------------------------------------------------------
10588
10589
const crs::GeographicCRSPtr &
10590
1.07k
PROJStringFormatter::getGeogCRSOfCompoundCRS() const {
10591
1.07k
    return d->geogCRSOfCompoundCRS_;
10592
1.07k
}
10593
10594
// ---------------------------------------------------------------------------
10595
10596
233k
void PROJStringFormatter::setOmitProjLongLatIfPossible(bool omit) {
10597
233k
    assert(d->omitProjLongLatIfPossible_ ^ omit);
10598
233k
    d->omitProjLongLatIfPossible_ = omit;
10599
233k
}
10600
10601
// ---------------------------------------------------------------------------
10602
10603
478k
bool PROJStringFormatter::omitProjLongLatIfPossible() const {
10604
478k
    return d->omitProjLongLatIfPossible_;
10605
478k
}
10606
10607
// ---------------------------------------------------------------------------
10608
10609
270k
void PROJStringFormatter::pushOmitZUnitConversion() {
10610
270k
    d->omitZUnitConversion_.push_back(true);
10611
270k
}
10612
10613
// ---------------------------------------------------------------------------
10614
10615
270k
void PROJStringFormatter::popOmitZUnitConversion() {
10616
270k
    assert(d->omitZUnitConversion_.size() > 1);
10617
270k
    d->omitZUnitConversion_.pop_back();
10618
270k
}
10619
10620
// ---------------------------------------------------------------------------
10621
10622
596k
bool PROJStringFormatter::omitZUnitConversion() const {
10623
596k
    return d->omitZUnitConversion_.back();
10624
596k
}
10625
10626
// ---------------------------------------------------------------------------
10627
10628
100k
void PROJStringFormatter::pushOmitHorizontalConversionInVertTransformation() {
10629
100k
    d->omitHorizontalConversionInVertTransformation_.push_back(true);
10630
100k
}
10631
10632
// ---------------------------------------------------------------------------
10633
10634
100k
void PROJStringFormatter::popOmitHorizontalConversionInVertTransformation() {
10635
100k
    assert(d->omitHorizontalConversionInVertTransformation_.size() > 1);
10636
100k
    d->omitHorizontalConversionInVertTransformation_.pop_back();
10637
100k
}
10638
10639
// ---------------------------------------------------------------------------
10640
10641
240k
bool PROJStringFormatter::omitHorizontalConversionInVertTransformation() const {
10642
240k
    return d->omitHorizontalConversionInVertTransformation_.back();
10643
240k
}
10644
10645
// ---------------------------------------------------------------------------
10646
10647
14.4k
void PROJStringFormatter::setLegacyCRSToCRSContext(bool legacyContext) {
10648
14.4k
    d->legacyCRSToCRSContext_ = legacyContext;
10649
14.4k
}
10650
10651
// ---------------------------------------------------------------------------
10652
10653
400k
bool PROJStringFormatter::getLegacyCRSToCRSContext() const {
10654
400k
    return d->legacyCRSToCRSContext_;
10655
400k
}
10656
10657
// ---------------------------------------------------------------------------
10658
10659
/** Asks for a "normalized" output during toString(), aimed at comparing two
10660
 * strings for equivalence.
10661
 *
10662
 * This consists for now in sorting the +key=value option in lexicographic
10663
 * order.
10664
 */
10665
14.5k
PROJStringFormatter &PROJStringFormatter::setNormalizeOutput() {
10666
14.5k
    d->normalizeOutput_ = true;
10667
14.5k
    return *this;
10668
14.5k
}
10669
10670
// ---------------------------------------------------------------------------
10671
10672
601k
const DatabaseContextPtr &PROJStringFormatter::databaseContext() const {
10673
601k
    return d->dbContext_;
10674
601k
}
10675
10676
//! @endcond
10677
10678
// ---------------------------------------------------------------------------
10679
10680
//! @cond Doxygen_Suppress
10681
10682
struct PROJStringParser::Private {
10683
    DatabaseContextPtr dbContext_{};
10684
    PJ_CONTEXT *ctx_{};
10685
    bool usePROJ4InitRules_ = false;
10686
    std::vector<std::string> warningList_{};
10687
10688
    std::string projString_{};
10689
10690
    std::vector<Step> steps_{};
10691
    std::vector<Step::KeyValue> globalParamValues_{};
10692
    std::string title_{};
10693
10694
    bool ignoreNadgrids_ = false;
10695
10696
    template <class T>
10697
    // cppcheck-suppress functionStatic
10698
90.1k
    bool hasParamValue(Step &step, const T key) {
10699
159k
        for (auto &pair : globalParamValues_) {
10700
159k
            if (ci_equal(pair.key, key)) {
10701
1.47k
                pair.usedByParser = true;
10702
1.47k
                return true;
10703
1.47k
            }
10704
159k
        }
10705
208k
        for (auto &pair : step.paramValues) {
10706
208k
            if (ci_equal(pair.key, key)) {
10707
7.86k
                pair.usedByParser = true;
10708
7.86k
                return true;
10709
7.86k
            }
10710
208k
        }
10711
80.8k
        return false;
10712
88.7k
    }
10713
10714
    template <class T>
10715
    // cppcheck-suppress functionStatic
10716
2.17k
    const std::string &getGlobalParamValue(T key) {
10717
13.7k
        for (auto &pair : globalParamValues_) {
10718
13.7k
            if (ci_equal(pair.key, key)) {
10719
1.33k
                pair.usedByParser = true;
10720
1.33k
                return pair.value;
10721
1.33k
            }
10722
13.7k
        }
10723
840
        return emptyString;
10724
2.17k
    }
10725
10726
    template <class T>
10727
    // cppcheck-suppress functionStatic
10728
437k
    const std::string &getParamValue(Step &step, const T key) {
10729
608k
        for (auto &pair : globalParamValues_) {
10730
608k
            if (ci_equal(pair.key, key)) {
10731
7.25k
                pair.usedByParser = true;
10732
7.25k
                return pair.value;
10733
7.25k
            }
10734
608k
        }
10735
936k
        for (auto &pair : step.paramValues) {
10736
936k
            if (ci_equal(pair.key, key)) {
10737
40.2k
                pair.usedByParser = true;
10738
40.2k
                return pair.value;
10739
40.2k
            }
10740
936k
        }
10741
389k
        return emptyString;
10742
429k
    }
std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const& osgeo::proj::io::PROJStringParser::Private::getParamValue<std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > >(osgeo::proj::io::Step&, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)
Line
Count
Source
10728
91.8k
    const std::string &getParamValue(Step &step, const T key) {
10729
135k
        for (auto &pair : globalParamValues_) {
10730
135k
            if (ci_equal(pair.key, key)) {
10731
267
                pair.usedByParser = true;
10732
267
                return pair.value;
10733
267
            }
10734
135k
        }
10735
224k
        for (auto &pair : step.paramValues) {
10736
224k
            if (ci_equal(pair.key, key)) {
10737
3.36k
                pair.usedByParser = true;
10738
3.36k
                return pair.value;
10739
3.36k
            }
10740
224k
        }
10741
88.2k
        return emptyString;
10742
91.6k
    }
std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const& osgeo::proj::io::PROJStringParser::Private::getParamValue<char const*>(osgeo::proj::io::Step&, char const*)
Line
Count
Source
10728
345k
    const std::string &getParamValue(Step &step, const T key) {
10729
472k
        for (auto &pair : globalParamValues_) {
10730
472k
            if (ci_equal(pair.key, key)) {
10731
6.98k
                pair.usedByParser = true;
10732
6.98k
                return pair.value;
10733
6.98k
            }
10734
472k
        }
10735
712k
        for (auto &pair : step.paramValues) {
10736
712k
            if (ci_equal(pair.key, key)) {
10737
36.8k
                pair.usedByParser = true;
10738
36.8k
                return pair.value;
10739
36.8k
            }
10740
712k
        }
10741
301k
        return emptyString;
10742
338k
    }
10743
10744
2.11k
    static const std::string &getParamValueK(Step &step) {
10745
4.39k
        for (auto &pair : step.paramValues) {
10746
4.39k
            if (ci_equal(pair.key, "k") || ci_equal(pair.key, "k_0")) {
10747
74
                pair.usedByParser = true;
10748
74
                return pair.value;
10749
74
            }
10750
4.39k
        }
10751
2.03k
        return emptyString;
10752
2.11k
    }
10753
10754
    // cppcheck-suppress functionStatic
10755
18.3k
    bool hasUnusedParameters(const Step &step) const {
10756
18.3k
        if (steps_.size() == 1) {
10757
16.1k
            for (const auto &pair : step.paramValues) {
10758
16.1k
                if (pair.key != "no_defs" && !pair.usedByParser) {
10759
4.79k
                    return true;
10760
4.79k
                }
10761
16.1k
            }
10762
15.4k
        }
10763
13.5k
        return false;
10764
18.3k
    }
10765
10766
    // cppcheck-suppress functionStatic
10767
    std::string guessBodyName(double a);
10768
10769
    PrimeMeridianNNPtr buildPrimeMeridian(Step &step);
10770
    GeodeticReferenceFrameNNPtr buildDatum(Step &step,
10771
                                           const std::string &title);
10772
    GeodeticCRSNNPtr buildGeodeticCRS(int iStep, int iUnitConvert,
10773
                                      int iAxisSwap, bool ignorePROJAxis);
10774
    GeodeticCRSNNPtr buildGeocentricCRS(int iStep, int iUnitConvert);
10775
    CRSNNPtr buildProjectedCRS(int iStep, const GeodeticCRSNNPtr &geogCRS,
10776
                               int iUnitConvert, int iAxisSwap);
10777
    CRSNNPtr buildBoundOrCompoundCRSIfNeeded(int iStep, CRSNNPtr crs);
10778
    UnitOfMeasure buildUnit(Step &step, const std::string &unitsParamName,
10779
                            const std::string &toMeterParamName);
10780
10781
    enum class AxisType { REGULAR, NORTH_POLE, SOUTH_POLE };
10782
10783
    std::vector<CoordinateSystemAxisNNPtr>
10784
    processAxisSwap(Step &step, const UnitOfMeasure &unit, int iAxisSwap,
10785
                    AxisType axisType, bool ignorePROJAxis);
10786
10787
    EllipsoidalCSNNPtr buildEllipsoidalCS(int iStep, int iUnitConvert,
10788
                                          int iAxisSwap, bool ignorePROJAxis);
10789
10790
    SphericalCSNNPtr buildSphericalCS(int iStep, int iUnitConvert,
10791
                                      int iAxisSwap, bool ignorePROJAxis);
10792
};
10793
10794
//! @endcond
10795
10796
// ---------------------------------------------------------------------------
10797
10798
12.9k
PROJStringParser::PROJStringParser() : d(std::make_unique<Private>()) {}
10799
10800
// ---------------------------------------------------------------------------
10801
10802
//! @cond Doxygen_Suppress
10803
12.9k
PROJStringParser::~PROJStringParser() = default;
10804
//! @endcond
10805
10806
// ---------------------------------------------------------------------------
10807
10808
/** \brief Attach a database context, to allow queries in it if needed.
10809
 */
10810
PROJStringParser &
10811
12.8k
PROJStringParser::attachDatabaseContext(const DatabaseContextPtr &dbContext) {
10812
12.8k
    d->dbContext_ = dbContext;
10813
12.8k
    return *this;
10814
12.8k
}
10815
10816
// ---------------------------------------------------------------------------
10817
10818
//! @cond Doxygen_Suppress
10819
12.8k
PROJStringParser &PROJStringParser::attachContext(PJ_CONTEXT *ctx) {
10820
12.8k
    d->ctx_ = ctx;
10821
12.8k
    return *this;
10822
12.8k
}
10823
//! @endcond
10824
10825
// ---------------------------------------------------------------------------
10826
10827
/** \brief Set how init=epsg:XXXX syntax should be interpreted.
10828
 *
10829
 * @param enable When set to true,
10830
 * init=epsg:XXXX syntax will be allowed and will be interpreted according to
10831
 * PROJ.4 and PROJ.5 rules, that is geodeticCRS will have longitude, latitude
10832
 * order and will expect/output coordinates in radians. ProjectedCRS will have
10833
 * easting, northing axis order (except the ones with Transverse Mercator South
10834
 * Orientated projection).
10835
 */
10836
12.8k
PROJStringParser &PROJStringParser::setUsePROJ4InitRules(bool enable) {
10837
12.8k
    d->usePROJ4InitRules_ = enable;
10838
12.8k
    return *this;
10839
12.8k
}
10840
10841
// ---------------------------------------------------------------------------
10842
10843
/** \brief Return the list of warnings found during parsing.
10844
 */
10845
0
std::vector<std::string> PROJStringParser::warningList() const {
10846
0
    return d->warningList_;
10847
0
}
10848
10849
// ---------------------------------------------------------------------------
10850
10851
//! @cond Doxygen_Suppress
10852
10853
// ---------------------------------------------------------------------------
10854
10855
static const struct LinearUnitDesc {
10856
    const char *projName;
10857
    const char *convToMeter;
10858
    const char *name;
10859
    int epsgCode;
10860
} linearUnitDescs[] = {
10861
    {"mm", "0.001", "millimetre", 1025},
10862
    {"cm", "0.01", "centimetre", 1033},
10863
    {"m", "1.0", "metre", 9001},
10864
    {"meter", "1.0", "metre", 9001}, // alternative
10865
    {"metre", "1.0", "metre", 9001}, // alternative
10866
    {"ft", "0.3048", "foot", 9002},
10867
    {"us-ft", "0.3048006096012192", "US survey foot", 9003},
10868
    {"fath", "1.8288", "fathom", 9014},
10869
    {"kmi", "1852", "nautical mile", 9030},
10870
    {"us-ch", "20.11684023368047", "US survey chain", 9033},
10871
    {"us-mi", "1609.347218694437", "US survey mile", 9035},
10872
    {"km", "1000.0", "kilometre", 9036},
10873
    {"ind-ft", "0.30479841", "Indian foot (1937)", 9081},
10874
    {"ind-yd", "0.91439523", "Indian yard (1937)", 9085},
10875
    {"mi", "1609.344", "Statute mile", 9093},
10876
    {"yd", "0.9144", "yard", 9096},
10877
    {"ch", "20.1168", "chain", 9097},
10878
    {"link", "0.201168", "link", 9098},
10879
    {"dm", "0.1", "decimetre", 0},                       // no EPSG equivalent
10880
    {"in", "0.0254", "inch", 0},                         // no EPSG equivalent
10881
    {"us-in", "0.025400050800101", "US survey inch", 0}, // no EPSG equivalent
10882
    {"us-yd", "0.914401828803658", "US survey yard", 0}, // no EPSG equivalent
10883
    {"ind-ch", "20.11669506", "Indian chain", 0},        // no EPSG equivalent
10884
};
10885
10886
2.81k
static const LinearUnitDesc *getLinearUnits(const std::string &projName) {
10887
14.3k
    for (const auto &desc : linearUnitDescs) {
10888
14.3k
        if (desc.projName == projName)
10889
2.79k
            return &desc;
10890
14.3k
    }
10891
27
    return nullptr;
10892
2.81k
}
10893
10894
190
static const LinearUnitDesc *getLinearUnits(double toMeter) {
10895
4.13k
    for (const auto &desc : linearUnitDescs) {
10896
4.13k
        if (std::fabs(c_locale_stod(desc.convToMeter) - toMeter) <
10897
4.13k
            1e-10 * toMeter) {
10898
12
            return &desc;
10899
12
        }
10900
4.13k
    }
10901
178
    return nullptr;
10902
190
}
10903
10904
// ---------------------------------------------------------------------------
10905
10906
2.80k
static UnitOfMeasure _buildUnit(const LinearUnitDesc *unitsMatch) {
10907
2.80k
    std::string unitsCode;
10908
2.80k
    if (unitsMatch->epsgCode) {
10909
2.78k
        std::ostringstream buffer;
10910
2.78k
        buffer.imbue(std::locale::classic());
10911
2.78k
        buffer << unitsMatch->epsgCode;
10912
2.78k
        unitsCode = buffer.str();
10913
2.78k
    }
10914
2.80k
    return UnitOfMeasure(
10915
2.80k
        unitsMatch->name, c_locale_stod(unitsMatch->convToMeter),
10916
2.80k
        UnitOfMeasure::Type::LINEAR,
10917
2.80k
        unitsMatch->epsgCode ? Identifier::EPSG : std::string(), unitsCode);
10918
2.80k
}
10919
10920
// ---------------------------------------------------------------------------
10921
10922
178
static UnitOfMeasure _buildUnit(double to_meter_value) {
10923
    // TODO: look-up in EPSG catalog
10924
178
    if (to_meter_value == 0) {
10925
1
        throw ParsingException("invalid unit value");
10926
1
    }
10927
177
    return UnitOfMeasure("unknown", to_meter_value,
10928
177
                         UnitOfMeasure::Type::LINEAR);
10929
178
}
10930
10931
// ---------------------------------------------------------------------------
10932
10933
UnitOfMeasure
10934
PROJStringParser::Private::buildUnit(Step &step,
10935
                                     const std::string &unitsParamName,
10936
36.5k
                                     const std::string &toMeterParamName) {
10937
36.5k
    UnitOfMeasure unit = UnitOfMeasure::METRE;
10938
36.5k
    const LinearUnitDesc *unitsMatch = nullptr;
10939
36.5k
    const auto &projUnits = getParamValue(step, unitsParamName);
10940
36.5k
    if (!projUnits.empty()) {
10941
2.81k
        unitsMatch = getLinearUnits(projUnits);
10942
2.81k
        if (unitsMatch == nullptr) {
10943
22
            throw ParsingException("unhandled " + unitsParamName + "=" +
10944
22
                                   projUnits);
10945
22
        }
10946
2.81k
    }
10947
10948
36.4k
    const auto &toMeter = getParamValue(step, toMeterParamName);
10949
36.4k
    if (!toMeter.empty()) {
10950
200
        double to_meter_value;
10951
200
        try {
10952
200
            to_meter_value = c_locale_stod(toMeter);
10953
200
        } catch (const std::invalid_argument &) {
10954
10
            throw ParsingException("invalid value for " + toMeterParamName);
10955
10
        }
10956
190
        unitsMatch = getLinearUnits(to_meter_value);
10957
190
        if (unitsMatch == nullptr) {
10958
178
            unit = _buildUnit(to_meter_value);
10959
178
        }
10960
190
    }
10961
10962
36.4k
    if (unitsMatch) {
10963
2.80k
        unit = _buildUnit(unitsMatch);
10964
2.80k
    }
10965
10966
36.4k
    return unit;
10967
36.4k
}
10968
10969
// ---------------------------------------------------------------------------
10970
10971
static const struct DatumDesc {
10972
    const char *projName;
10973
    const char *gcsName;
10974
    int gcsCode;
10975
    const char *datumName;
10976
    int datumCode;
10977
    const char *ellipsoidName;
10978
    int ellipsoidCode;
10979
    double a;
10980
    double rf;
10981
} datumDescs[] = {
10982
    {"GGRS87", "GGRS87", 4121, "Greek Geodetic Reference System 1987", 6121,
10983
     "GRS 1980", 7019, 6378137, 298.257222101},
10984
    {"potsdam", "DHDN", 4314, "Deutsches Hauptdreiecksnetz", 6314,
10985
     "Bessel 1841", 7004, 6377397.155, 299.1528128},
10986
    {"carthage", "Carthage", 4223, "Carthage", 6223, "Clarke 1880 (IGN)", 7011,
10987
     6378249.2, 293.4660213},
10988
    {"hermannskogel", "MGI", 4312, "Militar-Geographische Institut", 6312,
10989
     "Bessel 1841", 7004, 6377397.155, 299.1528128},
10990
    {"ire65", "TM65", 4299, "TM65", 6299, "Airy Modified 1849", 7002,
10991
     6377340.189, 299.3249646},
10992
    {"nzgd49", "NZGD49", 4272, "New Zealand Geodetic Datum 1949", 6272,
10993
     "International 1924", 7022, 6378388, 297},
10994
    {"OSGB36", "OSGB 1936", 4277, "OSGB 1936", 6277, "Airy 1830", 7001,
10995
     6377563.396, 299.3249646},
10996
};
10997
10998
// ---------------------------------------------------------------------------
10999
11000
30.1k
static bool isGeographicStep(const std::string &name) {
11001
30.1k
    return name == "longlat" || name == "lonlat" || name == "latlong" ||
11002
18.9k
           name == "latlon";
11003
30.1k
}
11004
11005
// ---------------------------------------------------------------------------
11006
11007
9.26k
static bool isGeocentricStep(const std::string &name) {
11008
9.26k
    return name == "geocent" || name == "cart";
11009
9.26k
}
11010
11011
// ---------------------------------------------------------------------------
11012
11013
20.1k
static bool isTopocentricStep(const std::string &name) {
11014
20.1k
    return name == "topocentric";
11015
20.1k
}
11016
11017
// ---------------------------------------------------------------------------
11018
11019
9.91k
static bool isProjectedStep(const std::string &name) {
11020
9.91k
    if (name == "etmerc" || name == "utm" ||
11021
9.81k
        !getMappingsFromPROJName(name).empty()) {
11022
3.18k
        return true;
11023
3.18k
    }
11024
    // IMPROVE ME: have a better way of distinguishing projections from
11025
    // other
11026
    // transformations.
11027
6.73k
    if (name == "pipeline" || name == "geoc" || name == "deformation" ||
11028
6.71k
        name == "helmert" || name == "hgridshift" || name == "molodensky" ||
11029
6.57k
        name == "vgridshift") {
11030
237
        return false;
11031
237
    }
11032
6.50k
    const auto *operations = proj_list_operations();
11033
586k
    for (int i = 0; operations[i].id != nullptr; ++i) {
11034
585k
        if (name == operations[i].id) {
11035
6.05k
            return true;
11036
6.05k
        }
11037
585k
    }
11038
443
    return false;
11039
6.50k
}
11040
11041
// ---------------------------------------------------------------------------
11042
11043
33.9k
static PropertyMap createMapWithUnknownName() {
11044
33.9k
    return PropertyMap().set(common::IdentifiedObject::NAME_KEY, "unknown");
11045
33.9k
}
11046
11047
// ---------------------------------------------------------------------------
11048
11049
28.8k
PrimeMeridianNNPtr PROJStringParser::Private::buildPrimeMeridian(Step &step) {
11050
11051
28.8k
    PrimeMeridianNNPtr pm = PrimeMeridian::GREENWICH;
11052
28.8k
    const auto &pmStr = getParamValue(step, "pm");
11053
28.8k
    if (!pmStr.empty()) {
11054
3.06k
        char *end;
11055
3.06k
        double pmValue = dmstor(pmStr.c_str(), &end) * RAD_TO_DEG;
11056
3.06k
        if (pmValue != HUGE_VAL && *end == '\0') {
11057
2.89k
            pm = PrimeMeridian::create(createMapWithUnknownName(),
11058
2.89k
                                       Angle(pmValue));
11059
2.89k
        } else {
11060
168
            bool found = false;
11061
168
            if (pmStr == "paris") {
11062
34
                found = true;
11063
34
                pm = PrimeMeridian::PARIS;
11064
34
            }
11065
168
            auto proj_prime_meridians = proj_list_prime_meridians();
11066
1.65k
            for (int i = 0; !found && proj_prime_meridians[i].id != nullptr;
11067
1.62k
                 i++) {
11068
1.62k
                if (pmStr == proj_prime_meridians[i].id) {
11069
131
                    found = true;
11070
131
                    std::string name = static_cast<char>(::toupper(pmStr[0])) +
11071
131
                                       pmStr.substr(1);
11072
131
                    pmValue = dmstor(proj_prime_meridians[i].defn, nullptr) *
11073
131
                              RAD_TO_DEG;
11074
131
                    pm = PrimeMeridian::create(
11075
131
                        PropertyMap().set(IdentifiedObject::NAME_KEY, name),
11076
131
                        Angle(pmValue));
11077
131
                    break;
11078
131
                }
11079
1.62k
            }
11080
168
            if (!found) {
11081
3
                throw ParsingException("unknown pm " + pmStr);
11082
3
            }
11083
168
        }
11084
3.06k
    }
11085
28.8k
    return pm;
11086
28.8k
}
11087
11088
// ---------------------------------------------------------------------------
11089
11090
895
std::string PROJStringParser::Private::guessBodyName(double a) {
11091
11092
895
    auto ret = Ellipsoid::guessBodyName(dbContext_, a);
11093
895
    if (ret == NON_EARTH_BODY && dbContext_ == nullptr && ctx_ != nullptr) {
11094
78
        dbContext_ =
11095
78
            ctx_->get_cpp_context()->getDatabaseContext().as_nullable();
11096
78
        if (dbContext_) {
11097
78
            ret = Ellipsoid::guessBodyName(dbContext_, a);
11098
78
        }
11099
78
    }
11100
895
    return ret;
11101
895
}
11102
11103
// ---------------------------------------------------------------------------
11104
11105
GeodeticReferenceFrameNNPtr
11106
18.3k
PROJStringParser::Private::buildDatum(Step &step, const std::string &title) {
11107
11108
18.3k
    std::string ellpsStr = getParamValue(step, "ellps");
11109
18.3k
    const auto &datumStr = getParamValue(step, "datum");
11110
18.3k
    const auto &RStr = getParamValue(step, "R");
11111
18.3k
    const auto &aStr = getParamValue(step, "a");
11112
18.3k
    const auto &bStr = getParamValue(step, "b");
11113
18.3k
    const auto &rfStr = getParamValue(step, "rf");
11114
18.3k
    const auto &fStr = getParamValue(step, "f");
11115
18.3k
    const auto &esStr = getParamValue(step, "es");
11116
18.3k
    const auto &eStr = getParamValue(step, "e");
11117
18.3k
    double a = -1.0;
11118
18.3k
    double b = -1.0;
11119
18.3k
    double rf = -1.0;
11120
18.3k
    const util::optional<std::string> optionalEmptyString{};
11121
18.3k
    const bool numericParamPresent =
11122
18.3k
        !RStr.empty() || !aStr.empty() || !bStr.empty() || !rfStr.empty() ||
11123
17.6k
        !fStr.empty() || !esStr.empty() || !eStr.empty();
11124
11125
18.3k
    if (!numericParamPresent && ellpsStr.empty() && datumStr.empty() &&
11126
14.6k
        (step.name == "krovak" || step.name == "mod_krovak")) {
11127
717
        ellpsStr = "bessel";
11128
717
    }
11129
11130
18.3k
    PrimeMeridianNNPtr pm(buildPrimeMeridian(step));
11131
18.3k
    PropertyMap grfMap;
11132
11133
18.3k
    const auto &nadgrids = getParamValue(step, "nadgrids");
11134
18.3k
    const auto &towgs84 = getParamValue(step, "towgs84");
11135
18.3k
    std::string datumNameSuffix;
11136
18.3k
    if (!nadgrids.empty()) {
11137
1.50k
        datumNameSuffix = " using nadgrids=" + nadgrids;
11138
16.8k
    } else if (!towgs84.empty()) {
11139
1.23k
        datumNameSuffix = " using towgs84=" + towgs84;
11140
1.23k
    }
11141
11142
    // It is arguable that we allow the prime meridian of a datum defined by
11143
    // its name to be overridden, but this is found at least in a regression
11144
    // test
11145
    // of GDAL. So let's keep the ellipsoid part of the datum in that case and
11146
    // use the specified prime meridian.
11147
18.3k
    const auto overridePmIfNeeded =
11148
18.3k
        [&pm, &datumNameSuffix](const GeodeticReferenceFrameNNPtr &grf) {
11149
15.3k
            if (pm->_isEquivalentTo(PrimeMeridian::GREENWICH.get())) {
11150
14.2k
                return grf;
11151
14.2k
            } else {
11152
1.09k
                return GeodeticReferenceFrame::create(
11153
1.09k
                    PropertyMap().set(IdentifiedObject::NAME_KEY,
11154
1.09k
                                      UNKNOWN_BASED_ON +
11155
1.09k
                                          grf->ellipsoid()->nameStr() +
11156
1.09k
                                          " ellipsoid" + datumNameSuffix),
11157
1.09k
                    grf->ellipsoid(), grf->anchorDefinition(), pm);
11158
1.09k
            }
11159
15.3k
        };
11160
11161
    // R take precedence
11162
18.3k
    if (!RStr.empty()) {
11163
113
        double R;
11164
113
        try {
11165
113
            R = c_locale_stod(RStr);
11166
113
        } catch (const std::invalid_argument &) {
11167
18
            throw ParsingException("Invalid R value");
11168
18
        }
11169
95
        auto ellipsoid = Ellipsoid::createSphere(createMapWithUnknownName(),
11170
95
                                                 Length(R), guessBodyName(R));
11171
95
        return GeodeticReferenceFrame::create(
11172
95
            grfMap.set(IdentifiedObject::NAME_KEY,
11173
95
                       title.empty() ? "unknown" + datumNameSuffix : title),
11174
95
            ellipsoid, optionalEmptyString, fixupPrimeMeridan(ellipsoid, pm));
11175
113
    }
11176
11177
18.2k
    if (!datumStr.empty()) {
11178
2.55k
        auto l_datum = [&datumStr, &overridePmIfNeeded, &grfMap,
11179
2.55k
                        &optionalEmptyString, &pm]() {
11180
2.55k
            if (datumStr == "WGS84") {
11181
3
                return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6326);
11182
2.54k
            } else if (datumStr == "NAD83") {
11183
525
                return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6269);
11184
2.02k
            } else if (datumStr == "NAD27") {
11185
875
                return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6267);
11186
1.14k
            } else {
11187
11188
6.20k
                for (const auto &datumDesc : datumDescs) {
11189
6.20k
                    if (datumStr == datumDesc.projName) {
11190
1.12k
                        (void)datumDesc.gcsName; // to please cppcheck
11191
1.12k
                        (void)datumDesc.gcsCode; // to please cppcheck
11192
1.12k
                        auto ellipsoid = Ellipsoid::createFlattenedSphere(
11193
1.12k
                            grfMap
11194
1.12k
                                .set(IdentifiedObject::NAME_KEY,
11195
1.12k
                                     datumDesc.ellipsoidName)
11196
1.12k
                                .set(Identifier::CODESPACE_KEY,
11197
1.12k
                                     Identifier::EPSG)
11198
1.12k
                                .set(Identifier::CODE_KEY,
11199
1.12k
                                     datumDesc.ellipsoidCode),
11200
1.12k
                            Length(datumDesc.a), Scale(datumDesc.rf));
11201
1.12k
                        return GeodeticReferenceFrame::create(
11202
1.12k
                            grfMap
11203
1.12k
                                .set(IdentifiedObject::NAME_KEY,
11204
1.12k
                                     datumDesc.datumName)
11205
1.12k
                                .set(Identifier::CODESPACE_KEY,
11206
1.12k
                                     Identifier::EPSG)
11207
1.12k
                                .set(Identifier::CODE_KEY, datumDesc.datumCode),
11208
1.12k
                            ellipsoid, optionalEmptyString, pm);
11209
1.12k
                    }
11210
6.20k
                }
11211
1.14k
            }
11212
19
            throw ParsingException("unknown datum " + datumStr);
11213
2.55k
        }();
11214
2.55k
        if (!numericParamPresent) {
11215
2.11k
            return l_datum;
11216
2.11k
        }
11217
439
        a = l_datum->ellipsoid()->semiMajorAxis().getSIValue();
11218
439
        rf = l_datum->ellipsoid()->computedInverseFlattening();
11219
439
    }
11220
11221
15.7k
    else if (!ellpsStr.empty()) {
11222
1.44k
        auto l_datum = [&ellpsStr, &title, &grfMap, &optionalEmptyString, &pm,
11223
1.44k
                        &datumNameSuffix]() {
11224
1.44k
            if (ellpsStr == "WGS84") {
11225
22
                return GeodeticReferenceFrame::create(
11226
22
                    grfMap.set(IdentifiedObject::NAME_KEY,
11227
22
                               title.empty() ? std::string(UNKNOWN_BASED_ON)
11228
20
                                                   .append("WGS 84 ellipsoid")
11229
20
                                                   .append(datumNameSuffix)
11230
22
                                             : title),
11231
22
                    Ellipsoid::WGS84, optionalEmptyString, pm);
11232
1.42k
            } else if (ellpsStr == "GRS80") {
11233
26
                return GeodeticReferenceFrame::create(
11234
26
                    grfMap.set(IdentifiedObject::NAME_KEY,
11235
26
                               title.empty() ? std::string(UNKNOWN_BASED_ON)
11236
6
                                                   .append("GRS 1980 ellipsoid")
11237
6
                                                   .append(datumNameSuffix)
11238
26
                                             : title),
11239
26
                    Ellipsoid::GRS1980, optionalEmptyString, pm);
11240
1.40k
            } else {
11241
1.40k
                auto proj_ellps = proj_list_ellps();
11242
20.8k
                for (int i = 0; proj_ellps[i].id != nullptr; i++) {
11243
20.8k
                    if (ellpsStr == proj_ellps[i].id) {
11244
1.38k
                        assert(strncmp(proj_ellps[i].major, "a=", 2) == 0);
11245
1.38k
                        const double a_iter =
11246
1.38k
                            c_locale_stod(proj_ellps[i].major + 2);
11247
1.38k
                        EllipsoidPtr ellipsoid;
11248
1.38k
                        PropertyMap ellpsMap;
11249
1.38k
                        if (strncmp(proj_ellps[i].ell, "b=", 2) == 0) {
11250
67
                            const double b_iter =
11251
67
                                c_locale_stod(proj_ellps[i].ell + 2);
11252
67
                            ellipsoid =
11253
67
                                Ellipsoid::createTwoAxis(
11254
67
                                    ellpsMap.set(IdentifiedObject::NAME_KEY,
11255
67
                                                 proj_ellps[i].name),
11256
67
                                    Length(a_iter), Length(b_iter))
11257
67
                                    .as_nullable();
11258
1.32k
                        } else {
11259
1.32k
                            assert(strncmp(proj_ellps[i].ell, "rf=", 3) == 0);
11260
1.32k
                            const double rf_iter =
11261
1.32k
                                c_locale_stod(proj_ellps[i].ell + 3);
11262
1.32k
                            ellipsoid =
11263
1.32k
                                Ellipsoid::createFlattenedSphere(
11264
1.32k
                                    ellpsMap.set(IdentifiedObject::NAME_KEY,
11265
1.32k
                                                 proj_ellps[i].name),
11266
1.32k
                                    Length(a_iter), Scale(rf_iter))
11267
1.32k
                                    .as_nullable();
11268
1.32k
                        }
11269
1.38k
                        return GeodeticReferenceFrame::create(
11270
1.38k
                            grfMap.set(IdentifiedObject::NAME_KEY,
11271
1.38k
                                       title.empty()
11272
1.38k
                                           ? std::string(UNKNOWN_BASED_ON)
11273
1.22k
                                                 .append(proj_ellps[i].name)
11274
1.22k
                                                 .append(" ellipsoid")
11275
1.22k
                                                 .append(datumNameSuffix)
11276
1.38k
                                           : title),
11277
1.38k
                            NN_NO_CHECK(ellipsoid), optionalEmptyString, pm);
11278
1.38k
                    }
11279
20.8k
                }
11280
13
                throw ParsingException("unknown ellipsoid " + ellpsStr);
11281
1.40k
            }
11282
1.44k
        }();
11283
1.44k
        if (!numericParamPresent) {
11284
1.34k
            return l_datum;
11285
1.34k
        }
11286
104
        a = l_datum->ellipsoid()->semiMajorAxis().getSIValue();
11287
104
        if (l_datum->ellipsoid()->semiMinorAxis().has_value()) {
11288
35
            b = l_datum->ellipsoid()->semiMinorAxis()->getSIValue();
11289
69
        } else {
11290
69
            rf = l_datum->ellipsoid()->computedInverseFlattening();
11291
69
        }
11292
104
    }
11293
11294
14.8k
    if (!aStr.empty()) {
11295
558
        try {
11296
558
            a = c_locale_stod(aStr);
11297
558
        } catch (const std::invalid_argument &) {
11298
39
            throw ParsingException("Invalid a value");
11299
39
        }
11300
558
    }
11301
11302
14.7k
    const auto createGRF = [&grfMap, &title, &optionalEmptyString,
11303
14.7k
                            &datumNameSuffix,
11304
14.7k
                            &pm](const EllipsoidNNPtr &ellipsoid) {
11305
800
        std::string datumName(title);
11306
800
        if (title.empty()) {
11307
663
            if (ellipsoid->nameStr() != "unknown") {
11308
111
                datumName = UNKNOWN_BASED_ON;
11309
111
                datumName += ellipsoid->nameStr();
11310
111
                datumName += " ellipsoid";
11311
552
            } else {
11312
552
                datumName = "unknown";
11313
552
            }
11314
663
            datumName += datumNameSuffix;
11315
663
        }
11316
800
        return GeodeticReferenceFrame::create(
11317
800
            grfMap.set(IdentifiedObject::NAME_KEY, datumName), ellipsoid,
11318
800
            optionalEmptyString, fixupPrimeMeridan(ellipsoid, pm));
11319
800
    };
11320
11321
14.7k
    if (a > 0 && (b > 0 || !bStr.empty())) {
11322
153
        if (!bStr.empty()) {
11323
118
            try {
11324
118
                b = c_locale_stod(bStr);
11325
118
            } catch (const std::invalid_argument &) {
11326
7
                throw ParsingException("Invalid b value");
11327
7
            }
11328
118
        }
11329
146
        auto ellipsoid =
11330
146
            Ellipsoid::createTwoAxis(createMapWithUnknownName(), Length(a),
11331
146
                                     Length(b), guessBodyName(a))
11332
146
                ->identify();
11333
146
        return createGRF(ellipsoid);
11334
153
    }
11335
11336
14.6k
    else if (a > 0 && (rf >= 0 || !rfStr.empty())) {
11337
452
        if (!rfStr.empty()) {
11338
9
            try {
11339
9
                rf = c_locale_stod(rfStr);
11340
9
            } catch (const std::invalid_argument &) {
11341
5
                throw ParsingException("Invalid rf value");
11342
5
            }
11343
9
        }
11344
447
        auto ellipsoid = Ellipsoid::createFlattenedSphere(
11345
447
                             createMapWithUnknownName(), Length(a), Scale(rf),
11346
447
                             guessBodyName(a))
11347
447
                             ->identify();
11348
447
        return createGRF(ellipsoid);
11349
452
    }
11350
11351
14.1k
    else if (a > 0 && !fStr.empty()) {
11352
8
        double f;
11353
8
        try {
11354
8
            f = c_locale_stod(fStr);
11355
8
        } catch (const std::invalid_argument &) {
11356
3
            throw ParsingException("Invalid f value");
11357
3
        }
11358
5
        auto ellipsoid = Ellipsoid::createFlattenedSphere(
11359
5
                             createMapWithUnknownName(), Length(a),
11360
5
                             Scale(f != 0.0 ? 1.0 / f : 0.0), guessBodyName(a))
11361
5
                             ->identify();
11362
5
        return createGRF(ellipsoid);
11363
8
    }
11364
11365
14.1k
    else if (a > 0 && !eStr.empty()) {
11366
8
        double e;
11367
8
        try {
11368
8
            e = c_locale_stod(eStr);
11369
8
        } catch (const std::invalid_argument &) {
11370
4
            throw ParsingException("Invalid e value");
11371
4
        }
11372
4
        double alpha = asin(e);    /* angular eccentricity */
11373
4
        double f = 1 - cos(alpha); /* = 1 - sqrt (1 - es); */
11374
4
        auto ellipsoid = Ellipsoid::createFlattenedSphere(
11375
4
                             createMapWithUnknownName(), Length(a),
11376
4
                             Scale(f != 0.0 ? 1.0 / f : 0.0), guessBodyName(a))
11377
4
                             ->identify();
11378
4
        return createGRF(ellipsoid);
11379
8
    }
11380
11381
14.1k
    else if (a > 0 && !esStr.empty()) {
11382
0
        double es;
11383
0
        try {
11384
0
            es = c_locale_stod(esStr);
11385
0
        } catch (const std::invalid_argument &) {
11386
0
            throw ParsingException("Invalid es value");
11387
0
        }
11388
0
        double f = 1 - sqrt(1 - es);
11389
0
        auto ellipsoid = Ellipsoid::createFlattenedSphere(
11390
0
                             createMapWithUnknownName(), Length(a),
11391
0
                             Scale(f != 0.0 ? 1.0 / f : 0.0), guessBodyName(a))
11392
0
                             ->identify();
11393
0
        return createGRF(ellipsoid);
11394
0
    }
11395
11396
    // If only a is specified, create a sphere
11397
14.1k
    if (a > 0 && bStr.empty() && rfStr.empty() && eStr.empty() &&
11398
198
        esStr.empty()) {
11399
198
        auto ellipsoid = Ellipsoid::createSphere(createMapWithUnknownName(),
11400
198
                                                 Length(a), guessBodyName(a));
11401
198
        return createGRF(ellipsoid);
11402
198
    }
11403
11404
13.9k
    if (!bStr.empty() && aStr.empty()) {
11405
7
        throw ParsingException("b found, but a missing");
11406
7
    }
11407
11408
13.9k
    if (!rfStr.empty() && aStr.empty()) {
11409
1
        throw ParsingException("rf found, but a missing");
11410
1
    }
11411
11412
13.9k
    if (!fStr.empty() && aStr.empty()) {
11413
5
        throw ParsingException("f found, but a missing");
11414
5
    }
11415
11416
13.9k
    if (!eStr.empty() && aStr.empty()) {
11417
6
        throw ParsingException("e found, but a missing");
11418
6
    }
11419
11420
13.9k
    if (!esStr.empty() && aStr.empty()) {
11421
2
        throw ParsingException("es found, but a missing");
11422
2
    }
11423
11424
13.9k
    return overridePmIfNeeded(GeodeticReferenceFrame::EPSG_6326);
11425
13.9k
}
11426
11427
// ---------------------------------------------------------------------------
11428
11429
static const MeridianPtr nullMeridian{};
11430
11431
static CoordinateSystemAxisNNPtr
11432
createAxis(const std::string &name, const std::string &abbreviation,
11433
           const AxisDirection &direction, const common::UnitOfMeasure &unit,
11434
103k
           const MeridianPtr &meridian = nullMeridian) {
11435
103k
    return CoordinateSystemAxis::create(
11436
103k
        PropertyMap().set(IdentifiedObject::NAME_KEY, name), abbreviation,
11437
103k
        direction, unit, meridian);
11438
103k
}
11439
11440
std::vector<CoordinateSystemAxisNNPtr>
11441
PROJStringParser::Private::processAxisSwap(Step &step,
11442
                                           const UnitOfMeasure &unit,
11443
                                           int iAxisSwap, AxisType axisType,
11444
25.9k
                                           bool ignorePROJAxis) {
11445
25.9k
    assert(iAxisSwap < 0 || ci_equal(steps_[iAxisSwap].name, "axisswap"));
11446
11447
25.9k
    const bool isGeographic = unit.type() == UnitOfMeasure::Type::ANGULAR;
11448
25.9k
    const bool isSpherical = isGeographic && hasParamValue(step, "geoc");
11449
25.9k
    const auto &eastName = isSpherical    ? "Planetocentric longitude"
11450
25.9k
                           : isGeographic ? AxisName::Longitude
11451
25.7k
                                          : AxisName::Easting;
11452
25.9k
    const auto &eastAbbev = isSpherical    ? "V"
11453
25.9k
                            : isGeographic ? AxisAbbreviation::lon
11454
25.7k
                                           : AxisAbbreviation::E;
11455
25.9k
    const auto &eastDir =
11456
25.9k
        isGeographic                         ? AxisDirection::EAST
11457
25.9k
        : (axisType == AxisType::NORTH_POLE) ? AxisDirection::SOUTH
11458
8.69k
        : (axisType == AxisType::SOUTH_POLE) ? AxisDirection::NORTH
11459
8.66k
                                             : AxisDirection::EAST;
11460
25.9k
    CoordinateSystemAxisNNPtr east = createAxis(
11461
25.9k
        eastName, eastAbbev, eastDir, unit,
11462
25.9k
        (!isGeographic &&
11463
8.69k
         (axisType == AxisType::NORTH_POLE || axisType == AxisType::SOUTH_POLE))
11464
25.9k
            ? Meridian::create(Angle(90, UnitOfMeasure::DEGREE)).as_nullable()
11465
25.9k
            : nullMeridian);
11466
11467
25.9k
    const auto &northName = isSpherical    ? "Planetocentric latitude"
11468
25.9k
                            : isGeographic ? AxisName::Latitude
11469
25.7k
                                           : AxisName::Northing;
11470
25.9k
    const auto &northAbbev = isSpherical    ? "U"
11471
25.9k
                             : isGeographic ? AxisAbbreviation::lat
11472
25.7k
                                            : AxisAbbreviation::N;
11473
25.9k
    const auto &northDir = isGeographic ? AxisDirection::NORTH
11474
25.9k
                           : (axisType == AxisType::NORTH_POLE)
11475
8.69k
                               ? AxisDirection::SOUTH
11476
                               /*: (axisType == AxisType::SOUTH_POLE)
11477
                                     ? AxisDirection::NORTH*/
11478
8.69k
                               : AxisDirection::NORTH;
11479
25.9k
    const CoordinateSystemAxisNNPtr north = createAxis(
11480
25.9k
        northName, northAbbev, northDir, unit,
11481
25.9k
        isGeographic ? nullMeridian
11482
25.9k
        : (axisType == AxisType::NORTH_POLE)
11483
8.69k
            ? Meridian::create(Angle(180, UnitOfMeasure::DEGREE)).as_nullable()
11484
8.69k
        : (axisType == AxisType::SOUTH_POLE)
11485
8.66k
            ? Meridian::create(Angle(0, UnitOfMeasure::DEGREE)).as_nullable()
11486
8.66k
            : nullMeridian);
11487
11488
25.9k
    CoordinateSystemAxisNNPtr west =
11489
25.9k
        createAxis(isSpherical    ? "Planetocentric longitude"
11490
25.9k
                   : isGeographic ? AxisName::Longitude
11491
25.7k
                                  : AxisName::Westing,
11492
25.9k
                   isSpherical    ? "V"
11493
25.9k
                   : isGeographic ? AxisAbbreviation::lon
11494
25.7k
                                  : std::string(),
11495
25.9k
                   AxisDirection::WEST, unit);
11496
11497
25.9k
    CoordinateSystemAxisNNPtr south =
11498
25.9k
        createAxis(isSpherical    ? "Planetocentric latitude"
11499
25.9k
                   : isGeographic ? AxisName::Latitude
11500
25.7k
                                  : AxisName::Southing,
11501
25.9k
                   isSpherical    ? "U"
11502
25.9k
                   : isGeographic ? AxisAbbreviation::lat
11503
25.7k
                                  : std::string(),
11504
25.9k
                   AxisDirection::SOUTH, unit);
11505
11506
25.9k
    std::vector<CoordinateSystemAxisNNPtr> axis{east, north};
11507
11508
25.9k
    const auto &axisStr = getParamValue(step, "axis");
11509
25.9k
    if (!ignorePROJAxis && !axisStr.empty()) {
11510
419
        if (axisStr.size() == 3) {
11511
1.23k
            for (int i = 0; i < 2; i++) {
11512
837
                if (axisStr[i] == 'n') {
11513
182
                    axis[i] = north;
11514
655
                } else if (axisStr[i] == 's') {
11515
225
                    axis[i] = south;
11516
430
                } else if (axisStr[i] == 'e') {
11517
175
                    axis[i] = east;
11518
255
                } else if (axisStr[i] == 'w') {
11519
234
                    axis[i] = west;
11520
234
                } else {
11521
21
                    throw ParsingException("Unhandled axis=" + axisStr);
11522
21
                }
11523
837
            }
11524
419
        } else {
11525
0
            throw ParsingException("Unhandled axis=" + axisStr);
11526
0
        }
11527
25.5k
    } else if (iAxisSwap >= 0) {
11528
76
        auto &stepAxisSwap = steps_[iAxisSwap];
11529
76
        const auto &orderStr = getParamValue(stepAxisSwap, "order");
11530
76
        auto orderTab = split(orderStr, ',');
11531
76
        if (orderTab.size() != 2) {
11532
19
            throw ParsingException("Unhandled order=" + orderStr);
11533
19
        }
11534
57
        if (stepAxisSwap.inverted) {
11535
0
            throw ParsingException("Unhandled +inv for +proj=axisswap");
11536
0
        }
11537
11538
154
        for (size_t i = 0; i < 2; i++) {
11539
112
            if (orderTab[i] == "1") {
11540
6
                axis[i] = east;
11541
106
            } else if (orderTab[i] == "-1") {
11542
50
                axis[i] = west;
11543
56
            } else if (orderTab[i] == "2") {
11544
4
                axis[i] = north;
11545
52
            } else if (orderTab[i] == "-2") {
11546
37
                axis[i] = south;
11547
37
            } else {
11548
15
                throw ParsingException("Unhandled order=" + orderStr);
11549
15
            }
11550
112
        }
11551
25.4k
    } else if ((step.name == "krovak" || step.name == "mod_krovak") &&
11552
1.81k
               hasParamValue(step, "czech")) {
11553
76
        axis[0] = std::move(west);
11554
76
        axis[1] = std::move(south);
11555
76
    }
11556
25.8k
    return axis;
11557
25.9k
}
11558
11559
// ---------------------------------------------------------------------------
11560
11561
EllipsoidalCSNNPtr PROJStringParser::Private::buildEllipsoidalCS(
11562
17.0k
    int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis) {
11563
17.0k
    auto &step = steps_[iStep];
11564
17.0k
    assert(iUnitConvert < 0 ||
11565
17.0k
           ci_equal(steps_[iUnitConvert].name, "unitconvert"));
11566
11567
17.0k
    UnitOfMeasure angularUnit = UnitOfMeasure::DEGREE;
11568
17.0k
    if (iUnitConvert >= 0) {
11569
47
        auto &stepUnitConvert = steps_[iUnitConvert];
11570
47
        const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in");
11571
47
        const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out");
11572
47
        if (stepUnitConvert.inverted) {
11573
0
            std::swap(xy_in, xy_out);
11574
0
        }
11575
47
        if (iUnitConvert < iStep) {
11576
36
            std::swap(xy_in, xy_out);
11577
36
        }
11578
47
        if (xy_in->empty() || xy_out->empty() || *xy_in != "rad" ||
11579
40
            (*xy_out != "rad" && *xy_out != "deg" && *xy_out != "grad")) {
11580
40
            throw ParsingException("unhandled values for xy_in and/or xy_out");
11581
40
        }
11582
7
        if (*xy_out == "rad") {
11583
5
            angularUnit = UnitOfMeasure::RADIAN;
11584
5
        } else if (*xy_out == "grad") {
11585
2
            angularUnit = UnitOfMeasure::GRAD;
11586
2
        }
11587
7
    }
11588
11589
17.0k
    std::vector<CoordinateSystemAxisNNPtr> axis = processAxisSwap(
11590
17.0k
        step, angularUnit, iAxisSwap, AxisType::REGULAR, ignorePROJAxis);
11591
17.0k
    CoordinateSystemAxisNNPtr up = CoordinateSystemAxis::create(
11592
17.0k
        util::PropertyMap().set(IdentifiedObject::NAME_KEY,
11593
17.0k
                                AxisName::Ellipsoidal_height),
11594
17.0k
        AxisAbbreviation::h, AxisDirection::UP,
11595
17.0k
        buildUnit(step, "vunits", "vto_meter"));
11596
11597
17.0k
    return (!hasParamValue(step, "geoidgrids") &&
11598
10.2k
            (hasParamValue(step, "vunits") || hasParamValue(step, "vto_meter")))
11599
17.0k
               ? EllipsoidalCS::create(emptyPropertyMap, axis[0], axis[1], up)
11600
17.0k
               : EllipsoidalCS::create(emptyPropertyMap, axis[0], axis[1]);
11601
17.0k
}
11602
11603
// ---------------------------------------------------------------------------
11604
11605
SphericalCSNNPtr PROJStringParser::Private::buildSphericalCS(
11606
239
    int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis) {
11607
239
    auto &step = steps_[iStep];
11608
239
    assert(iUnitConvert < 0 ||
11609
239
           ci_equal(steps_[iUnitConvert].name, "unitconvert"));
11610
11611
239
    UnitOfMeasure angularUnit = UnitOfMeasure::DEGREE;
11612
239
    if (iUnitConvert >= 0) {
11613
32
        auto &stepUnitConvert = steps_[iUnitConvert];
11614
32
        const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in");
11615
32
        const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out");
11616
32
        if (stepUnitConvert.inverted) {
11617
0
            std::swap(xy_in, xy_out);
11618
0
        }
11619
32
        if (iUnitConvert < iStep) {
11620
26
            std::swap(xy_in, xy_out);
11621
26
        }
11622
32
        if (xy_in->empty() || xy_out->empty() || *xy_in != "rad" ||
11623
29
            (*xy_out != "rad" && *xy_out != "deg" && *xy_out != "grad")) {
11624
29
            throw ParsingException("unhandled values for xy_in and/or xy_out");
11625
29
        }
11626
3
        if (*xy_out == "rad") {
11627
0
            angularUnit = UnitOfMeasure::RADIAN;
11628
3
        } else if (*xy_out == "grad") {
11629
3
            angularUnit = UnitOfMeasure::GRAD;
11630
3
        }
11631
3
    }
11632
11633
210
    std::vector<CoordinateSystemAxisNNPtr> axis = processAxisSwap(
11634
210
        step, angularUnit, iAxisSwap, AxisType::REGULAR, ignorePROJAxis);
11635
11636
210
    return SphericalCS::create(emptyPropertyMap, axis[0], axis[1]);
11637
239
}
11638
11639
// ---------------------------------------------------------------------------
11640
11641
static double getNumericValue(const std::string &paramValue,
11642
4.31k
                              bool *pHasError = nullptr) {
11643
4.31k
    bool success;
11644
4.31k
    double value = c_locale_stod(paramValue, success);
11645
4.31k
    if (pHasError)
11646
448
        *pHasError = !success;
11647
4.31k
    return value;
11648
4.31k
}
11649
11650
// ---------------------------------------------------------------------------
11651
namespace {
11652
15.9k
template <class T> inline void ignoreRetVal(T) {}
11653
} // namespace
11654
11655
GeodeticCRSNNPtr PROJStringParser::Private::buildGeodeticCRS(
11656
15.9k
    int iStep, int iUnitConvert, int iAxisSwap, bool ignorePROJAxis) {
11657
15.9k
    auto &step = steps_[iStep];
11658
11659
15.9k
    const bool l_isGeographicStep = isGeographicStep(step.name);
11660
15.9k
    const auto &title = l_isGeographicStep ? title_ : emptyString;
11661
11662
    // units=m is often found in the wild.
11663
    // No need to create a extension string for this
11664
15.9k
    ignoreRetVal(hasParamValue(step, "units"));
11665
11666
15.9k
    auto datum = buildDatum(step, title);
11667
11668
15.9k
    auto props = PropertyMap().set(IdentifiedObject::NAME_KEY,
11669
15.9k
                                   title.empty() ? "unknown" : title);
11670
11671
15.9k
    if (l_isGeographicStep &&
11672
7.23k
        (hasUnusedParameters(step) ||
11673
5.06k
         getNumericValue(getParamValue(step, "lon_0")) != 0.0)) {
11674
5.06k
        props.set("EXTENSION_PROJ4", projString_);
11675
5.06k
    }
11676
15.9k
    props.set("IMPLICIT_CS", true);
11677
11678
15.9k
    if (!hasParamValue(step, "geoc")) {
11679
15.5k
        auto cs =
11680
15.5k
            buildEllipsoidalCS(iStep, iUnitConvert, iAxisSwap, ignorePROJAxis);
11681
11682
15.5k
        return GeographicCRS::create(props, datum, cs);
11683
15.5k
    } else {
11684
365
        auto cs =
11685
365
            buildSphericalCS(iStep, iUnitConvert, iAxisSwap, ignorePROJAxis);
11686
11687
365
        return GeodeticCRS::create(props, datum, cs);
11688
365
    }
11689
15.9k
}
11690
11691
// ---------------------------------------------------------------------------
11692
11693
GeodeticCRSNNPtr
11694
2.44k
PROJStringParser::Private::buildGeocentricCRS(int iStep, int iUnitConvert) {
11695
2.44k
    auto &step = steps_[iStep];
11696
11697
2.44k
    assert(isGeocentricStep(step.name) || isTopocentricStep(step.name));
11698
2.44k
    assert(iUnitConvert < 0 ||
11699
2.44k
           ci_equal(steps_[iUnitConvert].name, "unitconvert"));
11700
11701
2.44k
    const auto &title = title_;
11702
11703
2.44k
    auto datum = buildDatum(step, title);
11704
11705
2.44k
    UnitOfMeasure unit = buildUnit(step, "units", "");
11706
2.44k
    if (iUnitConvert >= 0) {
11707
27
        auto &stepUnitConvert = steps_[iUnitConvert];
11708
27
        const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in");
11709
27
        const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out");
11710
27
        const std::string *z_in = &getParamValue(stepUnitConvert, "z_in");
11711
27
        const std::string *z_out = &getParamValue(stepUnitConvert, "z_out");
11712
27
        if (stepUnitConvert.inverted) {
11713
0
            std::swap(xy_in, xy_out);
11714
0
            std::swap(z_in, z_out);
11715
0
        }
11716
27
        if (xy_in->empty() || xy_out->empty() || *xy_in != "m" ||
11717
27
            *z_in != "m" || *xy_out != *z_out) {
11718
27
            throw ParsingException(
11719
27
                "unhandled values for xy_in, z_in, xy_out or z_out");
11720
27
        }
11721
11722
0
        const LinearUnitDesc *unitsMatch = nullptr;
11723
0
        try {
11724
0
            double to_meter_value = c_locale_stod(*xy_out);
11725
0
            unitsMatch = getLinearUnits(to_meter_value);
11726
0
            if (unitsMatch == nullptr) {
11727
0
                unit = _buildUnit(to_meter_value);
11728
0
            }
11729
0
        } catch (const std::invalid_argument &) {
11730
0
            unitsMatch = getLinearUnits(*xy_out);
11731
0
            if (!unitsMatch) {
11732
0
                throw ParsingException(
11733
0
                    "unhandled values for xy_in, z_in, xy_out or z_out");
11734
0
            }
11735
0
            unit = _buildUnit(unitsMatch);
11736
0
        }
11737
0
    }
11738
11739
2.41k
    auto props = PropertyMap().set(IdentifiedObject::NAME_KEY,
11740
2.41k
                                   title.empty() ? "unknown" : title);
11741
2.41k
    auto cs = CartesianCS::createGeocentric(unit);
11742
11743
2.41k
    if (hasUnusedParameters(step)) {
11744
84
        props.set("EXTENSION_PROJ4", projString_);
11745
84
    }
11746
11747
2.41k
    return GeodeticCRS::create(props, datum, cs);
11748
2.44k
}
11749
11750
// ---------------------------------------------------------------------------
11751
11752
CRSNNPtr
11753
PROJStringParser::Private::buildBoundOrCompoundCRSIfNeeded(int iStep,
11754
17.8k
                                                           CRSNNPtr crs) {
11755
17.8k
    auto &step = steps_[iStep];
11756
17.8k
    const auto &nadgrids = getParamValue(step, "nadgrids");
11757
17.8k
    const auto &towgs84 = getParamValue(step, "towgs84");
11758
    // nadgrids has the priority over towgs84
11759
17.8k
    if (!ignoreNadgrids_ && !nadgrids.empty()) {
11760
1.54k
        crs = BoundCRS::createFromNadgrids(crs, nadgrids);
11761
16.2k
    } else if (!towgs84.empty()) {
11762
1.17k
        std::vector<double> towgs84Values;
11763
1.17k
        const auto tokens = split(towgs84, ',');
11764
3.67k
        for (const auto &str : tokens) {
11765
3.67k
            try {
11766
3.67k
                towgs84Values.push_back(c_locale_stod(str));
11767
3.67k
            } catch (const std::invalid_argument &) {
11768
126
                throw ParsingException("Non numerical value in towgs84 clause");
11769
126
            }
11770
3.67k
        }
11771
11772
1.04k
        if (towgs84Values.size() == 7 && dbContext_) {
11773
6
            if (dbContext_->toWGS84AutocorrectWrongValues(
11774
6
                    towgs84Values[0], towgs84Values[1], towgs84Values[2],
11775
6
                    towgs84Values[3], towgs84Values[4], towgs84Values[5],
11776
6
                    towgs84Values[6])) {
11777
0
                for (auto &pair : step.paramValues) {
11778
0
                    if (ci_equal(pair.key, "towgs84")) {
11779
0
                        pair.value.clear();
11780
0
                        for (int i = 0; i < 7; ++i) {
11781
0
                            if (i > 0)
11782
0
                                pair.value += ',';
11783
0
                            pair.value += internal::toString(towgs84Values[i]);
11784
0
                        }
11785
0
                        break;
11786
0
                    }
11787
0
                }
11788
0
            }
11789
6
        }
11790
11791
1.04k
        crs = BoundCRS::createFromTOWGS84(crs, towgs84Values);
11792
1.04k
    }
11793
11794
17.6k
    const auto &geoidgrids = getParamValue(step, "geoidgrids");
11795
17.6k
    if (!geoidgrids.empty()) {
11796
6.54k
        auto vdatum = VerticalReferenceFrame::create(
11797
6.54k
            PropertyMap().set(common::IdentifiedObject::NAME_KEY,
11798
6.54k
                              "unknown using geoidgrids=" + geoidgrids));
11799
11800
6.54k
        const UnitOfMeasure unit = buildUnit(step, "vunits", "vto_meter");
11801
11802
6.54k
        auto vcrs =
11803
6.54k
            VerticalCRS::create(createMapWithUnknownName(), vdatum,
11804
6.54k
                                VerticalCS::createGravityRelatedHeight(unit));
11805
11806
6.54k
        CRSNNPtr geogCRS = GeographicCRS::EPSG_4979; // default
11807
6.54k
        const auto &geoid_crs = getParamValue(step, "geoid_crs");
11808
6.54k
        if (!geoid_crs.empty()) {
11809
2.07k
            if (geoid_crs == "WGS84") {
11810
                // nothing to do
11811
2.07k
            } else if (geoid_crs == "horizontal_crs") {
11812
2.03k
                auto geogCRSOfCompoundCRS = crs->extractGeographicCRS();
11813
2.03k
                if (geogCRSOfCompoundCRS &&
11814
2.02k
                    geogCRSOfCompoundCRS->primeMeridian()
11815
2.02k
                            ->longitude()
11816
2.02k
                            .getSIValue() == 0 &&
11817
1.98k
                    geogCRSOfCompoundCRS->coordinateSystem()
11818
1.98k
                            ->axisList()[0]
11819
1.98k
                            ->unit() == UnitOfMeasure::DEGREE) {
11820
1.98k
                    geogCRS = geogCRSOfCompoundCRS->promoteTo3D(std::string(),
11821
1.98k
                                                                nullptr);
11822
1.98k
                } else if (geogCRSOfCompoundCRS) {
11823
46
                    auto geogCRSOfCompoundCRSDatum =
11824
46
                        geogCRSOfCompoundCRS->datumNonNull(nullptr);
11825
46
                    geogCRS = GeographicCRS::create(
11826
46
                        createMapWithUnknownName(),
11827
46
                        datum::GeodeticReferenceFrame::create(
11828
46
                            util::PropertyMap().set(
11829
46
                                common::IdentifiedObject::NAME_KEY,
11830
46
                                geogCRSOfCompoundCRSDatum->nameStr() +
11831
46
                                    " (with Greenwich prime meridian)"),
11832
46
                            geogCRSOfCompoundCRSDatum->ellipsoid(),
11833
46
                            util::optional<std::string>(),
11834
46
                            datum::PrimeMeridian::GREENWICH),
11835
46
                        EllipsoidalCS::createLongitudeLatitudeEllipsoidalHeight(
11836
46
                            UnitOfMeasure::DEGREE, UnitOfMeasure::METRE));
11837
46
                }
11838
2.03k
            } else {
11839
48
                throw ParsingException("Unsupported value for geoid_crs: "
11840
48
                                       "should be 'WGS84' or 'horizontal_crs'");
11841
48
            }
11842
2.07k
        }
11843
6.49k
        auto transformation =
11844
6.49k
            Transformation::createGravityRelatedHeightToGeographic3D(
11845
6.49k
                PropertyMap().set(IdentifiedObject::NAME_KEY,
11846
6.49k
                                  "unknown to " + geogCRS->nameStr() +
11847
6.49k
                                      " ellipsoidal height"),
11848
6.49k
                VerticalCRS::create(createMapWithUnknownName(), vdatum,
11849
6.49k
                                    VerticalCS::createGravityRelatedHeight(
11850
6.49k
                                        common::UnitOfMeasure::METRE)),
11851
6.49k
                geogCRS, nullptr, geoidgrids,
11852
6.49k
                std::vector<PositionalAccuracyNNPtr>());
11853
6.49k
        auto boundvcrs = BoundCRS::create(vcrs, geogCRS, transformation);
11854
11855
6.49k
        crs = CompoundCRS::create(createMapWithUnknownName(),
11856
6.49k
                                  std::vector<CRSNNPtr>{crs, boundvcrs});
11857
6.49k
    }
11858
11859
17.6k
    return crs;
11860
17.6k
}
11861
11862
// ---------------------------------------------------------------------------
11863
11864
static double getAngularValue(const std::string &paramValue,
11865
2.72k
                              bool *pHasError = nullptr) {
11866
2.72k
    char *endptr = nullptr;
11867
2.72k
    double value = dmstor(paramValue.c_str(), &endptr) * RAD_TO_DEG;
11868
2.72k
    if (value == HUGE_VAL || endptr != paramValue.c_str() + paramValue.size()) {
11869
215
        if (pHasError)
11870
172
            *pHasError = true;
11871
215
        return 0.0;
11872
215
    }
11873
2.51k
    if (pHasError)
11874
2.36k
        *pHasError = false;
11875
2.51k
    return value;
11876
2.72k
}
11877
11878
// ---------------------------------------------------------------------------
11879
11880
28.6k
static bool is_in_stringlist(const std::string &str, const char *stringlist) {
11881
28.6k
    if (str.empty())
11882
729
        return false;
11883
27.9k
    const char *haystack = stringlist;
11884
282k
    while (true) {
11885
282k
        const char *res = strstr(haystack, str.c_str());
11886
282k
        if (res == nullptr)
11887
24.1k
            return false;
11888
258k
        if ((res == stringlist || res[-1] == ',') &&
11889
90.0k
            (res[str.size()] == ',' || res[str.size()] == '\0'))
11890
3.74k
            return true;
11891
254k
        haystack += str.size();
11892
254k
    }
11893
27.9k
}
11894
11895
// ---------------------------------------------------------------------------
11896
11897
CRSNNPtr
11898
PROJStringParser::Private::buildProjectedCRS(int iStep,
11899
                                             const GeodeticCRSNNPtr &geodCRS,
11900
10.4k
                                             int iUnitConvert, int iAxisSwap) {
11901
10.4k
    auto &step = steps_[iStep];
11902
10.4k
    const auto mappings = getMappingsFromPROJName(step.name);
11903
10.4k
    const MethodMapping *mapping = mappings.empty() ? nullptr : mappings[0];
11904
11905
10.4k
    bool foundStrictlyMatchingMapping = false;
11906
10.4k
    if (mappings.size() >= 2) {
11907
        // To distinguish for example +ortho from +ortho +f=0
11908
2.44k
        bool allMappingsHaveAuxParam = true;
11909
6.05k
        for (const auto *mappingIter : mappings) {
11910
6.05k
            if (mappingIter->proj_name_aux == nullptr) {
11911
3.92k
                allMappingsHaveAuxParam = false;
11912
3.92k
            }
11913
6.05k
            if (mappingIter->proj_name_aux != nullptr &&
11914
2.13k
                strchr(mappingIter->proj_name_aux, '=') == nullptr &&
11915
617
                hasParamValue(step, mappingIter->proj_name_aux)) {
11916
40
                foundStrictlyMatchingMapping = true;
11917
40
                mapping = mappingIter;
11918
40
                break;
11919
6.01k
            } else if (mappingIter->proj_name_aux != nullptr &&
11920
2.09k
                       strchr(mappingIter->proj_name_aux, '=') != nullptr) {
11921
1.51k
                const auto tokens = split(mappingIter->proj_name_aux, '=');
11922
1.51k
                if (tokens.size() == 2 &&
11923
1.51k
                    getParamValue(step, tokens[0]) == tokens[1]) {
11924
73
                    foundStrictlyMatchingMapping = true;
11925
73
                    mapping = mappingIter;
11926
73
                    break;
11927
73
                }
11928
1.51k
            }
11929
6.05k
        }
11930
2.44k
        if (allMappingsHaveAuxParam && !foundStrictlyMatchingMapping) {
11931
70
            mapping = nullptr;
11932
70
        }
11933
2.44k
    }
11934
11935
10.4k
    if (mapping && !foundStrictlyMatchingMapping) {
11936
4.12k
        mapping = selectSphericalOrEllipsoidal(mapping, geodCRS);
11937
4.12k
    }
11938
11939
10.4k
    assert(isProjectedStep(step.name));
11940
10.4k
    assert(iUnitConvert < 0 ||
11941
10.4k
           ci_equal(steps_[iUnitConvert].name, "unitconvert"));
11942
11943
10.4k
    const auto &title = title_;
11944
11945
10.4k
    if (!buildPrimeMeridian(step)->longitude()._isEquivalentTo(
11946
10.4k
            geodCRS->primeMeridian()->longitude(),
11947
10.4k
            util::IComparable::Criterion::EQUIVALENT)) {
11948
1
        throw ParsingException("inconsistent pm values between projectedCRS "
11949
1
                               "and its base geographicalCRS");
11950
1
    }
11951
11952
10.4k
    auto axisType = AxisType::REGULAR;
11953
10.4k
    bool bWebMercator = false;
11954
10.4k
    std::string webMercatorName("WGS 84 / Pseudo-Mercator");
11955
11956
10.4k
    if (step.name == "tmerc" &&
11957
353
        ((getParamValue(step, "axis") == "wsu" && iAxisSwap < 0) ||
11958
332
         (iAxisSwap > 0 &&
11959
67
          getParamValue(steps_[iAxisSwap], "order") == "-1,-2"))) {
11960
36
        mapping =
11961
36
            getMapping(EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED);
11962
10.4k
    } else if (step.name == "etmerc") {
11963
5
        mapping = getMapping(EPSG_CODE_METHOD_TRANSVERSE_MERCATOR);
11964
10.4k
    } else if (step.name == "lcc") {
11965
83
        const auto &lat_0 = getParamValue(step, "lat_0");
11966
83
        const auto &lat_1 = getParamValue(step, "lat_1");
11967
83
        const auto &lat_2 = getParamValue(step, "lat_2");
11968
83
        const auto &k = getParamValueK(step);
11969
83
        if (lat_2.empty() && !lat_0.empty() && !lat_1.empty()) {
11970
5
            if (lat_0 == lat_1 ||
11971
                // For some reason with gcc 5.3.1-14ubuntu2 32bit, the following
11972
                // comparison returns false even if lat_0 == lat_1. Smells like
11973
                // a compiler bug
11974
5
                getAngularValue(lat_0) == getAngularValue(lat_1)) {
11975
2
                mapping =
11976
2
                    getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP);
11977
3
            } else {
11978
3
                mapping = getMapping(
11979
3
                    EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_1SP_VARIANT_B);
11980
3
            }
11981
78
        } else if (!k.empty() && getNumericValue(k) != 1.0) {
11982
8
            mapping = getMapping(
11983
8
                EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP_MICHIGAN);
11984
70
        } else {
11985
70
            mapping = getMapping(EPSG_CODE_METHOD_LAMBERT_CONIC_CONFORMAL_2SP);
11986
70
        }
11987
10.3k
    } else if (step.name == "aeqd" && hasParamValue(step, "guam")) {
11988
15
        mapping = getMapping(EPSG_CODE_METHOD_GUAM_PROJECTION);
11989
10.3k
    } else if (step.name == "geos" && getParamValue(step, "sweep") == "x") {
11990
16
        mapping =
11991
16
            getMapping(PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_X);
11992
10.3k
    } else if (step.name == "geos") {
11993
7
        mapping =
11994
7
            getMapping(PROJ_WKT2_NAME_METHOD_GEOSTATIONARY_SATELLITE_SWEEP_Y);
11995
10.3k
    } else if (step.name == "omerc") {
11996
59
        if (hasParamValue(step, "no_rot")) {
11997
0
            mapping = nullptr;
11998
59
        } else if (hasParamValue(step, "no_uoff") ||
11999
59
                   hasParamValue(step, "no_off")) {
12000
5
            mapping =
12001
5
                getMapping(EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_A);
12002
54
        } else if (hasParamValue(step, "lat_1") &&
12003
46
                   hasParamValue(step, "lon_1") &&
12004
15
                   hasParamValue(step, "lat_2") &&
12005
5
                   hasParamValue(step, "lon_2")) {
12006
0
            mapping = getMapping(
12007
0
                PROJ_WKT2_NAME_METHOD_HOTINE_OBLIQUE_MERCATOR_TWO_POINT_NATURAL_ORIGIN);
12008
54
        } else {
12009
54
            mapping =
12010
54
                getMapping(EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B);
12011
54
        }
12012
10.2k
    } else if (step.name == "somerc") {
12013
48
        mapping =
12014
48
            getMapping(EPSG_CODE_METHOD_HOTINE_OBLIQUE_MERCATOR_VARIANT_B);
12015
48
        if (!hasParamValue(step, "alpha") && !hasParamValue(step, "gamma") &&
12016
27
            !hasParamValue(step, "lonc")) {
12017
27
            step.paramValues.emplace_back(Step::KeyValue("alpha", "90"));
12018
27
            step.paramValues.emplace_back(Step::KeyValue("gamma", "90"));
12019
27
            step.paramValues.emplace_back(
12020
27
                Step::KeyValue("lonc", getParamValue(step, "lon_0")));
12021
27
        }
12022
10.2k
    } else if (step.name == "krovak" &&
12023
811
               ((iAxisSwap < 0 && getParamValue(step, "axis") == "swu" &&
12024
16
                 !hasParamValue(step, "czech")) ||
12025
795
                (iAxisSwap > 0 &&
12026
0
                 getParamValue(steps_[iAxisSwap], "order") == "-2,-1" &&
12027
16
                 !hasParamValue(step, "czech")))) {
12028
16
        mapping = getMapping(EPSG_CODE_METHOD_KROVAK);
12029
10.1k
    } else if (step.name == "krovak" && iAxisSwap < 0 &&
12030
795
               hasParamValue(step, "czech") && !hasParamValue(step, "axis")) {
12031
4
        mapping = getMapping(EPSG_CODE_METHOD_KROVAK);
12032
10.1k
    } else if (step.name == "mod_krovak" &&
12033
119
               ((iAxisSwap < 0 && getParamValue(step, "axis") == "swu" &&
12034
2
                 !hasParamValue(step, "czech")) ||
12035
117
                (iAxisSwap > 0 &&
12036
0
                 getParamValue(steps_[iAxisSwap], "order") == "-2,-1" &&
12037
2
                 !hasParamValue(step, "czech")))) {
12038
2
        mapping = getMapping(EPSG_CODE_METHOD_KROVAK_MODIFIED);
12039
10.1k
    } else if (step.name == "mod_krovak" && iAxisSwap < 0 &&
12040
117
               hasParamValue(step, "czech") && !hasParamValue(step, "axis")) {
12041
33
        mapping = getMapping(EPSG_CODE_METHOD_KROVAK_MODIFIED);
12042
10.1k
    } else if (step.name == "merc") {
12043
160
        if (hasParamValue(step, "a") && hasParamValue(step, "b") &&
12044
4
            getParamValue(step, "a") == getParamValue(step, "b") &&
12045
4
            (!hasParamValue(step, "lat_ts") ||
12046
0
             getAngularValue(getParamValue(step, "lat_ts")) == 0.0) &&
12047
4
            getNumericValue(getParamValueK(step)) == 1.0 &&
12048
0
            getParamValue(step, "nadgrids") == "@null") {
12049
0
            mapping = getMapping(
12050
0
                EPSG_CODE_METHOD_POPULAR_VISUALISATION_PSEUDO_MERCATOR);
12051
0
            for (size_t i = 0; i < step.paramValues.size(); ++i) {
12052
0
                if (ci_equal(step.paramValues[i].key, "nadgrids")) {
12053
0
                    ignoreNadgrids_ = true;
12054
0
                    break;
12055
0
                }
12056
0
            }
12057
0
            if (getNumericValue(getParamValue(step, "a")) == 6378137 &&
12058
0
                getAngularValue(getParamValue(step, "lon_0")) == 0.0 &&
12059
0
                getAngularValue(getParamValue(step, "lat_0")) == 0.0 &&
12060
0
                getAngularValue(getParamValue(step, "x_0")) == 0.0 &&
12061
0
                getAngularValue(getParamValue(step, "y_0")) == 0.0) {
12062
0
                bWebMercator = true;
12063
0
                if (hasParamValue(step, "units") &&
12064
0
                    getParamValue(step, "units") != "m") {
12065
0
                    webMercatorName +=
12066
0
                        " (unit " + getParamValue(step, "units") + ')';
12067
0
                }
12068
0
            }
12069
160
        } else if (hasParamValue(step, "lat_ts")) {
12070
21
            if (hasParamValue(step, "R_C") &&
12071
4
                !geodCRS->ellipsoid()->isSphere() &&
12072
4
                getAngularValue(getParamValue(step, "lat_ts")) != 0) {
12073
0
                throw ParsingException("lat_ts != 0 not supported for "
12074
0
                                       "spherical Mercator on an ellipsoid");
12075
0
            }
12076
21
            mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_VARIANT_B);
12077
139
        } else if (hasParamValue(step, "R_C")) {
12078
16
            const auto &k = getParamValueK(step);
12079
16
            if (!k.empty() && getNumericValue(k) != 1.0) {
12080
4
                if (geodCRS->ellipsoid()->isSphere()) {
12081
0
                    mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_VARIANT_A);
12082
4
                } else {
12083
4
                    throw ParsingException(
12084
4
                        "k_0 != 1 not supported for spherical Mercator on an "
12085
4
                        "ellipsoid");
12086
4
                }
12087
12
            } else {
12088
12
                mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_SPHERICAL);
12089
12
            }
12090
123
        } else {
12091
123
            mapping = getMapping(EPSG_CODE_METHOD_MERCATOR_VARIANT_A);
12092
123
        }
12093
9.98k
    } else if (step.name == "stere") {
12094
255
        if (hasParamValue(step, "lat_0") &&
12095
79
            std::fabs(std::fabs(getAngularValue(getParamValue(step, "lat_0"))) -
12096
79
                      90.0) < 1e-10) {
12097
54
            const double lat_0 = getAngularValue(getParamValue(step, "lat_0"));
12098
54
            if (lat_0 > 0) {
12099
50
                axisType = AxisType::NORTH_POLE;
12100
50
            } else {
12101
4
                axisType = AxisType::SOUTH_POLE;
12102
4
            }
12103
54
            const auto &lat_ts = getParamValue(step, "lat_ts");
12104
54
            const auto &k = getParamValueK(step);
12105
54
            if (!lat_ts.empty() &&
12106
27
                std::fabs(getAngularValue(lat_ts) - lat_0) > 1e-10 &&
12107
24
                !k.empty() && std::fabs(getNumericValue(k) - 1) > 1e-10) {
12108
6
                throw ParsingException("lat_ts != lat_0 and k != 1 not "
12109
6
                                       "supported for Polar Stereographic");
12110
6
            }
12111
48
            if (!lat_ts.empty() &&
12112
21
                (k.empty() || std::fabs(getNumericValue(k) - 1) < 1e-10)) {
12113
18
                mapping =
12114
18
                    getMapping(EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_B);
12115
30
            } else {
12116
30
                mapping =
12117
30
                    getMapping(EPSG_CODE_METHOD_POLAR_STEREOGRAPHIC_VARIANT_A);
12118
30
            }
12119
201
        } else {
12120
201
            mapping = getMapping(PROJ_WKT2_NAME_METHOD_STEREOGRAPHIC);
12121
201
        }
12122
9.73k
    } else if (step.name == "laea") {
12123
196
        if (hasParamValue(step, "lat_0") &&
12124
13
            std::fabs(std::fabs(getAngularValue(getParamValue(step, "lat_0"))) -
12125
13
                      90.0) < 1e-10) {
12126
4
            const double lat_0 = getAngularValue(getParamValue(step, "lat_0"));
12127
4
            if (lat_0 > 0) {
12128
4
                axisType = AxisType::NORTH_POLE;
12129
4
            } else {
12130
0
                axisType = AxisType::SOUTH_POLE;
12131
0
            }
12132
4
        }
12133
9.53k
    } else if (step.name == "ortho") {
12134
37
        const std::string &k = getParamValueK(step);
12135
37
        if ((!k.empty() && getNumericValue(k) != 1.0) ||
12136
37
            (hasParamValue(step, "alpha") &&
12137
8
             getNumericValue(getParamValue(step, "alpha")) != 0.0)) {
12138
6
            mapping = getMapping(EPSG_CODE_METHOD_LOCAL_ORTHOGRAPHIC);
12139
6
        }
12140
37
    }
12141
12142
10.4k
    UnitOfMeasure unit = buildUnit(step, "units", "to_meter");
12143
10.4k
    if (iUnitConvert >= 0) {
12144
25
        auto &stepUnitConvert = steps_[iUnitConvert];
12145
25
        const std::string *xy_in = &getParamValue(stepUnitConvert, "xy_in");
12146
25
        const std::string *xy_out = &getParamValue(stepUnitConvert, "xy_out");
12147
25
        if (stepUnitConvert.inverted) {
12148
0
            std::swap(xy_in, xy_out);
12149
0
        }
12150
25
        if (xy_in->empty() || xy_out->empty() || *xy_in != "m") {
12151
25
            if (step.name != "ob_tran") {
12152
20
                throw ParsingException(
12153
20
                    "unhandled values for xy_in and/or xy_out");
12154
20
            }
12155
25
        }
12156
12157
5
        const LinearUnitDesc *unitsMatch = nullptr;
12158
5
        try {
12159
5
            double to_meter_value = c_locale_stod(*xy_out);
12160
5
            unitsMatch = getLinearUnits(to_meter_value);
12161
5
            if (unitsMatch == nullptr) {
12162
0
                unit = _buildUnit(to_meter_value);
12163
0
            }
12164
5
        } catch (const std::invalid_argument &) {
12165
5
            unitsMatch = getLinearUnits(*xy_out);
12166
5
            if (!unitsMatch) {
12167
5
                if (step.name != "ob_tran") {
12168
0
                    throw ParsingException(
12169
0
                        "unhandled values for xy_in and/or xy_out");
12170
0
                }
12171
5
            } else {
12172
0
                unit = _buildUnit(unitsMatch);
12173
0
            }
12174
5
        }
12175
5
    }
12176
12177
10.4k
    ConversionPtr conv;
12178
12179
10.4k
    auto mapWithUnknownName = createMapWithUnknownName();
12180
12181
10.4k
    if (step.name == "utm") {
12182
63
        const int zone = std::atoi(getParamValue(step, "zone").c_str());
12183
63
        const bool north = !hasParamValue(step, "south");
12184
63
        conv =
12185
63
            Conversion::createUTM(emptyPropertyMap, zone, north).as_nullable();
12186
10.3k
    } else if (mapping) {
12187
12188
4.26k
        auto methodMap =
12189
4.26k
            PropertyMap().set(IdentifiedObject::NAME_KEY, mapping->wkt2_name);
12190
4.26k
        if (mapping->epsg_code) {
12191
2.23k
            methodMap.set(Identifier::CODESPACE_KEY, Identifier::EPSG)
12192
2.23k
                .set(Identifier::CODE_KEY, mapping->epsg_code);
12193
2.23k
        }
12194
4.26k
        std::vector<OperationParameterNNPtr> parameters;
12195
4.26k
        std::vector<ParameterValueNNPtr> values;
12196
24.3k
        for (int i = 0; mapping->params[i] != nullptr; i++) {
12197
20.2k
            const auto *param = mapping->params[i];
12198
20.2k
            std::string proj_name(param->proj_name ? param->proj_name : "");
12199
20.2k
            const std::string *paramValue =
12200
20.2k
                (proj_name == "k" || proj_name == "k_0") ? &getParamValueK(step)
12201
20.2k
                : !proj_name.empty() ? &getParamValue(step, proj_name)
12202
18.4k
                                     : &emptyString;
12203
20.2k
            double value = 0;
12204
20.2k
            if (!paramValue->empty()) {
12205
441
                bool hasError = false;
12206
441
                if (param->unit_type == UnitOfMeasure::Type::ANGULAR) {
12207
350
                    value = getAngularValue(*paramValue, &hasError);
12208
350
                } else {
12209
91
                    value = getNumericValue(*paramValue, &hasError);
12210
91
                }
12211
441
                if (hasError) {
12212
101
                    throw ParsingException("invalid value for " + proj_name);
12213
101
                }
12214
441
            }
12215
            // For omerc, if gamma is missing, the default value is
12216
            // alpha
12217
19.7k
            else if (step.name == "omerc" && proj_name == "gamma") {
12218
54
                paramValue = &getParamValue(step, "alpha");
12219
54
                if (!paramValue->empty()) {
12220
0
                    value = getAngularValue(*paramValue);
12221
0
                }
12222
19.7k
            } else if (step.name == "krovak" || step.name == "mod_krovak") {
12223
                // Keep it in sync with defaults of krovak.cpp
12224
6.44k
                if (param->epsg_code ==
12225
6.44k
                    EPSG_CODE_PARAMETER_LATITUDE_PROJECTION_CENTRE) {
12226
926
                    value = 49.5;
12227
5.51k
                } else if (param->epsg_code ==
12228
5.51k
                           EPSG_CODE_PARAMETER_LONGITUDE_OF_ORIGIN) {
12229
921
                    value = 24.833333333333333333;
12230
4.59k
                } else if (param->epsg_code ==
12231
4.59k
                           EPSG_CODE_PARAMETER_COLATITUDE_CONE_AXIS) {
12232
922
                    value = 30.28813975277777776;
12233
3.67k
                } else if (
12234
3.67k
                    param->epsg_code ==
12235
3.67k
                    EPSG_CODE_PARAMETER_LATITUDE_PSEUDO_STANDARD_PARALLEL) {
12236
922
                    value = 78.5;
12237
2.74k
                } else if (
12238
2.74k
                    param->epsg_code ==
12239
2.74k
                    EPSG_CODE_PARAMETER_SCALE_FACTOR_PSEUDO_STANDARD_PARALLEL) {
12240
919
                    value = 0.9999;
12241
919
                }
12242
13.2k
            } else if (step.name == "cea" && proj_name == "lat_ts") {
12243
121
                paramValue = &getParamValueK(step);
12244
121
                if (!paramValue->empty()) {
12245
11
                    bool hasError = false;
12246
11
                    const double k = getNumericValue(*paramValue, &hasError);
12247
11
                    if (hasError) {
12248
5
                        throw ParsingException("invalid value for k/k_0");
12249
5
                    }
12250
6
                    if (k >= 0 && k <= 1) {
12251
5
                        const double es =
12252
5
                            geodCRS->ellipsoid()->squaredEccentricity();
12253
5
                        if (es < 0 || es == 1) {
12254
0
                            throw ParsingException("Invalid flattening");
12255
0
                        }
12256
5
                        value =
12257
5
                            Angle(acos(k * sqrt((1 - es) / (1 - k * k * es))),
12258
5
                                  UnitOfMeasure::RADIAN)
12259
5
                                .convertToUnit(UnitOfMeasure::DEGREE);
12260
5
                    } else {
12261
1
                        throw ParsingException("k/k_0 should be in [0,1]");
12262
1
                    }
12263
6
                }
12264
13.1k
            } else if (param->unit_type == UnitOfMeasure::Type::SCALE) {
12265
838
                value = 1;
12266
12.3k
            } else if (step.name == "peirce_q" && proj_name == "lat_0") {
12267
18
                value = 90;
12268
18
            }
12269
12270
20.0k
            PropertyMap propertiesParameter;
12271
20.0k
            propertiesParameter.set(IdentifiedObject::NAME_KEY,
12272
20.0k
                                    param->wkt2_name);
12273
20.0k
            if (param->epsg_code) {
12274
19.4k
                propertiesParameter.set(Identifier::CODE_KEY, param->epsg_code);
12275
19.4k
                propertiesParameter.set(Identifier::CODESPACE_KEY,
12276
19.4k
                                        Identifier::EPSG);
12277
19.4k
            }
12278
20.0k
            parameters.push_back(
12279
20.0k
                OperationParameter::create(propertiesParameter));
12280
            // In PROJ convention, angular parameters are always in degree
12281
            // and linear parameters always in metre.
12282
20.0k
            double valRounded =
12283
20.0k
                param->unit_type == UnitOfMeasure::Type::LINEAR
12284
20.0k
                    ? Length(value, UnitOfMeasure::METRE).convertToUnit(unit)
12285
20.0k
                    : value;
12286
20.0k
            if (std::fabs(valRounded - std::round(valRounded)) < 1e-8) {
12287
15.4k
                valRounded = std::round(valRounded);
12288
15.4k
            }
12289
20.0k
            values.push_back(ParameterValue::create(
12290
20.0k
                Measure(valRounded,
12291
20.0k
                        param->unit_type == UnitOfMeasure::Type::ANGULAR
12292
20.0k
                            ? UnitOfMeasure::DEGREE
12293
20.0k
                        : param->unit_type == UnitOfMeasure::Type::LINEAR ? unit
12294
10.1k
                        : param->unit_type == UnitOfMeasure::Type::SCALE
12295
1.78k
                            ? UnitOfMeasure::SCALE_UNITY
12296
1.78k
                            : UnitOfMeasure::NONE)));
12297
20.0k
        }
12298
12299
4.16k
        if (step.name == "tmerc" && hasParamValue(step, "approx")) {
12300
0
            methodMap.set("proj_method", "tmerc approx");
12301
4.16k
        } else if (step.name == "utm" && hasParamValue(step, "approx")) {
12302
0
            methodMap.set("proj_method", "utm approx");
12303
0
        }
12304
12305
4.16k
        conv = Conversion::create(mapWithUnknownName, methodMap, parameters,
12306
4.16k
                                  values)
12307
4.16k
                   .as_nullable();
12308
6.11k
    } else {
12309
6.11k
        std::vector<OperationParameterNNPtr> parameters;
12310
6.11k
        std::vector<ParameterValueNNPtr> values;
12311
6.11k
        std::string methodName = "PROJ " + step.name;
12312
23.6k
        for (const auto &param : step.paramValues) {
12313
23.6k
            if (is_in_stringlist(param.key,
12314
23.6k
                                 "wktext,no_defs,datum,ellps,a,b,R,f,rf,"
12315
23.6k
                                 "towgs84,nadgrids,geoidgrids,"
12316
23.6k
                                 "units,to_meter,vunits,vto_meter,type")) {
12317
3.40k
                continue;
12318
3.40k
            }
12319
20.2k
            if (param.value.empty()) {
12320
10.0k
                methodName += " " + param.key;
12321
10.2k
            } else if (isalpha(param.value[0])) {
12322
7.69k
                methodName += " " + param.key + "=" + param.value;
12323
7.69k
            } else {
12324
2.53k
                parameters.push_back(OperationParameter::create(
12325
2.53k
                    PropertyMap().set(IdentifiedObject::NAME_KEY, param.key)));
12326
2.53k
                bool hasError = false;
12327
2.53k
                if (is_in_stringlist(param.key, "x_0,y_0,h,h_0")) {
12328
98
                    double value = getNumericValue(param.value, &hasError);
12329
98
                    values.push_back(ParameterValue::create(
12330
98
                        Measure(value, UnitOfMeasure::METRE)));
12331
2.43k
                } else if (is_in_stringlist(
12332
2.43k
                               param.key,
12333
2.43k
                               "k,k_0,"
12334
2.43k
                               "north_square,south_square," // rhealpix
12335
2.43k
                               "n,m,"                       // sinu
12336
2.43k
                               "q,"                         // urm5
12337
2.43k
                               "path,lsat,"                 // lsat
12338
2.43k
                               "W,M,"                       // hammer
12339
2.43k
                               "aperture,resolution,"       // isea
12340
2.43k
                               )) {
12341
248
                    double value = getNumericValue(param.value, &hasError);
12342
248
                    values.push_back(ParameterValue::create(
12343
248
                        Measure(value, UnitOfMeasure::SCALE_UNITY)));
12344
2.18k
                } else {
12345
2.18k
                    double value = getAngularValue(param.value, &hasError);
12346
2.18k
                    values.push_back(ParameterValue::create(
12347
2.18k
                        Measure(value, UnitOfMeasure::DEGREE)));
12348
2.18k
                }
12349
2.53k
                if (hasError) {
12350
118
                    throw ParsingException("invalid value for " + param.key);
12351
118
                }
12352
2.53k
            }
12353
20.2k
        }
12354
5.99k
        conv = Conversion::create(
12355
5.99k
                   mapWithUnknownName,
12356
5.99k
                   PropertyMap().set(IdentifiedObject::NAME_KEY, methodName),
12357
5.99k
                   parameters, values)
12358
5.99k
                   .as_nullable();
12359
12360
5.99k
        for (const char *substr :
12361
5.99k
             {"PROJ ob_tran o_proj=longlat", "PROJ ob_tran o_proj=lonlat",
12362
20.8k
              "PROJ ob_tran o_proj=latlon", "PROJ ob_tran o_proj=latlong"}) {
12363
20.8k
            if (starts_with(methodName, substr)) {
12364
1.49k
                auto geogCRS =
12365
1.49k
                    util::nn_dynamic_pointer_cast<GeographicCRS>(geodCRS);
12366
1.49k
                if (geogCRS) {
12367
1.49k
                    return DerivedGeographicCRS::create(
12368
1.49k
                        PropertyMap().set(IdentifiedObject::NAME_KEY,
12369
1.49k
                                          "unnamed"),
12370
1.49k
                        NN_NO_CHECK(geogCRS), NN_NO_CHECK(conv),
12371
1.49k
                        buildEllipsoidalCS(iStep, iUnitConvert, iAxisSwap,
12372
1.49k
                                           false));
12373
1.49k
                }
12374
1.49k
            }
12375
20.8k
        }
12376
5.99k
    }
12377
12378
8.72k
    std::vector<CoordinateSystemAxisNNPtr> axis =
12379
8.72k
        processAxisSwap(step, unit, iAxisSwap, axisType, false);
12380
12381
8.72k
    auto csGeodCRS = geodCRS->coordinateSystem();
12382
8.72k
    auto cs = csGeodCRS->axisList().size() == 2
12383
8.72k
                  ? CartesianCS::create(emptyPropertyMap, axis[0], axis[1],
12384
7.41k
                                        /* enforceSameUnit = */ false)
12385
8.72k
                  : CartesianCS::create(emptyPropertyMap, axis[0], axis[1],
12386
1.31k
                                        csGeodCRS->axisList()[2],
12387
1.31k
                                        /* enforceSameUnit = */ false);
12388
8.72k
    if (isTopocentricStep(step.name)) {
12389
22
        cs = CartesianCS::create(
12390
22
            emptyPropertyMap,
12391
22
            createAxis("topocentric East", "U", AxisDirection::EAST, unit),
12392
22
            createAxis("topocentric North", "V", AxisDirection::NORTH, unit),
12393
22
            createAxis("topocentric Up", "W", AxisDirection::UP, unit));
12394
22
    }
12395
12396
8.72k
    auto props = PropertyMap().set(IdentifiedObject::NAME_KEY,
12397
8.72k
                                   title.empty() ? "unknown" : title);
12398
8.72k
    if (hasUnusedParameters(step)) {
12399
1.30k
        props.set("EXTENSION_PROJ4", projString_);
12400
1.30k
    }
12401
12402
8.72k
    props.set("IMPLICIT_CS", true);
12403
12404
8.72k
    CRSNNPtr crs =
12405
8.72k
        bWebMercator
12406
8.72k
            ? createPseudoMercator(
12407
0
                  props.set(IdentifiedObject::NAME_KEY, webMercatorName), cs)
12408
8.72k
            : ProjectedCRS::create(props, geodCRS, NN_NO_CHECK(conv), cs);
12409
12410
8.72k
    return crs;
12411
10.4k
}
12412
12413
//! @endcond
12414
12415
// ---------------------------------------------------------------------------
12416
12417
//! @cond Doxygen_Suppress
12418
static const metadata::ExtentPtr nullExtent{};
12419
12420
0
static const metadata::ExtentPtr &getExtent(const crs::CRS *crs) {
12421
0
    const auto &domains = crs->domains();
12422
0
    if (!domains.empty()) {
12423
0
        return domains[0]->domainOfValidity();
12424
0
    }
12425
0
    return nullExtent;
12426
0
}
12427
12428
//! @endcond
12429
12430
namespace {
12431
struct PJContextHolder {
12432
    PJ_CONTEXT *ctx_;
12433
    bool bFree_;
12434
12435
568
    PJContextHolder(PJ_CONTEXT *ctx, bool bFree) : ctx_(ctx), bFree_(bFree) {}
12436
568
    ~PJContextHolder() {
12437
568
        if (bFree_)
12438
3
            proj_context_destroy(ctx_);
12439
568
    }
12440
    PJContextHolder(const PJContextHolder &) = delete;
12441
    PJContextHolder &operator=(const PJContextHolder &) = delete;
12442
};
12443
} // namespace
12444
12445
// ---------------------------------------------------------------------------
12446
12447
/** \brief Instantiate a sub-class of BaseObject from a PROJ string.
12448
 *
12449
 * The projString must contain +type=crs for the object to be detected as a
12450
 * CRS instead of a CoordinateOperation.
12451
 *
12452
 * @throw ParsingException if the string cannot be parsed.
12453
 */
12454
BaseObjectNNPtr
12455
13.4k
PROJStringParser::createFromPROJString(const std::string &projString) {
12456
12457
    // In some abnormal situations involving init=epsg:XXXX syntax, we could
12458
    // have infinite loop
12459
13.4k
    if (d->ctx_ &&
12460
13.2k
        d->ctx_->projStringParserCreateFromPROJStringRecursionCounter == 2) {
12461
0
        throw ParsingException(
12462
0
            "Infinite recursion in PROJStringParser::createFromPROJString()");
12463
0
    }
12464
12465
13.4k
    d->steps_.clear();
12466
13.4k
    d->title_.clear();
12467
13.4k
    d->globalParamValues_.clear();
12468
13.4k
    d->projString_ = projString;
12469
13.4k
    PROJStringSyntaxParser(projString, d->steps_, d->globalParamValues_,
12470
13.4k
                           d->title_);
12471
12472
13.4k
    if (d->steps_.empty()) {
12473
235
        const auto &vunits = d->getGlobalParamValue("vunits");
12474
235
        const auto &vto_meter = d->getGlobalParamValue("vto_meter");
12475
235
        if (!vunits.empty() || !vto_meter.empty()) {
12476
56
            Step fakeStep;
12477
56
            if (!vunits.empty()) {
12478
49
                fakeStep.paramValues.emplace_back(
12479
49
                    Step::KeyValue("vunits", vunits));
12480
49
            }
12481
56
            if (!vto_meter.empty()) {
12482
7
                fakeStep.paramValues.emplace_back(
12483
7
                    Step::KeyValue("vto_meter", vto_meter));
12484
7
            }
12485
56
            auto vdatum =
12486
56
                VerticalReferenceFrame::create(createMapWithUnknownName());
12487
56
            auto vcrs = VerticalCRS::create(
12488
56
                createMapWithUnknownName(), vdatum,
12489
56
                VerticalCS::createGravityRelatedHeight(
12490
56
                    d->buildUnit(fakeStep, "vunits", "vto_meter")));
12491
56
            return vcrs;
12492
56
        }
12493
235
    }
12494
12495
13.3k
    const bool isGeocentricCRS =
12496
13.3k
        ((d->steps_.size() == 1 &&
12497
11.4k
          d->getParamValue(d->steps_[0], "type") == "crs") ||
12498
4.07k
         (d->steps_.size() == 2 && d->steps_[1].name == "unitconvert")) &&
12499
9.32k
        !d->steps_[0].inverted && isGeocentricStep(d->steps_[0].name);
12500
12501
13.3k
    const bool isTopocentricCRS =
12502
13.3k
        (d->steps_.size() == 1 && isTopocentricStep(d->steps_[0].name) &&
12503
39
         d->getParamValue(d->steps_[0], "type") == "crs");
12504
12505
    // +init=xxxx:yyyy syntax
12506
13.3k
    if (d->steps_.size() == 1 && d->steps_[0].isInit &&
12507
578
        !d->steps_[0].inverted) {
12508
12509
568
        auto ctx = d->ctx_ ? d->ctx_ : proj_context_create();
12510
568
        if (!ctx) {
12511
0
            throw ParsingException("out of memory");
12512
0
        }
12513
568
        PJContextHolder contextHolder(ctx, ctx != d->ctx_);
12514
12515
        // Those used to come from a text init file
12516
        // We only support them in compatibility mode
12517
568
        const std::string &stepName = d->steps_[0].name;
12518
568
        if (ci_starts_with(stepName, "epsg:") ||
12519
564
            ci_starts_with(stepName, "IGNF:")) {
12520
12521
9
            struct BackupContextErrno {
12522
9
                PJ_CONTEXT *m_ctxt = nullptr;
12523
9
                int m_last_errno = 0;
12524
12525
9
                explicit BackupContextErrno(PJ_CONTEXT *ctxtIn)
12526
9
                    : m_ctxt(ctxtIn), m_last_errno(m_ctxt->last_errno) {
12527
9
                    m_ctxt->debug_level = PJ_LOG_ERROR;
12528
9
                }
12529
12530
9
                ~BackupContextErrno() { m_ctxt->last_errno = m_last_errno; }
12531
12532
9
                BackupContextErrno(const BackupContextErrno &) = delete;
12533
9
                BackupContextErrno &
12534
9
                operator=(const BackupContextErrno &) = delete;
12535
9
            };
12536
12537
9
            BackupContextErrno backupContextErrno(ctx);
12538
12539
9
            bool usePROJ4InitRules = d->usePROJ4InitRules_;
12540
9
            if (!usePROJ4InitRules) {
12541
9
                usePROJ4InitRules =
12542
9
                    proj_context_get_use_proj4_init_rules(ctx, FALSE) == TRUE;
12543
9
            }
12544
9
            if (!usePROJ4InitRules) {
12545
9
                throw ParsingException("init=epsg:/init=IGNF: syntax not "
12546
9
                                       "supported in non-PROJ4 emulation mode");
12547
9
            }
12548
12549
0
            char unused[256];
12550
0
            std::string initname(stepName);
12551
0
            initname.resize(initname.find(':'));
12552
0
            int file_found =
12553
0
                pj_find_file(ctx, initname.c_str(), unused, sizeof(unused),
12554
0
                             /* disable_network = */ true);
12555
12556
0
            if (!file_found) {
12557
0
                auto obj = createFromUserInput(stepName, d->dbContext_, true);
12558
0
                auto crs = dynamic_cast<CRS *>(obj.get());
12559
12560
0
                bool hasSignificantParamValues = false;
12561
0
                bool hasOver = false;
12562
0
                for (const auto &kv : d->steps_[0].paramValues) {
12563
0
                    if (kv.key == "over") {
12564
0
                        hasOver = true;
12565
0
                    } else if (!((kv.key == "type" && kv.value == "crs") ||
12566
0
                                 kv.key == "wktext" || kv.key == "no_defs")) {
12567
0
                        hasSignificantParamValues = true;
12568
0
                        break;
12569
0
                    }
12570
0
                }
12571
12572
0
                if (crs && !hasSignificantParamValues) {
12573
0
                    PropertyMap properties;
12574
0
                    properties.set(IdentifiedObject::NAME_KEY,
12575
0
                                   d->title_.empty() ? crs->nameStr()
12576
0
                                                     : d->title_);
12577
0
                    if (hasOver) {
12578
0
                        properties.set("OVER", true);
12579
0
                    }
12580
0
                    const auto &extent = getExtent(crs);
12581
0
                    if (extent) {
12582
0
                        properties.set(
12583
0
                            common::ObjectUsage::DOMAIN_OF_VALIDITY_KEY,
12584
0
                            NN_NO_CHECK(extent));
12585
0
                    }
12586
0
                    auto geogCRS = dynamic_cast<GeographicCRS *>(crs);
12587
0
                    if (geogCRS) {
12588
0
                        const auto &cs = geogCRS->coordinateSystem();
12589
                        // Override with longitude latitude in degrees
12590
0
                        return GeographicCRS::create(
12591
0
                            properties, geogCRS->datum(),
12592
0
                            geogCRS->datumEnsemble(),
12593
0
                            cs->axisList().size() == 2
12594
0
                                ? EllipsoidalCS::createLongitudeLatitude(
12595
0
                                      UnitOfMeasure::DEGREE)
12596
0
                                : EllipsoidalCS::
12597
0
                                      createLongitudeLatitudeEllipsoidalHeight(
12598
0
                                          UnitOfMeasure::DEGREE,
12599
0
                                          cs->axisList()[2]->unit()));
12600
0
                    }
12601
0
                    auto projCRS = dynamic_cast<ProjectedCRS *>(crs);
12602
0
                    if (projCRS) {
12603
                        // Override with easting northing order
12604
0
                        const auto conv = projCRS->derivingConversion();
12605
0
                        if (conv->method()->getEPSGCode() !=
12606
0
                            EPSG_CODE_METHOD_TRANSVERSE_MERCATOR_SOUTH_ORIENTATED) {
12607
0
                            return ProjectedCRS::create(
12608
0
                                properties, projCRS->baseCRS(), conv,
12609
0
                                CartesianCS::createEastingNorthing(
12610
0
                                    projCRS->coordinateSystem()
12611
0
                                        ->axisList()[0]
12612
0
                                        ->unit()));
12613
0
                        }
12614
0
                    }
12615
0
                    return obj;
12616
0
                }
12617
0
                auto projStringExportable =
12618
0
                    dynamic_cast<IPROJStringExportable *>(crs);
12619
0
                if (projStringExportable) {
12620
0
                    std::string expanded;
12621
0
                    if (!d->title_.empty()) {
12622
0
                        expanded = "title=";
12623
0
                        expanded +=
12624
0
                            pj_double_quote_string_param_if_needed(d->title_);
12625
0
                    }
12626
0
                    for (const auto &pair : d->steps_[0].paramValues) {
12627
0
                        if (!expanded.empty())
12628
0
                            expanded += ' ';
12629
0
                        expanded += '+';
12630
0
                        expanded += pair.key;
12631
0
                        if (!pair.value.empty()) {
12632
0
                            expanded += '=';
12633
0
                            expanded += pj_double_quote_string_param_if_needed(
12634
0
                                pair.value);
12635
0
                        }
12636
0
                    }
12637
0
                    expanded += ' ';
12638
0
                    expanded += projStringExportable->exportToPROJString(
12639
0
                        PROJStringFormatter::create().get());
12640
0
                    return createFromPROJString(expanded);
12641
0
                }
12642
0
            }
12643
0
        }
12644
12645
559
        paralist *init = pj_mkparam(("init=" + d->steps_[0].name).c_str());
12646
559
        if (!init) {
12647
0
            throw ParsingException("out of memory");
12648
0
        }
12649
559
        ctx->projStringParserCreateFromPROJStringRecursionCounter++;
12650
559
        paralist *list = pj_expand_init(ctx, init);
12651
559
        ctx->projStringParserCreateFromPROJStringRecursionCounter--;
12652
559
        if (!list) {
12653
134
            free(init);
12654
134
            throw ParsingException("cannot expand " + projString);
12655
134
        }
12656
425
        std::string expanded;
12657
425
        if (!d->title_.empty()) {
12658
140
            expanded =
12659
140
                "title=" + pj_double_quote_string_param_if_needed(d->title_);
12660
140
        }
12661
425
        bool first = true;
12662
425
        bool has_init_term = false;
12663
3.45k
        for (auto t = list; t;) {
12664
3.02k
            if (!expanded.empty()) {
12665
2.45k
                expanded += ' ';
12666
2.45k
            }
12667
3.02k
            if (first) {
12668
                // first parameter is the init= itself
12669
425
                first = false;
12670
2.60k
            } else if (starts_with(t->param, "init=")) {
12671
0
                has_init_term = true;
12672
2.60k
            } else {
12673
2.60k
                expanded += t->param;
12674
2.60k
            }
12675
12676
3.02k
            auto n = t->next;
12677
3.02k
            free(t);
12678
3.02k
            t = n;
12679
3.02k
        }
12680
6.86k
        for (const auto &pair : d->steps_[0].paramValues) {
12681
6.86k
            expanded += " +";
12682
6.86k
            expanded += pair.key;
12683
6.86k
            if (!pair.value.empty()) {
12684
4.44k
                expanded += '=';
12685
4.44k
                expanded += pj_double_quote_string_param_if_needed(pair.value);
12686
4.44k
            }
12687
6.86k
        }
12688
12689
425
        if (!has_init_term) {
12690
425
            return createFromPROJString(expanded);
12691
425
        }
12692
425
    }
12693
12694
12.7k
    int iFirstGeogStep = -1;
12695
12.7k
    int iSecondGeogStep = -1;
12696
12.7k
    int iProjStep = -1;
12697
12.7k
    int iFirstUnitConvert = -1;
12698
12.7k
    int iSecondUnitConvert = -1;
12699
12.7k
    int iFirstAxisSwap = -1;
12700
12.7k
    int iSecondAxisSwap = -1;
12701
12.7k
    bool unexpectedStructure = d->steps_.empty();
12702
26.0k
    for (int i = 0; i < static_cast<int>(d->steps_.size()); i++) {
12703
14.2k
        const auto &stepName = d->steps_[i].name;
12704
14.2k
        if (isGeographicStep(stepName)) {
12705
4.01k
            if (iFirstGeogStep < 0) {
12706
3.99k
                iFirstGeogStep = i;
12707
3.99k
            } else if (iSecondGeogStep < 0) {
12708
22
                iSecondGeogStep = i;
12709
22
            } else {
12710
3
                unexpectedStructure = true;
12711
3
                break;
12712
3
            }
12713
10.2k
        } else if (ci_equal(stepName, "unitconvert")) {
12714
198
            if (iFirstUnitConvert < 0) {
12715
164
                iFirstUnitConvert = i;
12716
164
            } else if (iSecondUnitConvert < 0) {
12717
32
                iSecondUnitConvert = i;
12718
32
            } else {
12719
2
                unexpectedStructure = true;
12720
2
                break;
12721
2
            }
12722
10.0k
        } else if (ci_equal(stepName, "axisswap")) {
12723
114
            if (iFirstAxisSwap < 0) {
12724
106
                iFirstAxisSwap = i;
12725
106
            } else if (iSecondAxisSwap < 0) {
12726
6
                iSecondAxisSwap = i;
12727
6
            } else {
12728
2
                unexpectedStructure = true;
12729
2
                break;
12730
2
            }
12731
9.91k
        } else if (isProjectedStep(stepName)) {
12732
9.23k
            if (iProjStep >= 0) {
12733
254
                unexpectedStructure = true;
12734
254
                break;
12735
254
            }
12736
8.98k
            iProjStep = i;
12737
8.98k
        } else {
12738
680
            unexpectedStructure = true;
12739
680
            break;
12740
680
        }
12741
14.2k
    }
12742
12743
12.7k
    if (!d->steps_.empty()) {
12744
        // CRS candidate
12745
12.5k
        if ((d->steps_.size() == 1 &&
12746
10.8k
             d->getParamValue(d->steps_[0], "type") != "crs") ||
12747
10.6k
            (d->steps_.size() > 1 && d->getGlobalParamValue("type") != "crs")) {
12748
2.38k
            unexpectedStructure = true;
12749
2.38k
        }
12750
12.5k
    }
12751
12752
12.7k
    struct Logger {
12753
12.7k
        std::string msg{};
12754
12755
        // cppcheck-suppress functionStatic
12756
12.7k
        void setMessage(const char *msgIn) noexcept {
12757
2.34k
            try {
12758
2.34k
                msg = msgIn;
12759
2.34k
            } catch (const std::exception &) {
12760
0
            }
12761
2.34k
        }
12762
12763
12.7k
        static void log(void *user_data, int level, const char *msg) {
12764
2.34k
            if (level == PJ_LOG_ERROR) {
12765
2.34k
                static_cast<Logger *>(user_data)->setMessage(msg);
12766
2.34k
            }
12767
2.34k
        }
12768
12.7k
    };
12769
12770
    // If the structure is not recognized, then try to instantiate the
12771
    // pipeline, and if successful, wrap it in a PROJBasedOperation
12772
12.7k
    Logger logger;
12773
12.7k
    bool valid;
12774
12775
12.7k
    auto pj_context = d->ctx_ ? d->ctx_ : proj_context_create();
12776
12.7k
    if (!pj_context) {
12777
0
        throw ParsingException("out of memory");
12778
0
    }
12779
12780
    // Backup error logger and level, and install temporary handler
12781
12.7k
    auto old_logger = pj_context->logger;
12782
12.7k
    auto old_logger_app_data = pj_context->logger_app_data;
12783
12.7k
    auto log_level = proj_log_level(pj_context, PJ_LOG_ERROR);
12784
12.7k
    proj_log_func(pj_context, &logger, Logger::log);
12785
12786
12.7k
    if (pj_context != d->ctx_) {
12787
130
        proj_context_use_proj4_init_rules(pj_context, d->usePROJ4InitRules_);
12788
130
    }
12789
12.7k
    pj_context->projStringParserCreateFromPROJStringRecursionCounter++;
12790
12.7k
    auto pj = pj_create_internal(
12791
12.7k
        pj_context, (projString.find("type=crs") != std::string::npos
12792
12.7k
                         ? projString + " +disable_grid_presence_check"
12793
12.7k
                         : projString)
12794
12.7k
                        .c_str());
12795
12.7k
    pj_context->projStringParserCreateFromPROJStringRecursionCounter--;
12796
12.7k
    valid = pj != nullptr;
12797
12798
    // Restore initial error logger and level
12799
12.7k
    proj_log_level(pj_context, log_level);
12800
12.7k
    pj_context->logger = old_logger;
12801
12.7k
    pj_context->logger_app_data = old_logger_app_data;
12802
12803
    // Remove parameters not understood by PROJ.
12804
12.7k
    if (valid && d->steps_.size() == 1) {
12805
9.76k
        std::vector<Step::KeyValue> newParamValues{};
12806
9.76k
        std::set<std::string> foundKeys;
12807
9.76k
        auto &step = d->steps_[0];
12808
12809
57.5k
        for (auto &kv : step.paramValues) {
12810
57.5k
            bool recognizedByPROJ = false;
12811
57.5k
            if (foundKeys.find(kv.key) != foundKeys.end()) {
12812
4.47k
                continue;
12813
4.47k
            }
12814
53.1k
            foundKeys.insert(kv.key);
12815
53.1k
            if ((step.name == "krovak" || step.name == "mod_krovak") &&
12816
3.32k
                kv.key == "alpha") {
12817
                // We recognize it in our CRS parsing code
12818
4
                recognizedByPROJ = true;
12819
53.1k
            } else {
12820
432k
                for (auto cur = pj->params; cur; cur = cur->next) {
12821
432k
                    const char *equal = strchr(cur->param, '=');
12822
432k
                    if (equal && static_cast<size_t>(equal - cur->param) ==
12823
223k
                                     kv.key.size()) {
12824
54.0k
                        if (memcmp(cur->param, kv.key.c_str(), kv.key.size()) ==
12825
54.0k
                            0) {
12826
30.2k
                            recognizedByPROJ = (cur->used == 1);
12827
30.2k
                            break;
12828
30.2k
                        }
12829
378k
                    } else if (strcmp(cur->param, kv.key.c_str()) == 0) {
12830
22.7k
                        recognizedByPROJ = (cur->used == 1);
12831
22.7k
                        break;
12832
22.7k
                    }
12833
432k
                }
12834
53.1k
            }
12835
53.1k
            if (!recognizedByPROJ && kv.key == "geoid_crs") {
12836
4.14k
                for (auto &pair : step.paramValues) {
12837
4.14k
                    if (ci_equal(pair.key, "geoidgrids")) {
12838
667
                        recognizedByPROJ = true;
12839
667
                        break;
12840
667
                    }
12841
4.14k
                }
12842
760
            }
12843
53.1k
            if (recognizedByPROJ) {
12844
15.7k
                newParamValues.emplace_back(kv);
12845
15.7k
            }
12846
53.1k
        }
12847
9.76k
        step.paramValues = std::move(newParamValues);
12848
12849
9.76k
        d->projString_.clear();
12850
9.76k
        if (!step.name.empty()) {
12851
9.75k
            d->projString_ += step.isInit ? "+init=" : "+proj=";
12852
9.75k
            d->projString_ += step.name;
12853
9.75k
        }
12854
15.7k
        for (const auto &paramValue : step.paramValues) {
12855
15.7k
            if (!d->projString_.empty()) {
12856
15.7k
                d->projString_ += ' ';
12857
15.7k
            }
12858
15.7k
            d->projString_ += '+';
12859
15.7k
            d->projString_ += paramValue.key;
12860
15.7k
            if (!paramValue.value.empty()) {
12861
13.0k
                d->projString_ += '=';
12862
13.0k
                d->projString_ +=
12863
13.0k
                    pj_double_quote_string_param_if_needed(paramValue.value);
12864
13.0k
            }
12865
15.7k
        }
12866
9.76k
    }
12867
12868
12.7k
    proj_destroy(pj);
12869
12870
12.7k
    if (!valid) {
12871
1.56k
        const int l_errno = proj_context_errno(pj_context);
12872
1.56k
        std::string msg("Error " + toString(l_errno) + " (" +
12873
1.56k
                        proj_errno_string(l_errno) + ")");
12874
1.56k
        if (!logger.msg.empty()) {
12875
1.50k
            msg += ": ";
12876
1.50k
            msg += logger.msg;
12877
1.50k
        }
12878
1.56k
        logger.msg = std::move(msg);
12879
1.56k
    }
12880
12881
12.7k
    if (pj_context != d->ctx_) {
12882
130
        proj_context_destroy(pj_context);
12883
130
    }
12884
12885
12.7k
    if (!valid) {
12886
1.56k
        throw ParsingException(logger.msg);
12887
1.56k
    }
12888
12889
11.2k
    if (isGeocentricCRS) {
12890
        // First run is dry run to mark all recognized/unrecognized tokens
12891
2.49k
        for (int iter = 0; iter < 2; iter++) {
12892
2.42k
            auto obj = d->buildBoundOrCompoundCRSIfNeeded(
12893
2.42k
                0, d->buildGeocentricCRS(0, (d->steps_.size() == 2 &&
12894
27
                                             d->steps_[1].name == "unitconvert")
12895
2.42k
                                                ? 1
12896
2.42k
                                                : -1));
12897
2.42k
            if (iter == 1) {
12898
1.17k
                return nn_static_pointer_cast<BaseObject>(obj);
12899
1.17k
            }
12900
2.42k
        }
12901
1.24k
    }
12902
12903
10.0k
    if (isTopocentricCRS) {
12904
        // First run is dry run to mark all recognized/unrecognized tokens
12905
24
        for (int iter = 0; iter < 2; iter++) {
12906
22
            auto obj = d->buildBoundOrCompoundCRSIfNeeded(
12907
22
                0,
12908
22
                d->buildProjectedCRS(0, d->buildGeocentricCRS(0, -1), -1, -1));
12909
22
            if (iter == 1) {
12910
10
                return nn_static_pointer_cast<BaseObject>(obj);
12911
10
            }
12912
22
        }
12913
12
    }
12914
12915
10.0k
    if (!unexpectedStructure) {
12916
8.37k
        if (iFirstGeogStep == 0 && !d->steps_[iFirstGeogStep].inverted &&
12917
3.71k
            iSecondGeogStep < 0 && iProjStep < 0 &&
12918
2.71k
            (iFirstUnitConvert < 0 || iSecondUnitConvert < 0) &&
12919
2.71k
            (iFirstAxisSwap < 0 || iSecondAxisSwap < 0)) {
12920
            // First run is dry run to mark all recognized/unrecognized tokens
12921
5.43k
            for (int iter = 0; iter < 2; iter++) {
12922
5.32k
                auto obj = d->buildBoundOrCompoundCRSIfNeeded(
12923
5.32k
                    0, d->buildGeodeticCRS(iFirstGeogStep, iFirstUnitConvert,
12924
5.32k
                                           iFirstAxisSwap, false));
12925
5.32k
                if (iter == 1) {
12926
2.61k
                    return nn_static_pointer_cast<BaseObject>(obj);
12927
2.61k
                }
12928
5.32k
            }
12929
2.71k
        }
12930
5.76k
        if (iProjStep >= 0 && !d->steps_[iProjStep].inverted &&
12931
5.60k
            (iFirstGeogStep < 0 || iFirstGeogStep + 1 == iProjStep) &&
12932
5.60k
            iSecondGeogStep < 0) {
12933
5.60k
            if (iFirstGeogStep < 0)
12934
4.60k
                iFirstGeogStep = iProjStep;
12935
            // First run is dry run to mark all recognized/unrecognized tokens
12936
11.2k
            for (int iter = 0; iter < 2; iter++) {
12937
10.6k
                auto obj = d->buildBoundOrCompoundCRSIfNeeded(
12938
10.6k
                    iProjStep,
12939
10.6k
                    d->buildProjectedCRS(
12940
10.6k
                        iProjStep,
12941
10.6k
                        d->buildGeodeticCRS(iFirstGeogStep,
12942
10.6k
                                            iFirstUnitConvert < iFirstGeogStep
12943
10.6k
                                                ? iFirstUnitConvert
12944
10.6k
                                                : -1,
12945
10.6k
                                            iFirstAxisSwap < iFirstGeogStep
12946
10.6k
                                                ? iFirstAxisSwap
12947
10.6k
                                                : -1,
12948
10.6k
                                            true),
12949
10.6k
                        iFirstUnitConvert < iFirstGeogStep ? iSecondUnitConvert
12950
10.6k
                                                           : iFirstUnitConvert,
12951
10.6k
                        iFirstAxisSwap < iFirstGeogStep ? iSecondAxisSwap
12952
10.6k
                                                        : iFirstAxisSwap));
12953
10.6k
                if (iter == 1) {
12954
5.00k
                    return nn_static_pointer_cast<BaseObject>(obj);
12955
5.00k
                }
12956
10.6k
            }
12957
5.60k
        }
12958
5.76k
    }
12959
12960
2.41k
    auto props = PropertyMap();
12961
2.41k
    if (!d->title_.empty()) {
12962
53
        props.set(IdentifiedObject::NAME_KEY, d->title_);
12963
53
    }
12964
2.41k
    return operation::SingleOperation::createPROJBased(props, projString,
12965
2.41k
                                                       nullptr, nullptr, {});
12966
10.0k
}
12967
12968
// ---------------------------------------------------------------------------
12969
12970
//! @cond Doxygen_Suppress
12971
struct JSONFormatter::Private {
12972
    CPLJSonStreamingWriter writer_{nullptr, nullptr};
12973
    DatabaseContextPtr dbContext_{};
12974
12975
    std::vector<bool> stackHasId_{false};
12976
    std::vector<bool> outputIdStack_{true};
12977
    bool allowIDInImmediateChild_ = false;
12978
    bool omitTypeInImmediateChild_ = false;
12979
    bool abridgedTransformation_ = false;
12980
    bool abridgedTransformationWriteSourceCRS_ = false;
12981
    std::string schema_ = PROJJSON_DEFAULT_VERSION;
12982
12983
    // cppcheck-suppress functionStatic
12984
0
    void pushOutputId(bool outputIdIn) { outputIdStack_.push_back(outputIdIn); }
12985
12986
    // cppcheck-suppress functionStatic
12987
0
    void popOutputId() { outputIdStack_.pop_back(); }
12988
};
12989
//! @endcond
12990
12991
// ---------------------------------------------------------------------------
12992
12993
/** \brief Constructs a new formatter.
12994
 *
12995
 * A formatter can be used only once (its internal state is mutated)
12996
 *
12997
 * @return new formatter.
12998
 */
12999
JSONFormatterNNPtr JSONFormatter::create( // cppcheck-suppress passedByValue
13000
0
    DatabaseContextPtr dbContext) {
13001
0
    auto ret = NN_NO_CHECK(JSONFormatter::make_unique<JSONFormatter>());
13002
0
    ret->d->dbContext_ = std::move(dbContext);
13003
0
    return ret;
13004
0
}
13005
13006
// ---------------------------------------------------------------------------
13007
13008
/** \brief Whether to use multi line output or not. */
13009
0
JSONFormatter &JSONFormatter::setMultiLine(bool multiLine) noexcept {
13010
0
    d->writer_.SetPrettyFormatting(multiLine);
13011
0
    return *this;
13012
0
}
13013
13014
// ---------------------------------------------------------------------------
13015
13016
/** \brief Set number of spaces for each indentation level (defaults to 4).
13017
 */
13018
0
JSONFormatter &JSONFormatter::setIndentationWidth(int width) noexcept {
13019
0
    d->writer_.SetIndentationSize(width);
13020
0
    return *this;
13021
0
}
13022
13023
// ---------------------------------------------------------------------------
13024
13025
/** \brief Set the value of the "$schema" key in the top level object.
13026
 *
13027
 * If set to empty string, it will not be written.
13028
 */
13029
0
JSONFormatter &JSONFormatter::setSchema(const std::string &schema) noexcept {
13030
0
    d->schema_ = schema;
13031
0
    return *this;
13032
0
}
13033
13034
// ---------------------------------------------------------------------------
13035
13036
//! @cond Doxygen_Suppress
13037
13038
0
JSONFormatter::JSONFormatter() : d(std::make_unique<Private>()) {}
13039
13040
// ---------------------------------------------------------------------------
13041
13042
0
JSONFormatter::~JSONFormatter() = default;
13043
13044
// ---------------------------------------------------------------------------
13045
13046
0
CPLJSonStreamingWriter *JSONFormatter::writer() const { return &(d->writer_); }
13047
13048
// ---------------------------------------------------------------------------
13049
13050
0
const DatabaseContextPtr &JSONFormatter::databaseContext() const {
13051
0
    return d->dbContext_;
13052
0
}
13053
13054
// ---------------------------------------------------------------------------
13055
13056
0
bool JSONFormatter::outputId() const { return d->outputIdStack_.back(); }
13057
13058
// ---------------------------------------------------------------------------
13059
13060
0
bool JSONFormatter::outputUsage(bool calledBeforeObjectContext) const {
13061
0
    return outputId() &&
13062
0
           d->outputIdStack_.size() == (calledBeforeObjectContext ? 1U : 2U);
13063
0
}
13064
13065
// ---------------------------------------------------------------------------
13066
13067
0
void JSONFormatter::setAllowIDInImmediateChild() {
13068
0
    d->allowIDInImmediateChild_ = true;
13069
0
}
13070
13071
// ---------------------------------------------------------------------------
13072
13073
0
void JSONFormatter::setOmitTypeInImmediateChild() {
13074
0
    d->omitTypeInImmediateChild_ = true;
13075
0
}
13076
13077
// ---------------------------------------------------------------------------
13078
13079
JSONFormatter::ObjectContext::ObjectContext(JSONFormatter &formatter,
13080
                                            const char *objectType, bool hasId)
13081
0
    : m_formatter(formatter) {
13082
0
    m_formatter.d->writer_.StartObj();
13083
0
    if (m_formatter.d->outputIdStack_.size() == 1 &&
13084
0
        !m_formatter.d->schema_.empty()) {
13085
0
        m_formatter.d->writer_.AddObjKey("$schema");
13086
0
        m_formatter.d->writer_.Add(m_formatter.d->schema_);
13087
0
    }
13088
0
    if (objectType && !m_formatter.d->omitTypeInImmediateChild_) {
13089
0
        m_formatter.d->writer_.AddObjKey("type");
13090
0
        m_formatter.d->writer_.Add(objectType);
13091
0
    }
13092
0
    m_formatter.d->omitTypeInImmediateChild_ = false;
13093
    // All intermediate nodes shouldn't have ID if a parent has an ID
13094
    // unless explicitly enabled.
13095
0
    if (m_formatter.d->allowIDInImmediateChild_) {
13096
0
        m_formatter.d->pushOutputId(m_formatter.d->outputIdStack_[0]);
13097
0
        m_formatter.d->allowIDInImmediateChild_ = false;
13098
0
    } else {
13099
0
        m_formatter.d->pushOutputId(m_formatter.d->outputIdStack_[0] &&
13100
0
                                    !m_formatter.d->stackHasId_.back());
13101
0
    }
13102
13103
0
    m_formatter.d->stackHasId_.push_back(hasId ||
13104
0
                                         m_formatter.d->stackHasId_.back());
13105
0
}
13106
13107
// ---------------------------------------------------------------------------
13108
13109
0
JSONFormatter::ObjectContext::~ObjectContext() {
13110
0
    m_formatter.d->writer_.EndObj();
13111
0
    m_formatter.d->stackHasId_.pop_back();
13112
0
    m_formatter.d->popOutputId();
13113
0
}
13114
13115
// ---------------------------------------------------------------------------
13116
13117
0
void JSONFormatter::setAbridgedTransformation(bool outputIn) {
13118
0
    d->abridgedTransformation_ = outputIn;
13119
0
}
13120
13121
// ---------------------------------------------------------------------------
13122
13123
0
bool JSONFormatter::abridgedTransformation() const {
13124
0
    return d->abridgedTransformation_;
13125
0
}
13126
13127
// ---------------------------------------------------------------------------
13128
13129
0
void JSONFormatter::setAbridgedTransformationWriteSourceCRS(bool writeCRS) {
13130
0
    d->abridgedTransformationWriteSourceCRS_ = writeCRS;
13131
0
}
13132
13133
// ---------------------------------------------------------------------------
13134
13135
0
bool JSONFormatter::abridgedTransformationWriteSourceCRS() const {
13136
0
    return d->abridgedTransformationWriteSourceCRS_;
13137
0
}
13138
13139
//! @endcond
13140
13141
// ---------------------------------------------------------------------------
13142
13143
/** \brief Return the serialized JSON.
13144
 */
13145
0
const std::string &JSONFormatter::toString() const {
13146
0
    return d->writer_.GetString();
13147
0
}
13148
13149
// ---------------------------------------------------------------------------
13150
13151
//! @cond Doxygen_Suppress
13152
12.2M
IJSONExportable::~IJSONExportable() = default;
13153
13154
// ---------------------------------------------------------------------------
13155
13156
0
std::string IJSONExportable::exportToJSON(JSONFormatter *formatter) const {
13157
0
    _exportToJSON(formatter);
13158
0
    return formatter->toString();
13159
0
}
13160
13161
//! @endcond
13162
13163
} // namespace io
13164
NS_PROJ_END