mapkmlrenderer.cpp 41.5 KB
Newer Older
1
/******************************************************************************
2
 * $Id$
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * Project:  MapServer
 * Purpose:  Google Earth KML output
 * Author:   David Kana and the MapServer team
 *
 ******************************************************************************
 * Copyright (c) 1996-2009 Regents of the University of Minnesota.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
18
 * The above copyright notice and this permission notice shall be included in
19 20 21 22 23 24 25 26 27 28 29
 * all copies of this Software or works derived from this Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *****************************************************************************/

30
#include "mapserver-config.h"
31 32 33 34 35 36 37 38 39 40 41 42 43 44
#ifdef USE_KML

#include "mapserver.h"
#include "maperror.h"
#include "mapkmlrenderer.h"
#include "mapio.h"

#if defined(USE_OGR)
#  include "cpl_conv.h"
#  include "cpl_vsi.h"
#endif

#define  KML_MAXFEATURES_TODRAW 1000

45
KmlRenderer::KmlRenderer(int width, int height, outputFormatObj *format, colorObj* color/*=NULL*/)
46 47 48 49 50 51
  : Width(width), Height(height), MapCellsize(1.0), XmlDoc(NULL), LayerNode(NULL), GroundOverlayNode(NULL),
    PlacemarkNode(NULL), GeomNode(NULL),
    Items(NULL), NumItems(0), FirstLayer(MS_TRUE), map(NULL), currentLayer(NULL),
    mElevationFromAttribute( false ), mElevationAttributeIndex( -1 ), mCurrentElevationValue(0.0)

{
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  /*private variables*/
  pszLayerDescMetadata = NULL;
  papszLayerIncludeItems = NULL;
  nIncludeItems=0;
  papszLayerExcludeItems = NULL;
  nExcludeItems=0;
  pszLayerNameAttributeMetadata = NULL;  /*metadata to use for a name for each feature*/

  LineStyle = NULL;
  numLineStyle = 0;

  xmlNodePtr styleNode;
  xmlNodePtr listStyleNode;
  /*  Create document.*/
  XmlDoc = xmlNewDoc(BAD_CAST "1.0");
67

68
  xmlNodePtr rootNode = xmlNewNode(NULL, BAD_CAST "kml");
69

70 71
  /*  Name spaces*/
  xmlSetNs(rootNode, xmlNewNs(rootNode, BAD_CAST "http://www.opengis.net/kml/2.2", NULL));
72

73
  xmlDocSetRootElement(XmlDoc, rootNode);
74

75
  DocNode = xmlNewChild(rootNode, NULL, BAD_CAST "Document", NULL);
76

77 78 79 80
  styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
  xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_check");
  listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
  xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "check");
81

82 83 84 85
  styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
  xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_checkHideChildren");
  listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
  xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "checkHideChildren");
86

87 88 89 90
  styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
  xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_checkOffOnly");
  listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
  xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "checkOffOnly");
91

92 93 94 95
  styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
  xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST "LayerFolder_radioFolder");
  listStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "ListStyle", NULL);
  xmlNewChild(listStyleNode, NULL, BAD_CAST "listItemType", BAD_CAST "radioFolder");
96 97


98
  StyleHashTable = msCreateHashTable();
99 100 101 102 103

}

KmlRenderer::~KmlRenderer()
{
104 105
  if (XmlDoc)
    xmlFreeDoc(XmlDoc);
106

107 108
  if (StyleHashTable)
    msFreeHashTable(StyleHashTable);
109

110 111
  if(LineStyle)
    msFree(LineStyle);
112

113
  xmlCleanupParser();
114 115 116 117
}

imageObj* KmlRenderer::createImage(int, int, outputFormatObj*, colorObj*)
{
118
  return NULL;
119 120 121
}

int KmlRenderer::saveImage(imageObj *, FILE *fp, outputFormatObj *format)
122 123 124 125 126 127 128 129 130
{
  /* -------------------------------------------------------------------- */
  /*      Write out the document.                                         */
  /* -------------------------------------------------------------------- */

  int bufSize = 0;
  xmlChar *buf = NULL;
  msIOContext *context = NULL;
  int chunkSize = 4096;
131
#if defined(CPL_ZIP_API_OFFERED)
132
  int bZip = MS_FALSE;
133 134
#endif

135 136 137 138
  if( msIO_needBinaryStdout() == MS_FAILURE )
    return MS_FAILURE;

  xmlDocDumpFormatMemoryEnc(XmlDoc, &buf, &bufSize, "UTF-8", 1);
139 140

#if defined(USE_OGR)
141
  if (format && format->driver && strcasecmp(format->driver, "kmz") == 0) {
142
#if defined(CPL_ZIP_API_OFFERED)
143
    bZip = MS_TRUE;
144
#else
145 146 147 148
    msSetError( MS_MISCERR, "kmz format support unavailable, perhaps you need to upgrade to GDAL/OGR 1.8?",
                "KmlRenderer::saveImage()");
    xmlFree(buf);
    return MS_FAILURE;
149
#endif
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
  }

#if defined(CPL_ZIP_API_OFFERED)
  if (bZip) {
    VSILFILE *fpZip;
    int bytes_read;
    char buffer[1024];
    char *zip_filename =NULL;
    void *hZip=NULL;

    zip_filename = msTmpFile(NULL, NULL, "/vsimem/kmlzip/", "kmz" );
    hZip = CPLCreateZip( zip_filename, NULL );
    CPLCreateFileInZip( hZip, "mapserver.kml", NULL );
    for (int i=0; i<bufSize; i+=chunkSize) {
      int size = chunkSize;
      if (i + size > bufSize)
        size = bufSize - i;
      CPLWriteFileInZip( hZip,  buf+i, size);
168
    }
169 170
    CPLCloseFileInZip( hZip );
    CPLCloseZip( hZip );
171

172 173 174 175 176 177 178 179
    context = msIO_getHandler(fp);
    fpZip = VSIFOpenL( zip_filename, "r" );

    while( (bytes_read = VSIFReadL( buffer, 1, sizeof(buffer), fpZip )) > 0 ) {
      if (context)
        msIO_contextWrite(context, buffer, bytes_read);
      else
        msIO_fwrite( buffer, 1, bytes_read, fp );
180
    }
181 182 183 184 185
    VSIFCloseL( fpZip );
    msFree( zip_filename);
    xmlFree(buf);
    return(MS_SUCCESS);
  }
186 187 188 189
#endif

#endif

190
  context = msIO_getHandler(fp);
191 192


193 194 195 196 197 198 199 200 201 202 203 204 205 206
  for (int i=0; i<bufSize; i+=chunkSize) {
    int size = chunkSize;
    if (i + size > bufSize)
      size = bufSize - i;

    if (context)
      msIO_contextWrite(context, buf+i, size);
    else
      msIO_fwrite(buf+i, 1, size, fp);
  }

  xmlFree(buf);

  return(MS_SUCCESS);
207 208 209 210 211 212 213 214 215 216
}


