mapkmlrenderer.cpp 41.8 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
#ifdef USE_KML

#include "mapserver.h"
#include "maperror.h"
#include "mapkmlrenderer.h"
#include "mapio.h"
37
#include "mapows.h"
38 39 40 41 42 43 44 45

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

#define  KML_MAXFEATURES_TODRAW 1000

46
KmlRenderer::KmlRenderer(int width, int height, outputFormatObj *format, colorObj* color/*=NULL*/)
47 48 49 50 51 52
  : 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)

{
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
  /*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");
68

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

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

74
  xmlDocSetRootElement(XmlDoc, rootNode);
75

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

78 79 80 81
  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");
82

83 84 85 86
  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");
87

88 89 90 91
  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");
92

93 94 95 96
  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");
97 98


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

}

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

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

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

114
  xmlCleanupParser();
115 116 117 118
}

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

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

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

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

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

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

#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);
169
    }
170 171
    CPLCloseFileInZip( hZip );
    CPLCloseZip( hZip );
172

173 174 175 176 177 178 179 180
    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 );
181
    }
182 183 184 185 186
    VSIFCloseL( fpZip );
    msFree( zip_filename);
    xmlFree(buf);
    return(MS_SUCCESS);
  }
187 188 189 190
#endif

#endif

191
  context = msIO_getHandler(fp);
192 193


194 195 196 197 198 199 200 201 202 203 204 205 206 207
  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);
208 209 210 211 212 213 214 215 216 217
}


/************************************************************************/
/*                               processLayer                           */
/*                                                                      */
/*      Set parameters that make sense to a kml output.                 */
/************************************************************************/
void KmlRenderer::processLayer(layerObj *layer, outputFormatObj *format)
{
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
  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");
262 263
    if (pszTmp)
      nMaxFeatures = atoi(pszTmp);
264 265 266 267 268 269 270 271
  }
  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);
  }
272 273 274 275 276 277 278 279 280 281

}

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

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


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

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

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

}

const char* KmlRenderer::getAliasName(layerObj *lp, char *pszItemName, const char *namespaces)
{
303 304 305 306 307 308 309
  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;
310 311 312 313
}

int KmlRenderer::startNewLayer(imageObj *img, layerObj *layer)
{
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
  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");
340
    else
341 342
      xmlNewChild(LayerNode, NULL, BAD_CAST "styleUrl", BAD_CAST "#LayerFolder_check");
  }
343 344


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

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

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

356 357 358
    /*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");
359 360


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

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

370
  }
371

372
  currentLayer = layer;
373

374 375 376
  if (!msLayerIsOpen(layer)) {
    if (msLayerOpen(layer) != MS_SUCCESS) {
      msSetError(MS_MISCERR, "msLayerOpen failed", "KmlRenderer::startNewLayer" );
377
      return MS_FAILURE;
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
    }
  }

  /*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*/
409 410 411
  if(msLayerWhichItems(layer, MS_TRUE, NULL) != MS_SUCCESS) {
    return MS_FAILURE;
  }
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430


  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;
      }
    }
  }
431

432 433
  setupRenderingParams(&layer->metadata);
  return MS_SUCCESS;
434 435 436 437
}

int KmlRenderer::closeNewLayer(imageObj *img, layerObj *layer)
{
438
  flushPlacemark();
439

440
  xmlAddChild(DocNode, LayerNode);
441

442 443 444 445 446
  if(Items) {
    msFreeCharArray(Items, NumItems);
    Items = NULL;
    NumItems = 0;
  }
447

448 449 450 451
  if (pszLayerDescMetadata)
    pszLayerDescMetadata = NULL;
  if (pszLayerNameAttributeMetadata)
    pszLayerNameAttributeMetadata = NULL;
452

453 454 455
  if (papszLayerIncludeItems && nIncludeItems>0)
    msFreeCharArray(papszLayerIncludeItems, nIncludeItems);
  papszLayerIncludeItems=NULL;
456

457 458 459 460 461
  if (papszLayerExcludeItems && nExcludeItems>0)
    msFreeCharArray(papszLayerExcludeItems, nExcludeItems);
  papszLayerExcludeItems=NULL;

  return MS_SUCCESS;
462 463
}

