lwgeom_in_kml.c 13.9 KB
Newer Older
1 2 3
/**********************************************************************
 *
 * PostGIS - Spatial Types for PostgreSQL
4 5 6 7 8 9 10 11 12 13 14
 * http://postgis.net
 *
 * PostGIS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * PostGIS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
15
 *
16 17 18 19 20 21
 * You should have received a copy of the GNU General Public License
 * along with PostGIS.  If not, see <http://www.gnu.org/licenses/>.
 *
 **********************************************************************
 *
 * Copyright 2009 Oslandia
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
 *
 **********************************************************************/

/**
* @file KML input routines.
* Ability to parse KML geometry fragment and to return an LWGEOM
* or an error message.
*
* KML version supported: 2.2.0
* Cf: <http://www.opengeospatial.org/standards/kml>
*
* Known limitations related to 3D:
*  - Not support kml:Model geometries
*  - Don't handle kml:extrude attribute
*
* Written by Olivier Courtin - Oslandia
*
**********************************************************************/


42 43
#include <libxml/tree.h>
#include <libxml/parser.h>
44 45
#include <errno.h>
#include <string.h>
46

47
#include "postgres.h"
48 49

#include "../postgis_config.h"
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
#include "lwgeom_pg.h"
#include "liblwgeom.h"



/*
TODO:
	- OGC:LonLat84_5773 explicit support (rather than EPSG:4326)
	- altitudeModeGroup relativeToGround Z Altitude
	  computation upon Geoid
*/


Datum geom_from_kml(PG_FUNCTION_ARGS);
static LWGEOM* parse_kml(xmlNodePtr xnode, bool *hasz);

#define KML_NS		((char *) "http://www.opengis.net/kml/2.2")


/**
 * Ability to parse KML geometry fragment and to return an LWGEOM
 * or an error message.
 */
PG_FUNCTION_INFO_V1(geom_from_kml);
Datum geom_from_kml(PG_FUNCTION_ARGS)
{
76 77
	GSERIALIZED *geom;
	LWGEOM *lwgeom, *hlwgeom;
78 79 80 81 82 83 84 85 86 87 88
	xmlDocPtr xmldoc;
	text *xml_input;
	int xml_size;
	char *xml;
	bool hasz=true;
	xmlNodePtr xmlroot=NULL;


	/* Get the KML stream */
	if (PG_ARGISNULL(0)) PG_RETURN_NULL();
	xml_input = PG_GETARG_TEXT_P(0);
89 90
	xml = text2cstring(xml_input);
	xml_size = VARSIZE(xml_input) - VARHDRSZ;
91 92 93

	/* Begin to Parse XML doc */
	xmlInitParser();
94
	xmldoc = xmlReadMemory(xml, xml_size, NULL, NULL, XML_PARSE_SAX1);
95 96 97 98
	if (!xmldoc || (xmlroot = xmlDocGetRootElement(xmldoc)) == NULL)
	{
		xmlFreeDoc(xmldoc);
		xmlCleanupParser();
99
		lwpgerror("invalid KML representation");
100 101 102 103
	}

	lwgeom = parse_kml(xmlroot, &hasz);

104 105 106 107 108 109 110 111 112
	/* Homogenize geometry result if needed */
	if (lwgeom->type == COLLECTIONTYPE)
	{
		hlwgeom = lwgeom_homogenize(lwgeom);
		lwgeom_release(lwgeom);
		lwgeom = hlwgeom;
	}

	lwgeom_add_bbox(lwgeom);
113 114 115 116 117 118 119 120 121

	/* KML geometries could be either 2 or 3D
	 *
	 * So we deal with 3D in all structures allocation, and flag hasz
	 * to false if we met once a missing Z dimension
	 * In this case, we force recursive 2D.
	 */
	if (!hasz)
	{
122 123 124
		LWGEOM *tmp = lwgeom_force_2d(lwgeom);
		lwgeom_free(lwgeom);
		lwgeom = tmp;
125 126
	}

127 128 129 130 131 132
	geom = geometry_serialize(lwgeom);
	lwgeom_free(lwgeom);

	xmlFreeDoc(xmldoc);
	xmlCleanupParser();

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
	PG_RETURN_POINTER(geom);
}