/************************************************************************/
/*                               processLayer                           */
/*                                                                      */
/*      Set parameters that make sense to a kml output.                 */
/************************************************************************/
void KmlRenderer::processLayer(layerObj *layer, outputFormatObj *format)
{
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
  int i;
  const char *asRaster = NULL;
  int nMaxFeatures = -1;
  const char *pszTmp;
  char szTmp[10];

  if (!layer)
    return;

  /*turn of labelcache*/
  layer->labelcache = MS_OFF;

  /*if there are labels we want the coordinates to
    be the center of the element.*/
  for(i=0; i<layer->numclasses; i++)
    if(layer->_class[i]->numlabels > 0) layer->_class[i]->labels[0]->position = MS_XY;

  /*we do not want to draw multiple styles.
    the new rendering architecture does not allow
    to know if we are dealing with a multi-style.
    So here we remove all styles beside the first one*/

  for(i=0; i<layer->numclasses; i++) {
    while (layer->_class[i]->numstyles > 1)
      msDeleteStyle(layer->_class[i], layer->_class[i]->numstyles-1);
  }

  /*if layer has a metadata KML_OUTPUTASRASTER set to true, add a processing directive
    to use an agg driver*/
  asRaster = msLookupHashTable(&layer->metadata, "kml_outputasraster");
  if (!asRaster)
    asRaster = msLookupHashTable(&(layer->map->web.metadata), "kml_outputasraster");
  if (asRaster && (strcasecmp(asRaster, "true") == 0 ||
                   strcasecmp(asRaster, "yes") == 0))
    msLayerAddProcessing(layer, "RENDERER=png24");


  /*set a maxfeaturestodraw, if not already set*/

  pszTmp = msLookupHashTable(&layer->metadata, "maxfeaturestodraw");
  if (pszTmp)
    nMaxFeatures = atoi(pszTmp);
  else {
    pszTmp = msLookupHashTable(&layer->map->web.metadata, "maxfeaturestodraw");
261 262
    if (pszTmp)
      nMaxFeatures = atoi(pszTmp);
263 264 265 266 267 268 269 270
  }
  if (nMaxFeatures < 0 && format)
    nMaxFeatures = atoi(msGetOutputFormatOption( format, "maxfeaturestodraw", "-1"));

  if (nMaxFeatures < 0 && format) {
    snprintf(szTmp, sizeof(szTmp), "%d", KML_MAXFEATURES_TODRAW);
    msSetOutputFormatOption( format, "maxfeaturestodraw", szTmp);
  }
271 272 273 274 275 276 277 278 279 280

}

/************************************************************************/
/*                               getLayerName                           */
/*                                                                      */
/*      Internal utility function to build name used fo rthe layer.     */
/************************************************************************/
char* KmlRenderer::getLayerName(layerObj *layer)
{
281 282
  char stmp[20];
  const char *name=NULL;;
283

284 285
  if (!layer)
    return NULL;
286 287


288 289 290
  name = msLookupHashTable(&layer->metadata, "ows_name");
  if (name && strlen(name) > 0)
    return msStrdup(name);
291

292 293
  if (layer->name && strlen(layer->name) > 0)
    return msStrdup(layer->name);
294

295 296
  sprintf(stmp, "Layer%d",layer->index);
  return msStrdup(stmp);
297 298 299 300 301

}

const char* KmlRenderer::getAliasName(layerObj *lp, char *pszItemName, const char *namespaces)
{
302 303 304 305 306 307 308
  const char *pszAlias = NULL;
  if (lp && pszItemName && strlen(pszItemName) > 0) {
    char szTmp[256];
    snprintf(szTmp, sizeof(szTmp), "%s_alias", pszItemName);
    pszAlias = msOWSLookupMetadata(&(lp->metadata), namespaces, szTmp);
  }
  return pszAlias;
309 310 311 312
}