464
int KmlRenderer::mergeRasterBuffer(imageObj *image, rasterBufferObj *rb)
465
{
466 467 468 469
  assert(rb && rb->type == MS_BUFFER_BYTE_RGBA);
  char *tmpFileName = NULL;
  char *tmpUrl = NULL;
  FILE *tmpFile = NULL;
470

471 472 473
  tmpFileName = msTmpFile(NULL, MapPath, image->imagepath, "png");
  tmpFile = fopen(tmpFileName,"wb");
  if (tmpFile) {
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 515 516 517 518
    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);
  }
519 520 521 522 523

}

int KmlRenderer::checkProjection(mapObj *map)
{
524
  projectionObj *projection= &map->projection;
525
#ifdef USE_PROJ
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
  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);
          }
546
        }
547 548 549 550 551 552
        msFree(pszMapProjectString);
      }
    }
    strcpy(epsg_string, "epsg:4326" );
    msInitProjection(&out);
    msLoadProjectionString(&out, epsg_string);
553

554 555 556 557
    sRect = map->extent;
    msProjectRect(projection, &out, &sRect);
    msFreeProjection(projection);
    msLoadProjectionString(projection, epsg_string);
558

559 560 561
    /*change also units and extents*/
    map->extent = sRect;
    map->units = MS_DD;
562 563


564 565
    if (map->debug)
      msDebug("KmlRenderer::checkProjection: Mapfile projection set to epsg:4326\n");
566

567 568
    return MS_SUCCESS;
  }
569 570

#else
571 572
  msSetError(MS_MISCERR, "Projection support not enabled", "KmlRenderer::checkProjection" );
  return MS_FAILURE;
573 574 575 576 577
#endif
}

xmlNodePtr KmlRenderer::createPlacemarkNode(xmlNodePtr parentNode, char *styleUrl)
{
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
  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;
597 598 599 600
}

void KmlRenderer::renderLine(imageObj*, shapeObj *p, strokeStyleObj *style)
{
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
  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);
      }
628
    }
629 630 631 632

    CurrentDrawnShapeIndex = p->index;
  }

633 634 635 636
}

void KmlRenderer::renderPolygon(imageObj*, shapeObj *p, colorObj *color)
{
637 638
  if (PlacemarkNode == NULL)
    PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
639

640 641
  if (!PlacemarkNode)
    return;
642

643 644
  memcpy(&PolygonColor, color, sizeof(colorObj));
  SymbologyFlag[Polygon] = 1;
645 646


647
  if (p->index != CurrentDrawnShapeIndex) {
648

649
    xmlNodePtr geomParentNode = getGeomParentNode("Polygon");
650

651 652 653 654 655 656 657
    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);
658

659 660 661
      xmlNodePtr ringNode = xmlNewChild(bdryNode, NULL, BAD_CAST "LinearRing", NULL);
      addAddRenderingSpecifications(ringNode);
      addCoordsNode(ringNode, p->line[i].point, p->line[i].numpoints);
662
    }
663 664 665 666 667

    CurrentDrawnShapeIndex = p->index;

  }

668 669 670 671
}

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

674 675
  xmlNodePtr coordsNode = xmlNewChild(parentNode, NULL, BAD_CAST "coordinates", NULL);
  xmlNodeAddContent(coordsNode, BAD_CAST "\n");
676

677 678 679 680
  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) {
681
#ifdef USE_POINT_Z_M
682
      sprintf(lineBuf, "\t%.8f,%.8f,%.8f\n", pts[i].x, pts[i].y, pts[i].z);
683
#else
684
      msSetError(MS_MISCERR, "Z coordinates support not available  (mapserver not compiled with USE_POINT_Z_M option)", "KmlRenderer::addCoordsNode()");
685
#endif
686 687
    } else
      sprintf(lineBuf, "\t%.8f,%.8f\n", pts[i].x, pts[i].y);
688

689 690 691
    xmlNodeAddContent(coordsNode, BAD_CAST lineBuf);
  }
  xmlNodeAddContent(coordsNode, BAD_CAST "\t");
692 693
}