/**
 * Return false if current element namespace is not a KML one
 * Return true otherwise.
 */
static bool is_kml_namespace(xmlNodePtr xnode, bool is_strict)
{
	xmlNsPtr *ns, *p;

	ns = xmlGetNsList(xnode->doc, xnode);
	/*
	 * If no namespace is available we could return true anyway
	 * (because we work only on KML fragment, we don't want to
	 *  'oblige' to add namespace on the geometry root node)
	 */
	if (ns == NULL) return !is_strict;

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        for (p=ns ; *p ; p++)
        {
                if ((*p)->href == NULL || (*p)->prefix == NULL ||
                     xnode->ns == NULL || xnode->ns->prefix == NULL) continue;

                if (!xmlStrcmp(xnode->ns->prefix, (*p)->prefix))
                {
                        if (!strcmp((char *) (*p)->href, KML_NS))
                        {
                                xmlFree(ns);
                                return true;
                        } else {
                                xmlFree(ns);
                                return false;
                        }
                }
        }
170

171 172
        xmlFree(ns);
        return !is_strict; /* Same reason here to not return false */;
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
}


/* Temporarily disabling unused function. */
#if 0
/**
 * Retrieve a KML propertie from a node or NULL otherwise
 * Respect namespaces if presents in the node element
 */
static xmlChar *kmlGetProp(xmlNodePtr xnode, xmlChar *prop)
{
	xmlChar *value;

	if (!is_kml_namespace(xnode, true))
		return xmlGetProp(xnode, prop);

	value = xmlGetNsProp(xnode, prop, (xmlChar *) KML_NS);

	/* In last case try without explicit namespace */
	if (value == NULL) value = xmlGetNoNsProp(xnode, prop);

	return value;
}
#endif


199
#if 0 /* unused */
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
/**
 * Parse a string supposed to be a double
 */
static double parse_kml_double(char *d, bool space_before, bool space_after)
{
	char *p;
	int st;
	enum states
	{
		INIT     	= 0,
		NEED_DIG  	= 1,
		DIG	  	= 2,
		NEED_DIG_DEC 	= 3,
		DIG_DEC 	= 4,
		EXP	 	= 5,
		NEED_DIG_EXP 	= 6,
		DIG_EXP 	= 7,
		END 		= 8
	};

	/*
	 * Double pattern
	 * [-|\+]?[0-9]+(\.)?([0-9]+)?([Ee](\+|-)?[0-9]+)?
	 * We could also meet spaces before and/or after
	 * this pattern upon parameters
	 */

	if (space_before) while (isspace(*d)) d++;
	for (st = INIT, p = d ; *p ; p++)
	{

231
lwpgnotice("State: %d, *p=%c", st, *p);
232

233 234 235 236 237 238
		if (isdigit(*p))
		{
			if (st == INIT || st == NEED_DIG) 	st = DIG;
			else if (st == NEED_DIG_DEC) 			st = DIG_DEC;
			else if (st == NEED_DIG_EXP || st == EXP) 	st = DIG_EXP;
			else if (st == DIG || st == DIG_DEC || st == DIG_EXP);
239
			else lwpgerror("invalid KML representation");
240 241 242 243
		}
		else if (*p == '.')
		{
			if      (st == DIG) 				st = NEED_DIG_DEC;
244
			else    lwpgerror("invalid KML representation");
245 246 247 248 249
		}
		else if (*p == '-' || *p == '+')
		{
			if      (st == INIT) 				st = NEED_DIG;
			else if (st == EXP) 				st = NEED_DIG_EXP;
250
			else    lwpgerror("invalid KML representation");
251 252 253 254
		}
		else if (*p == 'e' || *p == 'E')
		{
			if      (st == DIG || st == DIG_DEC) 		st = EXP;
255
			else    lwpgerror("invalid KML representation");
256 257 258
		}
		else if (isspace(*p))
		{
259
			if (!space_after) lwpgerror("invalid KML representation");
260 261 262
			if (st == DIG || st == DIG_DEC || st == DIG_EXP)st = END;
			else if (st == NEED_DIG_DEC)			st = END;
			else if (st == END);
263
			else    lwpgerror("invalid KML representation");
264
		}
265
		else  lwpgerror("invalid KML representation");
266 267 268
	}

	if (st != DIG && st != NEED_DIG_DEC && st != DIG_DEC && st != DIG_EXP && st != END)
269
		lwpgerror("invalid KML representation");
270 271 272

	return atof(d);
}
273
#endif /* unused */
274 275 276 277 278 279 280 281