int KmlRenderer::startNewLayer(imageObj *img, layerObj *layer)
{
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
  char *layerName=NULL;
  const char *value=NULL;

  LayerNode = xmlNewNode(NULL, BAD_CAST "Folder");

  layerName = getLayerName(layer);
  xmlNewChild(LayerNode, NULL, BAD_CAST "name", BAD_CAST layerName);
  msFree(layerName);

  const char *layerVisibility = layer->status != MS_OFF ? "1" : "0";
  xmlNewChild(LayerNode, NULL, BAD_CAST "visibility", BAD_CAST layerVisibility);

  const char *layerDsiplayFolder = msLookupHashTable(&(layer->metadata), "kml_folder_display");
  if (layerDsiplayFolder == NULL)
    layerDsiplayFolder = msLookupHashTable(&(layer->map->web.metadata), "kml_folder_display");
  if (!layerDsiplayFolder || strlen(layerDsiplayFolder)<=0) {
    xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_check");
  }

  else {
    if (strcasecmp(layerDsiplayFolder, "checkHideChildren") == 0)
      xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_checkHideChildren");
    else if (strcasecmp(layerDsiplayFolder, "checkOffOnly") == 0)
      xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_checkOffOnly");
    else if (strcasecmp(layerDsiplayFolder, "radioFolder") == 0)
      xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_radioFolder");
339
    else
340 341
      xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_check");
  }
342 343


344 345 346 347
  /*Init few things on the first layer*/
  if (FirstLayer) {
    FirstLayer = MS_FALSE;
    map = layer->map;
348

349 350
    if (layer->map->mappath)
      snprintf(MapPath, sizeof(MapPath), "%s", layer->map->mappath);
351

352 353
    /*First rendered layer - check mapfile projection*/
    checkProjection(layer->map);
354

355 356 357
    /*check for image path and image url*/
    if (layer->map->debug && (layer->map->web.imageurl == NULL ||   layer->map->web.imagepath == NULL))
      msDebug("KmlRenderer::startNewLayer: imagepath and imageurl sould be set in the web object\n");
358 359


360 361 362 363
    /*map rect for ground overlay*/
    MapExtent = layer->map->extent;
    MapCellsize = layer->map->cellsize;
    BgColor = layer->map->imagecolor;
364

365 366 367
    xmlNewChild(DocNode, NULL, BAD_CAST "name", BAD_CAST layer->map->name);
    aggFormat = msSelectOutputFormat( layer->map, "png24");
    aggFormat->transparent = MS_TRUE;
368

369
  }
370

371
  currentLayer = layer;
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
  if (!msLayerIsOpen(layer)) {
    if (msLayerOpen(layer) != MS_SUCCESS) {
      msSetError(MS_MISCERR, "msLayerOpen failed", "KmlRenderer::startNewLayer" );
    }
  }

  /*pre process the layer to set things that make sense for kml output*/
  if (img)
    processLayer(layer, img->format);
  else
    processLayer(layer, NULL);

  if (msLookupHashTable(&layer->metadata, "kml_description"))
    pszLayerDescMetadata = msLookupHashTable(&layer->metadata, "kml_description");
  else if (msLookupHashTable(&layer->metadata, "ows_description"))
    pszLayerDescMetadata = msLookupHashTable(&layer->metadata, "ows_description");

  value=msLookupHashTable(&layer->metadata, "kml_include_items");
  if (!value)
    value=msLookupHashTable(&layer->metadata, "ows_include_items");
  if (value)
    papszLayerIncludeItems = msStringSplit(value, ',', &nIncludeItems);

  value=msLookupHashTable(&layer->metadata, "kml_exclude_items");
  if (!value)
    value=msLookupHashTable(&layer->metadata, "ows_exclude_items");
  if (value)
    papszLayerExcludeItems = msStringSplit(value, ',', &nExcludeItems);


  if (msLookupHashTable(&layer->metadata, "kml_name_item"))
    pszLayerNameAttributeMetadata = msLookupHashTable(&layer->metadata, "kml_name_item");

  /*get all attributes*/
  msLayerWhichItems(layer, MS_TRUE, NULL);


  NumItems = layer->numitems;
  if (NumItems) {
    Items = (char **)msSmallCalloc(NumItems, sizeof(char *));
    for (int i=0; i<NumItems; i++)
      Items[i] = msStrdup(layer->items[i]);
  }


  char* elevationAttribute = msLookupHashTable(&layer->metadata, "kml_elevation_attribute");
  if( elevationAttribute ) {
    mElevationFromAttribute = true;
    for( int i = 0; i < layer->numitems; ++i ) {
      if( strcasecmp( layer->items[i], elevationAttribute ) == 0 ) {
        mElevationAttributeIndex = i;
      }
    }
  }
427

428 429
  setupRenderingParams(&layer->metadata);
  return MS_SUCCESS;
430 431 432 433
}

int KmlRenderer::closeNewLayer(imageObj *img, layerObj *layer)
{
434
  flushPlacemark();
435

436
  xmlAddChild(DocNode, LayerNode);
437

438 439 440 441 442
  if(Items) {
    msFreeCharArray(Items, NumItems);
    Items = NULL;
    NumItems = 0;
  }
443

444 445 446 447
  if (pszLayerDescMetadata)
    pszLayerDescMetadata = NULL;
  if (pszLayerNameAttributeMetadata)
    pszLayerNameAttributeMetadata = NULL;
448

449 450 451
  if (papszLayerIncludeItems && nIncludeItems>0)
    msFreeCharArray(papszLayerIncludeItems, nIncludeItems);
  papszLayerIncludeItems=NULL;
452

453 454 455 456 457
  if (papszLayerExcludeItems && nExcludeItems>0)
    msFreeCharArray(papszLayerExcludeItems, nExcludeItems);
  papszLayerExcludeItems=NULL;

  return MS_SUCCESS;
458 459
}

460
int KmlRenderer::mergeRasterBuffer(imageObj *image, rasterBufferObj *rb)
461
{
462 463 464 465
  assert(rb && rb->type == MS_BUFFER_BYTE_RGBA);
  char *tmpFileName = NULL;
  char *tmpUrl = NULL;
  FILE *tmpFile = NULL;
466

467 468 469
  tmpFileName = msTmpFile(NULL, MapPath, image->imagepath, "png");
  tmpFile = fopen(tmpFileName,"wb");
  if (tmpFile) {
470

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    if (!aggFormat->vtable)
      msInitializeRendererVTable(aggFormat);

    msSaveRasterBuffer(map,rb,tmpFile,aggFormat);
    tmpUrl = msStrdup( image->imageurl);
    tmpUrl = msStringConcatenate(tmpUrl, (char *)(msGetBasename(tmpFileName)));
    tmpUrl = msStringConcatenate(tmpUrl, ".png");

    createGroundOverlayNode(LayerNode, tmpUrl, currentLayer);
    msFree(tmpFileName);
    msFree(tmpUrl);
    fclose(tmpFile);
    return MS_SUCCESS;
  } else {
    msSetError(MS_IOERR,"Failed to create file for kml overlay","KmlRenderer::mergeRasterBuffer()");
    return MS_FAILURE;
  }
}

void KmlRenderer::setupRenderingParams(hashTableObj *layerMetadata)
{
  AltitudeMode = 0;
  Extrude = 0;
  Tessellate = 0;

  char *altitudeModeVal = msLookupHashTable(layerMetadata, "kml_altitudeMode");
  if (altitudeModeVal) {
    if(strcasecmp(altitudeModeVal, "absolute") == 0)
      AltitudeMode = absolute;
    else if(strcasecmp(altitudeModeVal, "relativeToGround") == 0)
      AltitudeMode = relativeToGround;
    else if(strcasecmp(altitudeModeVal, "clampToGround") == 0)
      AltitudeMode = clampToGround;
  }

  char *extrudeVal = msLookupHashTable(layerMetadata, "kml_extrude");
  if (altitudeModeVal) {
    Extrude = atoi(extrudeVal);
  }

  char *tessellateVal = msLookupHashTable(layerMetadata, "kml_tessellate");
  if (tessellateVal) {
    Tessellate = atoi(tessellateVal);
  }
515 516 517 518 519

}