694
void KmlRenderer::renderGlyphs(imageObj *img, pointObj *labelpnt, char *text, double angle, colorObj *clr, colorObj *olcolor, int olwidth)
695
{
696
  xmlNodePtr node;
697

698 699
  if (PlacemarkNode == NULL)
    PlacemarkNode = createPlacemarkNode(LayerNode, NULL);
700

701 702
  if (!PlacemarkNode)
    return;
703

704
  memcpy(&LabelColor, clr, sizeof(colorObj));
705
  SymbologyFlag[Label] = 1;
706

707 708 709 710
  /*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;
711

712 713 714
    if (strcmp((char *)node->name, "name") == 0) {
      xmlNodeSetContent(node,  BAD_CAST text);
      break;
715
    }
716
  }
717

718 719 720 721
  /*xmlNewChild(PlacemarkNode, NULL, BAD_CAST "name", BAD_CAST text);*/

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

723
  pointObj pt;
724 725
  pt.x = labelpnt->x;
  pt.y = labelpnt->y;
726
  addCoordsNode(geomNode, &pt, 1);
727 728 729 730
}

void KmlRenderer::addAddRenderingSpecifications(xmlNodePtr node)
{
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
  /*
    <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");
749 750 751 752 753 754 755
}


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

int KmlRenderer::createIconImage(char *fileName, symbolObj *symbol, symbolStyleObj *symstyle)
{
756 757 758
  pointObj p;

  imageObj *tmpImg = NULL;
759

760 761 762 763 764 765 766 767 768
  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;
769
#ifdef USE_POINT_Z_M
770
  p.z = 0.0;
771 772
#endif

773 774
  if(msDrawMarkerSymbol(map,tmpImg, &p, symstyle->style, 1) != MS_SUCCESS)
    return MS_FAILURE;
775

776
  return msSaveImage(map, tmpImg, fileName);
777 778 779 780
}

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

784 785
  if (!PlacemarkNode)
    return;
786

787 788
  snprintf(SymbolUrl, sizeof(SymbolUrl), "%s", lookupSymbolUrl(img, symbol, style));
  SymbologyFlag[Symbol] = 1;
789

790 791
  xmlNodePtr geomNode = getGeomParentNode("Point");
  addAddRenderingSpecifications(geomNode);
792

793 794 795 796
  pointObj pt;
  pt.x = x;
  pt.y = y;
  addCoordsNode(geomNode, &pt, 1);
797 798
}

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

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

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

817
void KmlRenderer::renderTruetypeSymbol(imageObj *img, double x, double y, symbolObj *symbol,
818 819
                                       symbolStyleObj *style)
{
820
  renderSymbol(img, x, y, symbol, style);
821 822 823 824
}

xmlNodePtr KmlRenderer::createGroundOverlayNode(xmlNodePtr parentNode, char *imageHref, layerObj *layer)
{
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
  /*
    <?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);
852 853
  if (layer->compositer && layer->compositer->opacity > 0 && layer->compositer->opacity < 100) {
    sprintf(layerHexColor, "%02xffffff", (unsigned int)MS_NINT(layer->compositer->opacity*2.55));
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 884 885 886 887 888
    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;
889 890 891 892
}

void KmlRenderer::startShape(imageObj *, shapeObj *shape)
{
893 894
  if (PlacemarkNode)
    flushPlacemark();
895

896 897 898
  CurrentShapeIndex=-1;
  CurrentDrawnShapeIndex = -1;
  CurrentShapeName=NULL;
899

900 901 902
  /*should be done at endshape but the plugin architecture does not call endshape yet*/
  if(LineStyle) {
    msFree(LineStyle);
903

904 905 906 907
    LineStyle = NULL;
    numLineStyle = 0;
  }

908 909 910 911 912 913
  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;
914
      }
915
    }
916 917 918
  }
  PlacemarkNode = NULL;
  GeomNode = NULL;
919

920
  DescriptionNode = createDescriptionNode(shape);
921

922 923 924 925
  if( mElevationFromAttribute && shape->numvalues > mElevationAttributeIndex &&
      mElevationAttributeIndex >= 0 && shape->values[mElevationAttributeIndex]) {
    mCurrentElevationValue = atof( shape->values[mElevationAttributeIndex] );
  }