/**
 * Parse kml:coordinates
 */
static POINTARRAY* parse_kml_coordinates(xmlNodePtr xnode, bool *hasz)
{
	xmlChar *kml_coord;
282
	bool found;
283
	POINTARRAY *dpa;
284
	int seen_kml_dims = 0;
285 286 287
	int kml_dims;
	char *p, *q;
	POINT4D pt;
288
  double d;
289

290
	if (xnode == NULL) lwpgerror("invalid KML representation");
291 292 293 294 295 296 297 298 299 300

	for (found = false ; xnode != NULL ; xnode = xnode->next)
	{
		if (xnode->type != XML_ELEMENT_NODE) continue;
		if (!is_kml_namespace(xnode, false)) continue;
		if (strcmp((char *) xnode->name, "coordinates")) continue;

		found = true;
		break;
	}
301
	if (!found) lwpgerror("invalid KML representation");
302 303 304 305 306 307 308 309 310 311

	/* We begin to retrieve coordinates string */
	kml_coord = xmlNodeGetContent(xnode);
	p = (char *) kml_coord;

	/* KML coordinates pattern:     x1,y1 x2,y2
	 *                              x1,y1,z1 x2,y2,z2
	*/

	/* Now we create PointArray from coordinates values */
312 313
	/* HasZ, !HasM, 1pt */
	dpa = ptarray_construct_empty(1, 0, 1);
314

315 316
  while (*p && isspace(*p)) ++p;
	for (kml_dims=0; *p ; p++)
317
	{
318
//lwpgnotice("*p:%c, kml_dims:%d", *p, kml_dims);
319 320 321 322 323
    if ( isdigit(*p) || *p == '+' || *p == '-' || *p == '.' ) {
			  kml_dims++;
        errno = 0; d = strtod(p, &q);
        if ( errno != 0 ) {
          // TODO: destroy dpa, return NULL
324
          lwpgerror("invalid KML representation"); /*: %s", strerror(errno));*/
325 326 327 328 329
        }
        if      (kml_dims == 1) pt.x = d;
        else if (kml_dims == 2) pt.y = d;
        else if (kml_dims == 3) pt.z = d;
        else {
330
          lwpgerror("invalid KML representation"); /* (more than 3 dimensions)"); */
331 332
          // TODO: destroy dpa, return NULL
        }
333

334
//lwpgnotice("after strtod d:%f, *q:%c, kml_dims:%d", d, *q, kml_dims);
335

336
        if ( *q && ! isspace(*q) && *q != ',' ) {
337
          lwpgerror("invalid KML representation"); /* (invalid character %c follows ordinate value)", *q); */
338
        }
339

340 341 342
        /* Look-ahead to see if we're done reading */
        while (*q && isspace(*q)) ++q;
        if ( isdigit(*q) || *q == '+' || *q == '-' || *q == '.' || ! *q ) {
343 344 345 346 347 348
          if ( kml_dims < 2 ) lwpgerror("invalid KML representation"); /* (not enough ordinates)"); */
          else if ( kml_dims < 3 ) *hasz = false;
          if ( ! seen_kml_dims ) seen_kml_dims = kml_dims;
          else if ( seen_kml_dims != kml_dims ) {
            lwpgerror("invalid KML representation: mixed coordinates dimension");
          }
349
          ptarray_append_point(dpa, &pt, LW_TRUE);
350 351 352
          kml_dims = 0;
        }
        p = q-1; /* will be incrementedon next iteration */
353
//lwpgnotice("after look-ahead *p:%c, kml_dims:%d", *p, kml_dims);
354
    } else if ( *p != ',' && ! isspace(*p) ) {
355
          lwpgerror("invalid KML representation"); /* (unexpected character %c)", *p); */
356
    }
357 358 359 360
	}

	xmlFree(kml_coord);

361 362
	/* TODO: we shouldn't need to clone here */
	return ptarray_clone_deep(dpa);
363 364 365 366 367 368 369 370 371 372
}