int KmlRenderer::checkProjection(mapObj *map)
{
520
  projectionObj *projection= &map->projection;
521
#ifdef USE_PROJ
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
  if (projection && projection->numargs > 0 && pj_is_latlong(projection->proj)) {
    return MS_SUCCESS;
  } else {
    char epsg_string[100];
    rectObj sRect;
    projectionObj out;

    /* for layer the do not have any projection set, set them with the current map
       projection*/
    if (projection && projection->numargs > 0) {
      layerObj *lp = NULL;
      int i =0;
      char *pszMapProjectString = msGetProjectionString(projection);
      if (pszMapProjectString) {
        for(i=0; i<map->numlayers; i++) {
          lp = GET_LAYER(map, i);
          if (lp->projection.numargs == 0 && lp->transform == MS_TRUE) {
            msFreeProjection(&lp->projection);
            msLoadProjectionString(&lp->projection, pszMapProjectString);
          }
542
        }
543 544 545 546 547 548
        msFree(pszMapProjectString);
      }
    }
    strcpy(epsg_string, "epsg:4326" );
    msInitProjection(&out);
    msLoadProjectionString(&out, epsg_string);
549

550 551 552 553
    sRect = map->extent;
    msProjectRect(projection, &out, &sRect);
    msFreeProjection(projection);
    msLoadProjectionString(projection, epsg_string);
554

555 556 557
    /*change also units and extents*/
    map->extent = sRect;
    map->units = MS_DD;
558 559


560 561
    if (map->debug)
      msDebug("KmlRenderer::checkProjection: Mapfile projection set to epsg:4326\n");
562

563 564
    return MS_SUCCESS;
  }
565 566

#else
567 568
  msSetError(MS_MISCERR, "Projection support not enabled", "KmlRenderer::checkProjection" );
  return MS_FAILURE;
569 570 571 572 573
#endif
}

xmlNodePtr KmlRenderer::createPlacemarkNode(xmlNodePtr parentNode, char *styleUrl)
{
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
  xmlNodePtr placemarkNode = xmlNewChild(parentNode, NULL, BAD_CAST "Placemark", NULL);
  /*always add a name. It will be replaced by a text value if available*/
  char tmpid[100];
  char *stmp=NULL, *layerName=NULL;
  if (CurrentShapeName && strlen(CurrentShapeName)>0) {
    xmlNewChild(placemarkNode, NULL, BAD_CAST "name", BAD_CAST CurrentShapeName);
  } else {
    sprintf(tmpid, ".%d", CurrentShapeIndex);
    layerName = getLayerName(currentLayer);
    stmp = msStringConcatenate(stmp, layerName);
    stmp = msStringConcatenate(stmp, tmpid);
    xmlNewChild(placemarkNode, NULL, BAD_CAST "name", BAD_CAST stmp);
  }
  msFree(layerName);
  msFree(stmp);
  if (styleUrl)
    xmlNewChild(placemarkNode, NULL, BAD_CAST "styleUrl", BAD_CAST styleUrl);

  return placemarkNode;
593 594 595 596
}

void KmlRenderer::renderLine(imageObj*, shapeObj *p, strokeStyleObj *style)
{
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
  if (p->numlines == 0)
    return;

  if (PlacemarkNode == NULL)
    PlacemarkNode = createPlacemarkNode(LayerNode, NULL);

  if (!PlacemarkNode)
    return;

  addLineStyleToList(style);
  SymbologyFlag[Line] = 1;

  /*p->index > CurrentDrawnShapeIndexneed to be reviewd. Added since the hight
    level code caches shapes when rendering lines*/
  if (CurrentDrawnShapeIndex == -1 || p->index > CurrentDrawnShapeIndex) {
    xmlNodePtr geomNode = getGeomParentNode("LineString");
    addAddRenderingSpecifications(geomNode);
    addCoordsNode(geomNode, p->line[0].point, p->line[0].numpoints);

    /* more than one line => MultiGeometry*/
    if (p->numlines > 1) {
      geomNode = getGeomParentNode("LineString"); // returns MultiGeom Node
      for (int i=1; i<p->numlines; i++) {
        xmlNodePtr lineStringNode = xmlNewChild(geomNode, NULL, BAD_CAST "LineString", NULL);
        addAddRenderingSpecifications(lineStringNode);
        addCoordsNode(lineStringNode, p->line[i].point, p->line[i].numpoints);
      }
624
    }
625 626 627 628

    CurrentDrawnShapeIndex = p->index;
  }

629 630 631 632
}

void KmlRenderer::renderPolygon(imageObj*, shapeObj *p, colorObj *color)
{
633 634
  if (PlacemarkNode == NULL)
    PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
635

636 637
  if (!PlacemarkNode)
    return;
638

639 640
  memcpy(&PolygonColor, color, sizeof(colorObj));
  SymbologyFlag[Polygon] = 1;
641 642


643
  if (p->index != CurrentDrawnShapeIndex) {
644

645
    xmlNodePtr geomParentNode = getGeomParentNode("Polygon");
646

647 648 649 650 651 652 653
    for (int i=0; i<p->numlines; i++) {
      xmlNodePtr bdryNode = NULL;

      if (i==0) /* __TODO__ check ring order*/
        bdryNode = xmlNewChild(geomParentNode, NULL, BAD_CAST "outerBoundaryIs", NULL);
      else
        bdryNode = xmlNewChild(geomParentNode, NULL, BAD_CAST "innerBoundaryIs", NULL);
654

655 656 657
      xmlNodePtr ringNode = xmlNewChild(bdryNode, NULL, BAD_CAST "LinearRing", NULL);
      addAddRenderingSpecifications(ringNode);
      addCoordsNode(ringNode, p->line[i].point, p->line[i].numpoints);
658
    }
659 660 661 662 663

    CurrentDrawnShapeIndex = p->index;

  }

664 665 666 667
}

void KmlRenderer::addCoordsNode(xmlNodePtr parentNode, pointObj *pts, int numPts)
{
668
  char lineBuf[128];
669

670 671
  xmlNodePtr coordsNode = xmlNewChild(parentNode, NULL, BAD_CAST "coordinates", NULL);
  xmlNodeAddContent(coordsNode, BAD_CAST "\n");
672

673 674 675 676
  for (int i=0; i<numPts; i++) {
    if( mElevationFromAttribute ) {
      sprintf(lineBuf, "\t%.8f,%.8f,%.8f\n", pts[i].x, pts[i].y, mCurrentElevationValue);
    } else if (AltitudeMode == relativeToGround || AltitudeMode == absolute) {
677
#ifdef USE_POINT_Z_M
678
      sprintf(lineBuf, "\t%.8f,%.8f,%.8f\n", pts[i].x, pts[i].y, pts[i].z);
679
#else
680
      msSetError(MS_MISCERR, "Z coordinates support not available  (mapserver not compiled with USE_POINT_Z_M option)", "KmlRenderer::addCoordsNode()");
681
#endif
682 683
    } else
      sprintf(lineBuf, "\t%.8f,%.8f\n", pts[i].x, pts[i].y);
684

685 686 687
    xmlNodeAddContent(coordsNode, BAD_CAST lineBuf);
  }
  xmlNodeAddContent(coordsNode, BAD_CAST "\t");
688 689 690 691
}