926 927


928
  memset(SymbologyFlag, 0, NumSymbologyFlag);
929 930 931 932
}

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

xmlNodePtr KmlRenderer::getGeomParentNode(const char *geomName)
{
941 942 943 944 945 946 947 948 949 950 951 952 953
  /*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;
  }
954 955 956 957
}

char* KmlRenderer::lookupSymbolUrl(imageObj *img, symbolObj *symbol, symbolStyleObj *symstyle)
{
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 985 986 987
  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");
    }
988

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

994 995 996 997
    if (img->imageurl)
      sprintf(iconUrl, "%s%s.%s", img->imageurl, msGetBasename(iconFileName), "png");
    else
      snprintf(iconUrl, sizeof(iconUrl), "%s", iconFileName);
998

999 1000 1001
    hashObj *hash = msInsertHashTable(StyleHashTable, SymbolName, iconUrl);
    symbolUrl = hash->data;
  }
1002

1003
  return symbolUrl;
1004 1005 1006 1007
}

char* KmlRenderer::lookupPlacemarkStyle()
{
1008 1009 1010 1011
  char  lineHexColor[32];
  char  polygonHexColor[32];
  char  labelHexColor[32];
  char        *styleName=NULL;
1012

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
  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>
    */
1026

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

      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);
1038
    }
1039
  }
1040

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
  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>
    */

1054
    if (currentLayer && currentLayer->compositer && currentLayer->compositer->opacity > 0 && currentLayer->compositer->opacity < 100 &&
1055
        PolygonColor.alpha == 255)
1056
      PolygonColor.alpha = MS_NINT(currentLayer->compositer->opacity*2.55);
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
    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>
    */

1076 1077 1078 1079
    if (currentLayer && currentLayer->compositer && currentLayer->compositer->opacity > 0 && currentLayer->compositer->opacity < 100 &&
        LabelColor.alpha == 255)
      LabelColor.alpha = MS_NINT(currentLayer->compositer->opacity*2.55);
    sprintf(labelHexColor,"%02x%02x%02x%02x", LabelColor.alpha, LabelColor.blue, LabelColor.green, LabelColor.red);
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 1121 1122 1123

    // __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);
1124 1125
    }

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    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);
      }
    }
1138

1139 1140
    if (SymbologyFlag[Symbol]) {
      xmlNodePtr iconStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "IconStyle", NULL);
1141

1142 1143
      xmlNodePtr iconNode = xmlNewChild(iconStyleNode, NULL, BAD_CAST "Icon", NULL);
      xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST SymbolUrl);
1144

1145 1146 1147 1148 1149 1150 1151
      /*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);
1152

1153 1154 1155 1156
        xmlNodePtr iconNode = xmlNewChild(iconStyleNode, NULL, BAD_CAST "Icon", NULL);
        xmlNewChild(iconNode, NULL, BAD_CAST "href", BAD_CAST value);
      }
    }
1157

1158 1159 1160
    if (SymbologyFlag[Label]) {
      xmlNodePtr labelStyleNode = xmlNewChild(styleNode, NULL, BAD_CAST "LabelStyle", NULL);
      xmlNewChild(labelStyleNode, NULL, BAD_CAST "color", BAD_CAST labelHexColor);
1161

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

1168 1169
  if (styleName)
    msFree(styleName);
1170

1171
  return styleUrl;
1172 1173 1174 1175
}

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

    if (DescriptionNode)
      xmlAddChild(PlacemarkNode, DescriptionNode);

    if (GeomNode)
      xmlAddChild(PlacemarkNode, GeomNode);
  }
1186 1187 1188 1189 1190
}


xmlNodePtr KmlRenderer::createDescriptionNode(shapeObj *shape)
{
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
  /*
    <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);
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 1263 1264 1265
    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);
1266
        }
1267 1268
      }
    }
1269

1270
    return extendedDataNode;
1271 1272


1273 1274 1275
  }

  return NULL;
1276 1277 1278 1279
}

void KmlRenderer::addLineStyleToList(strokeStyleObj *style)
{
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
  /*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));
  }
1300 1301 1302 1303

}

#endif