/**
 * Parse KML point
 */
static LWGEOM* parse_kml_point(xmlNodePtr xnode, bool *hasz)
{
	POINTARRAY *pa;

373
	if (xnode->children == NULL) lwpgerror("invalid KML representation");
374
	pa = parse_kml_coordinates(xnode->children, hasz);
375
	if (pa->npoints != 1) lwpgerror("invalid KML representation");
376 377 378 379 380 381 382 383 384 385 386 387

	return (LWGEOM *) lwpoint_construct(4326, NULL, pa);
}


/**
 * Parse KML lineString
 */
static LWGEOM* parse_kml_line(xmlNodePtr xnode, bool *hasz)
{
	POINTARRAY *pa;

388
	if (xnode->children == NULL) lwpgerror("invalid KML representation");
389
	pa = parse_kml_coordinates(xnode->children, hasz);
390
	if (pa->npoints < 2) lwpgerror("invalid KML representation");
391 392 393 394 395 396 397 398 399 400 401 402 403

	return (LWGEOM *) lwline_construct(4326, NULL, pa);
}


/**
 * Parse KML Polygon
 */
static LWGEOM* parse_kml_polygon(xmlNodePtr xnode, bool *hasz)
{
	int ring;
	xmlNodePtr xa, xb;
	POINTARRAY **ppa = NULL;
404
	int outer_rings = 0;
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

	for (xa = xnode->children ; xa != NULL ; xa = xa->next)
	{

		/* Polygon/outerBoundaryIs */
		if (xa->type != XML_ELEMENT_NODE) continue;
		if (!is_kml_namespace(xa, false)) continue;
		if (strcmp((char *) xa->name, "outerBoundaryIs")) continue;

		for (xb = xa->children ; xb != NULL ; xb = xb->next)
		{

			if (xb->type != XML_ELEMENT_NODE) continue;
			if (!is_kml_namespace(xb, false)) continue;
			if (strcmp((char *) xb->name, "LinearRing")) continue;

			ppa = (POINTARRAY**) lwalloc(sizeof(POINTARRAY*));
			ppa[0] = parse_kml_coordinates(xb->children, hasz);

424 425 426
			if (ppa[0]->npoints < 4)
				lwpgerror("invalid KML representation");

427
			if ((!*hasz && !ptarray_is_closed_2d(ppa[0])) ||
428 429 430 431 432 433 434
			    ( *hasz && !ptarray_is_closed_3d(ppa[0])))
			{
				POINT4D pt;
				getPoint4d_p(ppa[0], 0, &pt);
				ptarray_append_point(ppa[0], &pt, LW_TRUE);
				lwpgnotice("forced closure on an un-closed KML polygon");
			}
435
			outer_rings++;
436 437
		}
	}
438 439 440
	
	if (outer_rings != 1)
		lwpgerror("invalid KML representation");
441
		
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
	for (ring=1, xa = xnode->children ; xa != NULL ; xa = xa->next)
	{

		/* Polygon/innerBoundaryIs */
		if (xa->type != XML_ELEMENT_NODE) continue;
		if (!is_kml_namespace(xa, false)) continue;
		if (strcmp((char *) xa->name, "innerBoundaryIs")) continue;

		for (xb = xa->children ; xb != NULL ; xb = xb->next)
		{

			if (xb->type != XML_ELEMENT_NODE) continue;
			if (!is_kml_namespace(xb, false)) continue;
			if (strcmp((char *) xb->name, "LinearRing")) continue;

457
			ppa = (POINTARRAY**) lwrealloc(ppa, sizeof(POINTARRAY*) * (ring + 1));
458 459
			ppa[ring] = parse_kml_coordinates(xb->children, hasz);

460 461 462
			if (ppa[ring]->npoints < 4)
				lwpgerror("invalid KML representation");

463
			if ((!*hasz && !ptarray_is_closed_2d(ppa[ring])) ||
464 465 466 467 468 469 470
			    ( *hasz && !ptarray_is_closed_3d(ppa[ring])))
			{
				POINT4D pt;
				getPoint4d_p(ppa[ring], 0, &pt);
				ptarray_append_point(ppa[ring], &pt, LW_TRUE);
				lwpgnotice("forced closure on an un-closed KML polygon");
			}
471 472 473 474 475 476

			ring++;
		}
	}

	/* Exterior Ring is mandatory */
477
	if (ppa == NULL || ppa[0] == NULL) lwpgerror("invalid KML representation");
478 479 480 481 482 483 484 485 486 487 488 489 490

	return (LWGEOM *) lwpoly_construct(4326, NULL, ring, ppa);
}