void KmlRenderer::renderGlyphs(imageObj*, double x, double y, labelStyleObj *style, char *text)
{
692
  xmlNodePtr node;
693

694 695
  if (PlacemarkNode == NULL)
    PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
696

697 698
  if (!PlacemarkNode)
    return;
699

700 701
  memcpy(&LabelStyle, style, sizeof(labelStyleObj));
  SymbologyFlag[Label] = 1;
702

703 704 705 706
  /*there is alaws a default name (layer.shapeid). Replace it*/
  for (node = PlacemarkNode->children; node; node = node->next) {
    if (node->type != XML_ELEMENT_NODE)
      continue;
707

708 709 710
    if (strcmp((char *)node->name, "name") == 0) {
      xmlNodeSetContent(node,  BAD_CAST text);
      break;
711
    }
712
  }
713

714 715 716 717
  /*xmlNewChild(PlacemarkNode, NULL, BAD_CAST "name", BAD_CAST text);*/

  xmlNodePtr geomNode = getGeomParentNode("Point");
  addAddRenderingSpecifications(geomNode);
718

719 720 721 722
  pointObj pt;
  pt.x = x;
  pt.y = y;
  addCoordsNode(geomNode, &pt, 1);
723 724 725 726
}

void KmlRenderer::addAddRenderingSpecifications(xmlNodePtr node)
{
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
  /*
    <extrude>0</extrude>                   <!-- boolean -->
    <tessellate>0</tessellate>             <!-- boolean -->
    <altitudeMode>clampToGround</altitudeMode>
  */

  if (Extrude)
    xmlNewChild(node, NULL, BAD_CAST "extrude", BAD_CAST "1");

  if (Tessellate)
    xmlNewChild(node, NULL, BAD_CAST "tessellate", BAD_CAST "1");

  if (AltitudeMode == absolute)
    xmlNewChild(node, NULL, BAD_CAST "altitudeMode", BAD_CAST "absolute");
  else if (AltitudeMode == relativeToGround)
    xmlNewChild(node, NULL, BAD_CAST "altitudeMode", BAD_CAST "relativeToGround");
  else if (AltitudeMode == clampToGround)
    xmlNewChild(node, NULL, BAD_CAST "altitudeMode", BAD_CAST "clampToGround");
745 746 747 748 749 750 751
}


imageObj *agg2CreateImage(int width, int height, outputFormatObj *format, colorObj * bg);

int KmlRenderer::createIconImage(char *fileName, symbolObj *symbol, symbolStyleObj *symstyle)
{
752 753 754
  pointObj p;

  imageObj *tmpImg = NULL;
755

756 757 758 759 760 761 762 763 764
  tmpImg = agg2CreateImage((int)(symbol->sizex*symstyle->scale),
                           (int)(symbol->sizey*symstyle->scale),
                           aggFormat, NULL);
  tmpImg->format = aggFormat;
  if (!aggFormat->vtable)
    msInitializeRendererVTable(aggFormat);

  p.x = symbol->sizex * symstyle->scale / 2;
  p.y = symbol->sizey *symstyle->scale / 2;
765
#ifdef USE_POINT_Z_M
766
  p.z = 0.0;
767 768
#endif

769
  msDrawMarkerSymbol(&map->symbolset,tmpImg, &p, symstyle->style, 1);
770

771
  return msSaveImage(map, tmpImg, fileName);
772 773 774 775
}

void KmlRenderer::renderSymbol(imageObj *img, double x, double y, symbolObj *symbol, symbolStyleObj *style)
{
776 777
  if (PlacemarkNode == NULL)
    PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
778

779 780
  if (!PlacemarkNode)
    return;
781

782 783
  snprintf(SymbolUrl, sizeof(SymbolUrl), "%s", lookupSymbolUrl(img, symbol, style));
  SymbologyFlag[Symbol] = 1;
784

785 786
  xmlNodePtr geomNode = getGeomParentNode("Point");
  addAddRenderingSpecifications(geomNode);
787

788 789 790 791
  pointObj pt;
  pt.x = x;
  pt.y = y;
  addCoordsNode(geomNode, &pt, 1);
792 793
}

794
void KmlRenderer::renderPixmapSymbol(imageObj *img, double x, double y, symbolObj *symbol,
795 796
                                     symbolStyleObj *style)
{
797
  renderSymbol(img, x, y, symbol, style);
798 799
}

800
void KmlRenderer::renderVectorSymbol(imageObj *img, double x, double y, symbolObj *symbol,
801 802
                                     symbolStyleObj *style)
{
803
  renderSymbol(img, x, y, symbol, style);
804 805
}

806
void KmlRenderer::renderEllipseSymbol(imageObj *img, double x, double y, symbolObj *symbol,
807 808
                                      symbolStyleObj *style)
{
809
  renderSymbol(img, x, y, symbol, style);
810 811
}

812
void KmlRenderer::renderTruetypeSymbol(imageObj *img, double x, double y, symbolObj *symbol,
813 814
                                       symbolStyleObj *style)
{
815
  renderSymbol(img, x, y, symbol, style);
816 817 818 819
}

