1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2023-05-15
 * Description : geolocation engine based on Marble.
 *               (c) 2007-2022 Marble Team
 *               https://invent.kde.org/education/marble/-/raw/master/data/credits_authors.html
 *
 * SPDX-FileCopyrightText: 2023-2024 by Gilles Caulier <caulier dot gilles at gmail dot com>
 *
 * SPDX-License-Identifier: LGPL-2.1-or-later
 *
 * ============================================================ */

#include "Pn2Runner.h"

// Qt includes

#include <QFile>
#include <QFileInfo>

// Local includes

#include "GeoDataDocument.h"
#include "GeoDataPlacemark.h"
#include "GeoDataStyle.h"
#include "GeoDataPolyStyle.h"
#include "GeoDataLinearRing.h"
#include "GeoDataPolygon.h"
#include "GeoDataMultiGeometry.h"
#include "digikam_debug.h"

namespace Marble
{

// Polygon header flags, representing the type of polygon

enum polygonFlagType
{
    LINESTRING    = 0,
    LINEARRING    = 1,
    OUTERBOUNDARY = 2,
    INNERBOUNDARY = 3,
    MULTIGEOMETRY = 4
};

/**
 * For the Natural Earth Layer providing the Default data set at 0.5 arcminute resolution should be enough.
 * This fileformat allows for even better packed data than the PNT format. For detailed polygons at arcminute
 * scale on average it should use only 33% of the amount used by PNT.
 *
 * Description of the file format
 *
 * In the fileformat initially a file header is provided that provides the file format version and the number
 * of polygons stored inside the file. A Polygon starts with the Polygon Header which provides the feature id
 * and the number of so called "absolute nodes" that are about to follow. Absolute nodes always contain
 * absolute geodetic coordinates. The Polygon Header also provides a flag that allows to specify whether the
 * polygon is supposed to represent a line string ("0") or a linear ring ("1"). Each absolute node can be followed
 * by relative nodes: These relative nodes are always nodes that follow in correct order inside the polygon after
 * "their" absolute node. Each absolute node specifies the number of relative nodes which contain relative
 * coordinates in reference to their absolute node. So an absolute node provides the absolute reference for
 * relative nodes across a theoretical area of 2x2 squaredegree-area (which in practice frequently might rather
 * amount to 1x1 square degrees).
 *
 * So much of the compression works by just referencing lat/lon diffs to special "absolute nodes". Hence the
 * compression will especially work well for polygons with many nodes with a high node density.
 *
 * The parser has to convert these relative coordinates to absolute coordinates.
 */
Pn2Runner::Pn2Runner(QObject* parent)
    : ParsingRunner(parent)
{
}

Pn2Runner::~Pn2Runner()
{
}

bool Pn2Runner::errorCheckLat(qint16 lat)
{
    return !(lat >= -10800 && lat <= +10800);
}

bool Pn2Runner::errorCheckLon(qint16 lon)
{
    return !(lon >= -21600 && lon <= +21600);
}

bool Pn2Runner::importPolygon(QDataStream& stream, GeoDataLineString* linestring, quint32 nrAbsoluteNodes)
{
    qint16 lat, lon, nrRelativeNodes;
    qint8 relativeLat, relativeLon;
    bool error = false;


    for (quint32 absoluteNode = 1; absoluteNode <= nrAbsoluteNodes; absoluteNode++)
    {
        stream >> lat >> lon >> nrRelativeNodes;

        error = error | errorCheckLat(lat) | errorCheckLon(lon);

        qreal degLat = (1.0 * lat / 120.0);
        qreal degLon = (1.0 * lon / 120.0);

        GeoDataCoordinates coord(degLon / 180 * M_PI, degLat / 180 * M_PI);
        linestring->append(coord);

        for (qint16 relativeNode = 1; relativeNode <= nrRelativeNodes; ++relativeNode)
        {
            stream >> relativeLat >> relativeLon;

            qint16 currLat = relativeLat + lat;
            qint16 currLon = relativeLon + lon;


            error = error | errorCheckLat(currLat) | errorCheckLon(currLon);

            qreal currDegLat = (1.0 * currLat / 120.0);
            qreal currDegLon = (1.0 * currLon / 120.0);


            GeoDataCoordinates currCoord(currDegLon / 180 * M_PI, currDegLat / 180 * M_PI);
            linestring->append(currCoord);
        }
    }

    *linestring = linestring->optimized();

    return error;
}

GeoDataDocument* Pn2Runner::parseFile(const QString& fileName, DocumentRole role, QString& error)
{
    QFileInfo fileinfo(fileName);

    if (fileinfo.suffix().compare(QLatin1String("pn2"), Qt::CaseInsensitive) != 0)
    {
        error = QStringLiteral("File %1 does not have a pn2 suffix").arg(fileName);
        qCDebug(DIGIKAM_MARBLE_LOG) << error;
        return nullptr;
    }

    QFile  file(fileName);

    if (!file.exists())
    {
        error = QStringLiteral("File %1 does not exist").arg(fileName);
        qCDebug(DIGIKAM_MARBLE_LOG) << error;
        return nullptr;
    }

    file.open(QIODevice::ReadOnly);
    m_stream.setDevice(&file);    // read the data serialized from the file

    m_stream >> m_fileHeaderVersion >> m_fileHeaderPolygons >> m_isMapColorField;

    switch (m_fileHeaderVersion)
    {
        case 1:
            return parseForVersion1(fileName, role);

        case 2:
            return parseForVersion2(fileName, role);

        default:
            qCDebug(DIGIKAM_MARBLE_LOG) << "File can't be parsed. We don't have parser for file header version:" << m_fileHeaderVersion;
            break;
    }

    return nullptr;
}

GeoDataDocument* Pn2Runner::parseForVersion1(const QString& fileName, DocumentRole role)
{
    GeoDataDocument* document = new GeoDataDocument();
    document->setDocumentRole(role);

    bool error = false;

    quint32 ID, nrAbsoluteNodes;
    quint8 flag, prevFlag = -1;

    GeoDataStyle::Ptr style;
    GeoDataPolygon* polygon = new GeoDataPolygon;

    for (quint32 currentPoly = 1; (currentPoly <= m_fileHeaderPolygons) && (!error) && (!m_stream.atEnd()); currentPoly++)
    {

        m_stream >> ID >> nrAbsoluteNodes >> flag;

        if (flag != INNERBOUNDARY && (prevFlag == INNERBOUNDARY || prevFlag == OUTERBOUNDARY))
        {

            GeoDataPlacemark* placemark = new GeoDataPlacemark;
            placemark->setGeometry(polygon);

            if (m_isMapColorField)
            {
                if (style)
                {
                    placemark->setStyle(style);
                }
            }

            document->append(placemark);
        }

        if (flag == LINESTRING)
        {
            GeoDataLineString* linestring = new GeoDataLineString;
            error = error | importPolygon(m_stream, linestring, nrAbsoluteNodes);

            GeoDataPlacemark* placemark = new GeoDataPlacemark;
            placemark->setGeometry(linestring);
            document->append(placemark);
        }

        if ((flag == LINEARRING) || (flag == OUTERBOUNDARY) || (flag == INNERBOUNDARY))
        {
            if (flag == OUTERBOUNDARY && m_isMapColorField)
            {
                quint8 colorIndex;
                m_stream >> colorIndex;
                style = GeoDataStyle::Ptr(new GeoDataStyle);
                GeoDataPolyStyle polyStyle;
                polyStyle.setColorIndex(colorIndex);
                style->setPolyStyle(polyStyle);
            }

            GeoDataLinearRing* linearring = new GeoDataLinearRing;
            error = error | importPolygon(m_stream, linearring, nrAbsoluteNodes);

            if (flag == LINEARRING)
            {
                GeoDataPlacemark* placemark = new GeoDataPlacemark;
                placemark->setGeometry(linearring);
                document->append(placemark);
            }

            if (flag == OUTERBOUNDARY)
            {
                polygon = new GeoDataPolygon;
                polygon->setOuterBoundary(*linearring);
            }

            if (flag == INNERBOUNDARY)
            {
                polygon->appendInnerBoundary(*linearring);
            }
        }

        if (flag == MULTIGEOMETRY)
        {
            // not implemented yet, for now elements inside a multigeometry are separated as individual geometries
        }

        prevFlag = flag;
    }

    if (prevFlag == INNERBOUNDARY || prevFlag == OUTERBOUNDARY)
    {
        GeoDataPlacemark* placemark = new GeoDataPlacemark;

        if (m_isMapColorField)
        {
            if (style)
            {
                placemark->setStyle(style);
            }
        }

        placemark->setGeometry(polygon);
        document->append(placemark);
    }

    if (error)
    {
        delete document;
        document = nullptr;
        return nullptr;
    }

    document->setFileName(fileName);
    return document;
}

GeoDataDocument* Pn2Runner::parseForVersion2(const QString& fileName, DocumentRole role)
{
    GeoDataDocument* document = new GeoDataDocument();
    document->setDocumentRole(role);

    bool error = false;

    quint32 nrAbsoluteNodes;
    quint32 placemarkCurrentID = 1;
    quint32 placemarkPrevID = 0;
    quint8 flag, prevFlag = -1;

    GeoDataPolygon* polygon = new GeoDataPolygon;
    GeoDataStyle::Ptr style;
    GeoDataPlacemark* placemark = nullptr; // new GeoDataPlacemark;

    quint32 currentPoly;

    for (currentPoly = 1; (currentPoly <= m_fileHeaderPolygons) && (!error) && (!m_stream.atEnd()); currentPoly++)
    {
        m_stream >> flag >> placemarkCurrentID;

        if (flag == MULTIGEOMETRY && (prevFlag == INNERBOUNDARY || prevFlag == OUTERBOUNDARY))
        {
            if (placemark)
            {
                placemark->setGeometry(polygon);
            }
        }

        if (flag != MULTIGEOMETRY && flag != INNERBOUNDARY && (prevFlag == INNERBOUNDARY || prevFlag == OUTERBOUNDARY))
        {
            if (placemark)
            {
                placemark->setGeometry(polygon);
            }
        }

        /**
         * If the parsed placemark id @p placemarkCurrentID is different
         * from the id of previous placemark @p placemarkPrevID, it means
         * we have encountered a new placemark. So, prepare a style @p style
         * if file has color indices
         */
        if (placemarkCurrentID != placemarkPrevID)
        {
            placemark = new GeoDataPlacemark;

            // Handle the color index
            if (m_isMapColorField)
            {
                quint8 colorIndex;
                m_stream >> colorIndex;
                style = GeoDataStyle::Ptr(new GeoDataStyle);
                GeoDataPolyStyle polyStyle;
                polyStyle.setColorIndex(colorIndex);
                polyStyle.setFill(true);
                style->setPolyStyle(polyStyle);
                placemark->setStyle(style);
            }

            document->append(placemark);
        }

        placemarkPrevID = placemarkCurrentID;

        if (flag != MULTIGEOMETRY)
        {
            m_stream >> nrAbsoluteNodes;

            if (flag == LINESTRING)
            {
                GeoDataLineString* linestring = new GeoDataLineString;
                error = error | importPolygon(m_stream, linestring, nrAbsoluteNodes);

                if (placemark)
                {
                    placemark->setGeometry(linestring);
                }
            }

            if ((flag == LINEARRING) || (flag == OUTERBOUNDARY) || (flag == INNERBOUNDARY))
            {
                GeoDataLinearRing* linearring = new GeoDataLinearRing;
                error = error || importPolygon(m_stream, linearring, nrAbsoluteNodes);

                if (flag == LINEARRING)
                {
                    if (placemark)
                    {
                        placemark->setGeometry(linearring);
                    }
                }

                else
                {
                    if (flag == OUTERBOUNDARY)
                    {
                        polygon = new GeoDataPolygon;
                        polygon->setOuterBoundary(*linearring);
                    }

                    if (flag == INNERBOUNDARY)
                    {
                        polygon->appendInnerBoundary(*linearring);
                    }

                    delete linearring;
                }
            }

            prevFlag = flag;
        }

        else
        {
            quint32 placemarkCurrentIDInMulti;
            quint8 flagInMulti;
            quint8 prevFlagInMulti = -1;
            quint8 multiSize = 0;

            m_stream >> multiSize;

            GeoDataMultiGeometry* multigeom = new GeoDataMultiGeometry;

            /**
             * Read @p multiSize GeoDataGeometry objects
             */
            for (int iter = 0; iter < multiSize; ++iter)
            {
                m_stream >> flagInMulti >> placemarkCurrentIDInMulti >> nrAbsoluteNodes;

                if (flagInMulti != INNERBOUNDARY && (prevFlagInMulti == INNERBOUNDARY || prevFlagInMulti == OUTERBOUNDARY))
                {
                    multigeom->append(polygon);
                }

                if (flagInMulti == LINESTRING)
                {
                    GeoDataLineString* linestring = new GeoDataLineString;
                    error = error || importPolygon(m_stream, linestring, nrAbsoluteNodes);
                    multigeom->append(linestring);
                }

                if ((flagInMulti == LINEARRING) || (flagInMulti == OUTERBOUNDARY) || (flagInMulti == INNERBOUNDARY))
                {
                    GeoDataLinearRing* linearring = new GeoDataLinearRing;
                    error = error | importPolygon(m_stream, linearring, nrAbsoluteNodes);

                    if (flagInMulti == LINEARRING)
                    {
                        multigeom->append(linearring);
                    }

                    else
                    {
                        if (flagInMulti == OUTERBOUNDARY)
                        {
                            polygon = new GeoDataPolygon;
                            polygon->setOuterBoundary(*linearring);
                        }

                        if (flagInMulti == INNERBOUNDARY)
                        {
                            polygon->appendInnerBoundary(*linearring);
                        }

                        delete linearring;
                    }
                }

                prevFlagInMulti = flagInMulti;
            }

            if (prevFlagInMulti == INNERBOUNDARY || prevFlagInMulti == OUTERBOUNDARY)
            {
                multigeom->append(polygon);
            }

            if (placemark)
            {
                placemark->setGeometry(multigeom);
            }

            prevFlag = MULTIGEOMETRY;
        }
    }

    if (
        placemark                                                &&
        (prevFlag == INNERBOUNDARY || prevFlag == OUTERBOUNDARY) &&
        (prevFlag != MULTIGEOMETRY)
    )
    {
        placemark->setGeometry(polygon);
    }

    if (error)
    {
        delete document;
        document = nullptr;
        return nullptr;
    }

    document->setFileName(fileName);
    return document;
}

} // namespace Marble

#include "moc_Pn2Runner.cpp"