/**
 * Parse KML MultiGeometry
 */
static LWGEOM* parse_kml_multi(xmlNodePtr xnode, bool *hasz)
{
	LWGEOM *geom;
	xmlNodePtr xa;

491
	geom = (LWGEOM *)lwcollection_construct_empty(COLLECTIONTYPE, 4326, 1, 0);
492 493 494 495 496 497 498 499 500 501 502 503 504 505

	for (xa = xnode->children ; xa != NULL ; xa = xa->next)
	{

		if (xa->type != XML_ELEMENT_NODE) continue;
		if (!is_kml_namespace(xa, false)) continue;

		if (	   !strcmp((char *) xa->name, "Point")
		        || !strcmp((char *) xa->name, "LineString")
		        || !strcmp((char *) xa->name, "Polygon")
		        || !strcmp((char *) xa->name, "MultiGeometry"))
		{

			if (xa->children == NULL) break;
506
			geom = (LWGEOM*)lwcollection_add_lwgeom((LWCOLLECTION*)geom, parse_kml(xa, hasz));
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
		}
	}

	return geom;
}


/**
 * Parse KML
 */
static LWGEOM* parse_kml(xmlNodePtr xnode, bool *hasz)
{
	xmlNodePtr xa = xnode;

	while (xa != NULL && (xa->type != XML_ELEMENT_NODE
	                      || !is_kml_namespace(xa, false))) xa = xa->next;

524
	if (xa == NULL) lwpgerror("invalid KML representation");
525 526 527 528 529 530 531 532 533 534 535 536 537

	if (!strcmp((char *) xa->name, "Point"))
		return parse_kml_point(xa, hasz);

	if (!strcmp((char *) xa->name, "LineString"))
		return parse_kml_line(xa, hasz);

	if (!strcmp((char *) xa->name, "Polygon"))
		return parse_kml_polygon(xa, hasz);

	if (!strcmp((char *) xa->name, "MultiGeometry"))
		return parse_kml_multi(xa, hasz);

538
	lwpgerror("invalid KML representation");
539 540
	return NULL; /* Never reach */
}