xmlNodePtr KmlRenderer::createGroundOverlayNode(xmlNodePtr parentNode, char *imageHref, layerObj *layer)
{
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
  /*
    <?xml version="1.0" encoding="UTF-8"?>
    <kml xmlns="http://www.opengis.net/kml/2.2">
    <GroundOverlay>
    <name>GroundOverlay.kml</name>
    <color>7fffffff</color>
    <drawOrder>1</drawOrder>
    <Icon>
    <href>http://www.google.com/intl/en/images/logo.gif</href>
    <refreshMode>onInterval</refreshMode>
    <refreshInterval>86400</refreshInterval>
    <viewBoundScale>0.75</viewBoundScale>
    </Icon>
    <LatLonBox>
    <north>37.83234</north>
    <south>37.832122</south>
    <east>-122.373033</east>
    <west>-122.373724</west>
    <rotation>45</rotation>
    </LatLonBox>
    </GroundOverlay>
    </kml>
  */
  char  layerHexColor[32];
  xmlNodePtr groundOverlayNode = xmlNewChild(parentNode, NULL, BAD_CAST "GroundOverlay", NULL);
  char *layerName = getLayerName(layer);
  xmlNewChild(groundOverlayNode, NULL, BAD_CAST "name", BAD_CAST layerName);
  if (layer->opacity > 0 && layer->opacity < 100) {
    sprintf(layerHexColor, "%02xffffff", (unsigned int)MS_NINT(layer->opacity*2.55));
    xmlNewChild(groundOverlayNode, NULL, BAD_CAST "color", BAD_CAST layerHexColor);
  } else
    xmlNewChild(groundOverlayNode, NULL, BAD_CAST "color", BAD_CAST "ffffffff");
  char stmp[20];
  sprintf(stmp, "%d",layer->index);
  xmlNewChild(groundOverlayNode, NULL, BAD_CAST "drawOrder", BAD_CAST stmp);

  if (imageHref) {
    xmlNodePtr iconNode = xmlNewChild(groundOverlayNode, NULL, BAD_CAST "Icon", NULL);
    xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST imageHref);
  }

  char crdStr[64];
  rectObj mapextent;
  if (map->gt.need_geotransform == MS_TRUE)
    mapextent = currentLayer->map->saved_extent;
  else
    mapextent = currentLayer->map->extent;

  xmlNodePtr latLonBoxNode = xmlNewChild(groundOverlayNode, NULL, BAD_CAST "LatLonBox", NULL);
  sprintf(crdStr, "%.8f", mapextent.maxy);
  xmlNewChild(latLonBoxNode, NULL, BAD_CAST "north", BAD_CAST crdStr);

  sprintf(crdStr, "%.8f", mapextent.miny);
  xmlNewChild(latLonBoxNode, NULL, BAD_CAST "south", BAD_CAST crdStr);

  sprintf(crdStr, "%.8f", mapextent.minx);
  xmlNewChild(latLonBoxNode, NULL, BAD_CAST "west", BAD_CAST crdStr);

  sprintf(crdStr, "%.8f", mapextent.maxx);
  xmlNewChild(latLonBoxNode, NULL, BAD_CAST "east", BAD_CAST crdStr);

  xmlNewChild(latLonBoxNode, NULL, BAD_CAST "rotation", BAD_CAST "0.0");

  return groundOverlayNode;
884 885 886 887
}

void KmlRenderer::startShape(imageObj *, shapeObj *shape)
{
888 889
  if (PlacemarkNode)
    flushPlacemark();
890

891 892 893
  CurrentShapeIndex=-1;
  CurrentDrawnShapeIndex = -1;
  CurrentShapeName=NULL;
894

895 896 897
  /*should be done at endshape but the plugin architecture does not call endshape yet*/
  if(LineStyle) {
    msFree(LineStyle);
898

899 900 901 902 903 904 905 906 907 908 909
    LineStyle = NULL;
    numLineStyle = 0;
  }

  if (shape) {
    CurrentShapeIndex = shape->index;
    if (pszLayerNameAttributeMetadata) {
      for (int i=0; i<currentLayer->numitems; i++) {
        if (strcasecmp(currentLayer->items[i], pszLayerNameAttributeMetadata) == 0 && shape->values[i]) {
          CurrentShapeName = msStrdup(shape->values[i]);
          break;
910
        }
911
      }
912
    }
913 914 915
  }
  PlacemarkNode = NULL;
  GeomNode = NULL;
916

917
  DescriptionNode = createDescriptionNode(shape);
918

919 920 921 922
  if( mElevationFromAttribute && shape->numvalues > mElevationAttributeIndex &&
      mElevationAttributeIndex >= 0 && shape->values[mElevationAttributeIndex]) {
    mCurrentElevationValue = atof( shape->values[mElevationAttributeIndex] );
  }
923 924


925
  memset(SymbologyFlag, 0, NumSymbologyFlag);
926 927 928 929
}

void KmlRenderer::endShape(imageObj*, shapeObj*)
{
930 931 932 933
  CurrentShapeIndex = -1;
  if (CurrentShapeName)
    msFree(CurrentShapeName);
  CurrentShapeName = NULL;
934 935 936 937
}

xmlNodePtr KmlRenderer::getGeomParentNode(const char *geomName)
{
938 939 940 941 942 943 944 945 946 947 948 949 950
  /*we do not need a multi-geometry for point layers*/
  if (currentLayer->type != MS_LAYER_POINT && currentLayer->type != MS_LAYER_ANNOTATION && GeomNode) {
    /*placemark geometry already defined, we need multigeometry node*/
    xmlNodePtr multiGeomNode = xmlNewNode(NULL, BAD_CAST "MultiGeometry");
    xmlAddChild(multiGeomNode, GeomNode);
    GeomNode = multiGeomNode;

    xmlNodePtr geomNode = xmlNewChild(multiGeomNode, NULL, BAD_CAST geomName, NULL);
    return geomNode;
  } else {
    GeomNode = xmlNewNode(NULL, BAD_CAST geomName);
    return GeomNode;
  }
951 952 953 954
}

char* KmlRenderer::lookupSymbolUrl(imageObj *img, symbolObj *symbol, symbolStyleObj *symstyle)
{
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
  char  symbolHexColor[32];
  /*
      <Style id="randomColorIcon">
      <IconStyle>
      <color>ff00ff00</color>
      <colorMode>random</colorMode>
      <scale>1.1</scale>
      <Icon>
      <href>http://maps.google.com/mapfiles/kml/pal3/icon21.png</href>
      </Icon>
      </IconStyle>
      </Style>
  */

  sprintf(symbolHexColor,"%02x%02x%02x%02x", symstyle->style->color.alpha, symstyle->style->color.blue,
          symstyle->style->color.green, symstyle->style->color.red);
  snprintf(SymbolName, sizeof(SymbolName), "symbol_%s_%.1f_%s", symbol->name, symstyle->scale, symbolHexColor);

  char *symbolUrl = msLookupHashTable(StyleHashTable, SymbolName);
  if (!symbolUrl) {
    char iconFileName[MS_MAXPATHLEN];
    char iconUrl[MS_MAXPATHLEN];

    if (img->imagepath) {
      char *tmpFileName = msTmpFile(NULL, MapPath, img->imagepath, "png");
      snprintf(iconFileName, sizeof(iconFileName), "%s", tmpFileName);
      msFree(tmpFileName);
    } else {
      sprintf(iconFileName, "symbol_%s_%.1f.%s", symbol->name, symstyle->scale, "png");
    }
985

986
    if (createIconImage(iconFileName, symbol, symstyle) != MS_SUCCESS) {
987
      msSetError(MS_IOERR, "Error creating icon file '%s'", "KmlRenderer::lookupSymbolStyle()", iconFileName);
988 989
      return NULL;
    }
990

991 992 993 994
    if (img->imageurl)
      sprintf(iconUrl, "%s%s.%s", img->imageurl, msGetBasename(iconFileName), "png");
    else
      snprintf(iconUrl, sizeof(iconUrl), "%s", iconFileName);
995

996 997 998
    hashObj *hash = msInsertHashTable(StyleHashTable, SymbolName, iconUrl);
    symbolUrl = hash->data;
  }
999

1000
  return symbolUrl;
1001 1002 1003 1004
}

char* KmlRenderer::lookupPlacemarkStyle()
{
1005 1006 1007 1008
  char  lineHexColor[32];
  char  polygonHexColor[32];
  char  labelHexColor[32];
  char        *styleName=NULL;
1009

1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
  styleName = msStringConcatenate(styleName, "style");

  if (SymbologyFlag[Line]) {
    /*
      <LineStyle id="ID">
      <!-- inherited from ColorStyle -->
      <color>ffffffff</color>            <!-- kml:color -->
      <colorMode>normal</colorMode>      <!-- colorModeEnum: normal or random -->

      <!-- specific to LineStyle -->
      <width>1</width>                   <!-- float -->
      </LineStyle>
    */
1023

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
    for (int i=0; i<numLineStyle; i++) {
      if (currentLayer && currentLayer->opacity > 0 && currentLayer->opacity < 100 &&
          LineStyle[i].color->alpha == 255)
        LineStyle[i].color->alpha = MS_NINT(currentLayer->opacity*2.55);

      sprintf(lineHexColor,"%02x%02x%02x%02x", LineStyle[i].color->alpha, LineStyle[0].color->blue,
              LineStyle[i].color->green, LineStyle[i].color->red);

      char lineStyleName[32];
      sprintf(lineStyleName, "_line_%s_w%.1f", lineHexColor, LineStyle[i].width);
      styleName = msStringConcatenate(styleName, lineStyleName);
1035
    }
1036
  }
1037

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
  if (SymbologyFlag[Polygon]) {
    /*
      <PolyStyle id="ID">
      <!-- inherited from ColorStyle -->
      <color>ffffffff</color>            <!-- kml:color -->
      <colorMode>normal</colorMode>      <!-- kml:colorModeEnum: normal or random -->

      <!-- specific to PolyStyle -->
      <fill>1</fill>                     <!-- boolean -->
      <outline>1</outline>               <!-- boolean -->
      </PolyStyle>
    */

    if (currentLayer && currentLayer->opacity > 0 && currentLayer->opacity < 100 &&
        PolygonColor.alpha == 255)
      PolygonColor.alpha = MS_NINT(currentLayer->opacity*2.55);
    sprintf(polygonHexColor,"%02x%02x%02x%02x", PolygonColor.alpha, PolygonColor.blue, PolygonColor.green, PolygonColor.red);

    char polygonStyleName[64];
    sprintf(polygonStyleName, "_polygon_%s", polygonHexColor);
    styleName = msStringConcatenate(styleName, polygonStyleName);
  }

  if (SymbologyFlag[Label]) {
    /*
      <LabelStyle id="ID">
      <!-- inherited from ColorStyle -->
      <color>ffffffff</color>            <!-- kml:color -->
      <colorMode>normal</colorMode>      <!-- kml:colorModeEnum: normal or random -->

      <!-- specific to LabelStyle -->
      <scale>1</scale>                   <!-- float -->
      </LabelStyle>
    */

    if (currentLayer && currentLayer->opacity > 0 && currentLayer->opacity < 100 &&
        LabelStyle.color->alpha == 255)
      LabelStyle.color->alpha = MS_NINT(currentLayer->opacity*2.55);
    sprintf(labelHexColor,"%02x%02x%02x%02x", LabelStyle.color->alpha, LabelStyle.color->blue, LabelStyle.color->green, LabelStyle.color->red);

    // __TODO__ add label scale

    char labelStyleName[64];
    sprintf(labelStyleName, "_label_%s", labelHexColor);
    styleName = msStringConcatenate(styleName, labelStyleName);
  }

  if (SymbologyFlag[Symbol]) {
    /*
    <Style id="randomColorIcon">
            <IconStyle>
            <color>ff00ff00</color>
            <colorMode>random</colorMode>
            <scale>1.1</scale>
            <Icon>
            <href>http://maps.google.com/mapfiles/kml/pal3/icon21.png</href>
            </Icon>
            </IconStyle>
    </Style>
    */

    /* __TODO__ add label scale */

    styleName = msStringConcatenate(styleName, "_");
    styleName = msStringConcatenate(styleName, SymbolName);
  }

  char *styleUrl = msLookupHashTable(StyleHashTable, styleName);
  if (!styleUrl) {
    char *styleValue=NULL;
    styleValue = msStringConcatenate(styleValue, "#");
    styleValue = msStringConcatenate(styleValue, styleName);
    hashObj *hash = msInsertHashTable(StyleHashTable, styleName, styleValue);
    styleUrl = hash->data;
    msFree(styleValue);

    /* Insert new Style node into Document node*/
    xmlNodePtr styleNode = xmlNewChild(DocNode, NULL, BAD_CAST "Style", NULL);
    xmlNewProp(styleNode, BAD_CAST "id", BAD_CAST styleName);

    if (SymbologyFlag[Polygon]) {
      xmlNodePtr polyStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "PolyStyle", NULL);
      xmlNewChild(polyStyleNode, NULL, BAD_CAST "color", BAD_CAST polygonHexColor);
1121 1122
    }

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
    if (SymbologyFlag[Line]) {
      for (int i=0; i<numLineStyle; i++) {
        xmlNodePtr lineStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "LineStyle", NULL);
        sprintf(lineHexColor,"%02x%02x%02x%02x", LineStyle[i].color->alpha, LineStyle[i].color->blue,
                LineStyle[i].color->green, LineStyle[i].color->red);
        xmlNewChild(lineStyleNode, NULL, BAD_CAST "color", BAD_CAST lineHexColor);

        char width[16];
        sprintf(width, "%.1f", LineStyle[i].width);
        xmlNewChild(lineStyleNode, NULL, BAD_CAST "width", BAD_CAST width);
      }
    }
1135

1136 1137
    if (SymbologyFlag[Symbol]) {
      xmlNodePtr iconStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "IconStyle", NULL);
1138

1139 1140
      xmlNodePtr iconNode = xmlNewChild(iconStyleNode, NULL, BAD_CAST "Icon", NULL);
      xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST SymbolUrl);
1141

1142 1143 1144 1145 1146 1147 1148
      /*char scale[16];
        sprintf(scale, "%.1f", style->scale);
        xmlNewChild(iconStyleNode, NULL, BAD_CAST "scale", BAD_CAST scale);*/
    } else {
      const char *value=msLookupHashTable(&currentLayer->metadata, "kml_default_symbol_href");
      if (value && strlen(value) > 0) {
        xmlNodePtr iconStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "IconStyle", NULL);
1149

1150 1151 1152 1153
        xmlNodePtr iconNode = xmlNewChild(iconStyleNode, NULL, BAD_CAST "Icon", NULL);
        xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST value);
      }
    }
1154

1155 1156 1157
    if (SymbologyFlag[Label]) {
      xmlNodePtr labelStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "LabelStyle", NULL);
      xmlNewChild(labelStyleNode, NULL, BAD_CAST "color", BAD_CAST labelHexColor);
1158

1159 1160 1161
      /*char scale[16];
        sprintf(scale, "%.1f", style->scale);
        xmlNewChild(iconStyleNode, NULL, BAD_CAST "scale", BAD_CAST scale);*/
1162
    }
1163
  }
1164

1165 1166
  if (styleName)
    msFree(styleName);
1167

1168
  return styleUrl;
1169 1170 1171 1172
}

void KmlRenderer::flushPlacemark()
{
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
  if (PlacemarkNode) {
    char *styleUrl = lookupPlacemarkStyle();
    xmlNewChild(PlacemarkNode, NULL, BAD_CAST "styleUrl", BAD_CAST styleUrl);

    if (DescriptionNode)
      xmlAddChild(PlacemarkNode, DescriptionNode);

    if (GeomNode)
      xmlAddChild(PlacemarkNode, GeomNode);
  }
1183 1184 1185 1186 1187
}


xmlNodePtr KmlRenderer::createDescriptionNode(shapeObj *shape)
{
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
  /*
    <description>
    <![CDATA[
    special characters here
    ]]>
    <description>
  */


  /*description nodes for vector layers:
    - if kml_description is set, use it
    - if not, dump the attributes */

  if (pszLayerDescMetadata) {
    char *pszTmp=NULL;
    char *pszTmpDesc = NULL;
    size_t bufferSize = 0;
    pszTmpDesc = msStrdup(pszLayerDescMetadata);

    for (int i=0; i<currentLayer->numitems; i++) {
      bufferSize = strlen(currentLayer->items[i]) + 3;
      pszTmp = (char *)msSmallMalloc(bufferSize);
      snprintf(pszTmp, bufferSize, "%%%s%%",currentLayer->items[i]);
      if (strcasestr(pszTmpDesc, pszTmp))
        pszTmpDesc = msCaseReplaceSubstring(pszTmpDesc,  pszTmp, shape->values[i]);
      msFree(pszTmp);
1214
    }
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
    xmlNodePtr descriptionNode = xmlNewNode(NULL, BAD_CAST "description");
    xmlNodeAddContent(descriptionNode, BAD_CAST pszTmpDesc);
    msFree(pszTmpDesc);
    return descriptionNode;
  } else if ((papszLayerIncludeItems && nIncludeItems > 0) ||
             (papszLayerExcludeItems && nExcludeItems > 0)) {
    /* -------------------------------------------------------------------- */
    /*      preffered way is to use the ExtendedData tag (#3728)            */
    /*      http://code.google.com/apis/kml/documentation/extendeddata.html */
    /* -------------------------------------------------------------------- */

    xmlNodePtr extendedDataNode = xmlNewNode(NULL, BAD_CAST "ExtendedData");
    xmlNodePtr dataNode = NULL;
    const char*pszAlias=NULL;
    int bIncludeAll = MS_FALSE;

    if(papszLayerIncludeItems && nIncludeItems == 1 &&
        strcasecmp(papszLayerIncludeItems[0], "all") == 0)
      bIncludeAll = MS_TRUE;

    for (int i=0; i<currentLayer->numitems; i++) {
      int j=0,k=0;

      /*TODO optimize to calculate this only once per layer*/
      for (j=0; j<nIncludeItems; j++) {
        if (strcasecmp(currentLayer->items[i], papszLayerIncludeItems[j]) == 0)
          break;
      }
      if (j<nIncludeItems || bIncludeAll) {
        if (papszLayerExcludeItems && nExcludeItems > 0) {
          for (k=0; k<nExcludeItems; k++) {
            if (strcasecmp(currentLayer->items[i], papszLayerExcludeItems[k]) == 0)
              break;
          }
        }
        if (nExcludeItems == 0 || k == nExcludeItems) {
          dataNode = xmlNewNode(NULL, BAD_CAST "Data");
          xmlNewProp(dataNode, BAD_CAST "name", BAD_CAST  currentLayer->items[i]);
          pszAlias = getAliasName(currentLayer, currentLayer->items[i], "GO");
          if (pszAlias)
            xmlNewChild(dataNode, NULL, BAD_CAST "displayName", BAD_CAST  pszAlias);
          else
            xmlNewChild(dataNode, NULL, BAD_CAST "displayName", BAD_CAST  currentLayer->items[i]);
          if (shape->values[i] && strlen(shape->values[i]))
            xmlNewChild(dataNode, NULL, BAD_CAST "value", BAD_CAST  shape->values[i]);
          else
            xmlNewChild(dataNode, NULL, BAD_CAST "value", NULL);
          xmlAddChild(extendedDataNode, dataNode);
1263
        }
1264 1265
      }
    }
1266

1267
    return extendedDataNode;
1268 1269


1270 1271 1272
  }

  return NULL;
1273 1274 1275 1276
}

void KmlRenderer::addLineStyleToList(strokeStyleObj *style)
{
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
  /*actually this is not necessary. kml only uses the last LineStyle
    so we should not bother keeping them all*/
  int i =0;
  for (i=0; i<numLineStyle; i++) {
    if (style->width == LineStyle[i].width &&
        LineStyle[i].color->alpha == style->color->alpha &&
        LineStyle[i].color->red == style->color->red &&
        LineStyle[i].color->green == style->color->green &&
        LineStyle[i].color->blue == style->color->blue)
      break;
  }
  if (i == numLineStyle) {
    numLineStyle++;
    if (LineStyle == NULL)
      LineStyle = (strokeStyleObj *)msSmallMalloc(sizeof(strokeStyleObj));
    else
      LineStyle = (strokeStyleObj *)msSmallRealloc(LineStyle, sizeof(strokeStyleObj)*numLineStyle);

    memcpy(&LineStyle[numLineStyle-1], style, sizeof(strokeStyleObj));
  }
1297 1298 1299 1300

}

#endif