mapraster.c 40.1 KB
Newer Older
1
/******************************************************************************
2
 * $id: mapraster.c 10772 2010-11-29 18:27:02Z aboudreault $
3 4
 *
 * Project:  MapServer
5
 * Purpose:  msDrawRasterLayer(): generic raster layer drawing.
6
 * Author:   Frank Warmerdam, warmerdam@pobox.com
7
 *           Pete Olson (LMIC)
8 9 10
 *           Steve Lime
 *
 ******************************************************************************
11
 * Copyright (c) 1996-2010 Regents of the University of Minnesota.
12 13 14 15 16 17 18 19
 *
 * 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:
 *
20
 * The above copyright notice and this permission notice shall be included in
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
 * 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.
 ****************************************************************************/

#include <assert.h>
#include "mapserver.h"
#include "mapfile.h"
#include "mapresample.h"
#include "mapthread.h"

38

39

40 41
extern int msyylex_destroy(void);
extern int yyparse(parseObj *);
42

43
extern parseResultObj yypresult; /* result of parsing, true/false */
44 45 46 47 48

#ifdef USE_GDAL
#include "gdal.h"
#include "cpl_string.h"
#endif
49
#include "mapraster.h"
50 51 52 53 54

#define MAXCOLORS 256
#define BUFLEN 1024
#define HDRLEN 8

55
#define CVT(x) ((x) >> 8) /* converts to 8-bit color value */
56 57 58 59

#define NUMGRAYS 16

/************************************************************************/
60
/*                         msGetClass_String()                          */
61 62
/************************************************************************/

63
static int msGetClass_String( layerObj *layer, colorObj *color, const char *pixel_value, int firstClassToTry )
64 65

{
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  int i;
  const char *tmpstr1=NULL;
  int numitems;
  char *item_names[4] = { "pixel", "red", "green", "blue" };
  char *item_values[4];
  char red_value[8], green_value[8], blue_value[8];

  /* -------------------------------------------------------------------- */
  /*      No need to do a lookup in the case of one default class.        */
  /* -------------------------------------------------------------------- */
  if((layer->numclasses == 1) && !(layer->class[0]->expression.string)) /* no need to do lookup */
    return(0);

  /* -------------------------------------------------------------------- */
  /*      Setup values list for expressions.                              */
  /* -------------------------------------------------------------------- */
  numitems = 4;
83 84 85 86 87 88 89 90 91 92 93 94
  if( color->red == -1 && color->green == -1 && color->blue == -1 )
  {
    strcpy(red_value, "-1");
    strcpy(green_value, "-1");
    strcpy(blue_value, "-1");
  }
  else
  {
    sprintf( red_value, "%d", color->red );
    sprintf( green_value, "%d", color->green );
    sprintf( blue_value, "%d", color->blue );
  }
95 96 97 98 99 100 101 102 103

  item_values[0] = (char *)pixel_value;
  item_values[1] = red_value;
  item_values[2] = green_value;
  item_values[3] = blue_value;

  /* -------------------------------------------------------------------- */
  /*      Loop over classes till we find a match.                         */
  /* -------------------------------------------------------------------- */
104 105 106 107 108 109 110
  for(i= (firstClassToTry < 0 ) ? 0 : -1; i<layer->numclasses; i++) {

    int idx = i;
    if( i < 0 )
        idx = firstClassToTry;
    else if( i == firstClassToTry )
        continue;
111 112

    /* check for correct classgroup, if set */
113 114
    if ( layer->class[idx]->group && layer->classgroup &&
         strcasecmp(layer->class[idx]->group, layer->classgroup) != 0 )
115 116 117
      continue;

    /* Empty expression - always matches */
118
    if (layer->class[idx]->expression.string == NULL)
119 120
      return(i);

121
    switch(layer->class[idx]->expression.type) {
122 123 124 125 126 127 128 129 130 131

        /* -------------------------------------------------------------------- */
        /*      Simple string match                                             */
        /* -------------------------------------------------------------------- */
      case(MS_STRING):
        /* trim junk white space */
        tmpstr1= pixel_value;
        while( *tmpstr1 == ' ' )
          tmpstr1++;

132
        if(strcmp(layer->class[idx]->expression.string, tmpstr1) == 0) return(idx); /* matched */
133 134 135 136 137 138
        break;

        /* -------------------------------------------------------------------- */
        /*      Regular expression.  Rarely used for raster.                    */
        /* -------------------------------------------------------------------- */
      case(MS_REGEX):
139 140
        if(!layer->class[idx]->expression.compiled) {
          if(ms_regcomp(&(layer->class[idx]->expression.regex), layer->class[idx]->expression.string, MS_REG_EXTENDED|MS_REG_NOSUB) != 0) { /* compile the expression  */
141 142
            msSetError(MS_REGEXERR, "Invalid regular expression.", "msGetClass()");
            return(-1);
143
          }
144
          layer->class[idx]->expression.compiled = MS_TRUE;
145
        }
146

147
        if(ms_regexec(&(layer->class[idx]->expression.regex), pixel_value, 0, NULL, 0) == 0) return(idx); /* got a match */
148 149 150 151 152 153 154 155 156
        break;

        /* -------------------------------------------------------------------- */
        /*      Parsed expression.                                              */
        /* -------------------------------------------------------------------- */
      case(MS_EXPRESSION): {
        int status;
        parseObj p;
        shapeObj dummy_shape;
157
        expressionObj *expression = &(layer->class[idx]->expression);
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177

        dummy_shape.numvalues = numitems;
        dummy_shape.values = item_values;

        if( expression->tokens == NULL )
          msTokenizeExpression( expression, item_names, &numitems );

        p.shape = &dummy_shape;
        p.expr = expression;
        p.expr->curtoken = p.expr->tokens; /* reset */
        p.type = MS_PARSE_TYPE_BOOLEAN;

        status = yyparse(&p);

        if (status != 0) {
          msSetError(MS_PARSEERR, "Failed to parse expression: %s", "msGetClass_FloatRGB", expression->string);
          return -1;
        }

        if( p.result.intval )
178
          return idx;
179 180
        break;
      }
181
    }
182
  }
183

184
  return(-1); /* not found */
185
}
186

187 188 189
/************************************************************************/
/*                             msGetClass()                             */
/************************************************************************/
190

191
int msGetClass(layerObj *layer, colorObj *color, int colormap_index)
192
{
193
  char pixel_value[12];
194

195
  snprintf( pixel_value, sizeof(pixel_value), "%d", colormap_index );
196

197
  return msGetClass_String( layer, color, pixel_value, -1 );
198
}
199

200 201 202 203 204 205 206 207
/************************************************************************/
/*                          msGetClass_FloatRGB()                       */
/*                                                                      */
/*      Returns the class based on classification of a floating         */
/*      pixel value.                                                    */
/************************************************************************/

int msGetClass_FloatRGB(layerObj *layer, float fValue, int red, int green, int blue )
208 209 210 211 212 213 214
{
    return msGetClass_FloatRGB_WithFirstClassToTry(
                layer, fValue, red, green, blue, -1);
}


int msGetClass_FloatRGB_WithFirstClassToTry(layerObj *layer, float fValue, int red, int green, int blue, int firstClassToTry )
215
{
216 217
  char pixel_value[100];
  colorObj color;
218

219 220 221
  color.red = red;
  color.green = green;
  color.blue = blue;
222

223
  snprintf( pixel_value, sizeof(pixel_value), "%18g", fValue );
224

225
  return msGetClass_String( layer, &color, pixel_value, firstClassToTry );
226 227
}

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
#if defined(USE_GDAL)

/************************************************************************/
/*                      msRasterSetupTileLayer()                        */
/*                                                                      */
/*      Setup the tile layer.                                           */
/************************************************************************/

int msDrawRasterSetupTileLayer(mapObj *map, layerObj *layer,
                               rectObj* psearchrect,
                               int is_query,
                               int* ptilelayerindex, /* output */
                               int* ptileitemindex, /* output */
                               int* ptilesrsindex, /* output */
                               layerObj **ptlp  /* output */ )
{
    int i;
    char* requested_fields;
    int status;
    layerObj* tlp = NULL;

    *ptilelayerindex = msGetLayerIndex(layer->map, layer->tileindex);
    if(*ptilelayerindex == -1) { /* the tileindex references a file, not a layer */

      /* so we create a temporary layer */
      tlp = (layerObj *) malloc(sizeof(layerObj));
      MS_CHECK_ALLOC(tlp, sizeof(layerObj), MS_FAILURE);

      initLayer(tlp, map);
      *ptlp = tlp;

      /* set a few parameters for a very basic shapefile-based layer */
      tlp->name = msStrdup("TILE");
      tlp->type = MS_LAYER_TILEINDEX;
      tlp->data = msStrdup(layer->tileindex);

      if( is_query )
      {
        tlp->map = map;  /*needed when scaletokens are applied, to extract current map scale */
        for(i = 0; i < layer->numscaletokens; i++) {
          if(msGrowLayerScaletokens(tlp) == NULL) {
            return MS_FAILURE;
          }
          initScaleToken(&tlp->scaletokens[i]);
          msCopyScaleToken(&layer->scaletokens[i],&tlp->scaletokens[i]);
          tlp->numscaletokens++;
        }
      }

      if (layer->projection.numargs > 0 &&
        EQUAL(layer->projection.args[0], "auto"))
      {
          tlp->projection.numargs = 1;
          tlp->projection.args[0] = msStrdup("auto");
      }

      if (layer->filteritem)
        tlp->filteritem = msStrdup(layer->filteritem);
      if (layer->filter.string) {
        if (layer->filter.type == MS_EXPRESSION) {
          char* pszTmp =
            (char *)msSmallMalloc(sizeof(char)*(strlen(layer->filter.string)+3));
          sprintf(pszTmp,"(%s)",layer->filter.string);
          msLoadExpressionString(&tlp->filter, pszTmp);
          free(pszTmp);
        } else if (layer->filter.type == MS_REGEX ||
                   layer->filter.type == MS_IREGEX) {
          char* pszTmp =
            (char *)msSmallMalloc(sizeof(char)*(strlen(layer->filter.string)+3));
          sprintf(pszTmp,"/%s/",layer->filter.string);
          msLoadExpressionString(&tlp->filter, pszTmp);
          free(pszTmp);
        } else
          msLoadExpressionString(&tlp->filter, layer->filter.string);

        tlp->filter.type = layer->filter.type;
      }

    } else {
      if ( msCheckParentPointer(layer->map,"map")==MS_FAILURE )
        return MS_FAILURE;
      tlp = (GET_LAYER(layer->map, *ptilelayerindex));
      *ptlp = tlp;
    }
    status = msLayerOpen(tlp);
    if(status != MS_SUCCESS) {
      return status;
    }

    /* fetch tileitem and tilesrs fields */
    requested_fields = (char*) msSmallMalloc(sizeof(char)*(strlen(layer->tileitem)+1+
                                    (layer->tilesrs ? strlen(layer->tilesrs) : 0) + 1));
    if( layer->tilesrs != NULL )
        sprintf(requested_fields, "%s,%s", layer->tileitem, layer->tilesrs);
    else
        strcpy(requested_fields, layer->tileitem);
    status = msLayerWhichItems(tlp, MS_FALSE, requested_fields);
    msFree(requested_fields);
    if(status != MS_SUCCESS) {
      return status;
    }

    /* get the tileitem and tilesrs index */
    for(i=0; i<tlp->numitems; i++) {
      if(strcasecmp(tlp->items[i], layer->tileitem) == 0) {
        *ptileitemindex = i;
      }
      if(layer->tilesrs != NULL &&
         strcasecmp(tlp->items[i], layer->tilesrs) == 0) {
        *ptilesrsindex = i;
      }
    }
    if(*ptileitemindex < 0) { /* didn't find it */
      msSetError(MS_MEMERR,
                 "Could not find attribute %s in tileindex.",
                 "msDrawRasterLayerLow()",
                 layer->tileitem);
      return MS_FAILURE;
    }
    if(layer->tilesrs != NULL && *ptilesrsindex < 0) { /* didn't find it */
      msSetError(MS_MEMERR,
                 "Could not find attribute %s in tileindex.",
                 "msDrawRasterLayerLow()",
                 layer->tilesrs);
      return MS_FAILURE;
    }

#ifdef USE_PROJ
    /* if necessary, project the searchrect to source coords */
    if((map->projection.numargs > 0) && (layer->projection.numargs > 0) &&
        !EQUAL(layer->projection.args[0], "auto")) {
      if( msProjectRect(&map->projection, &layer->projection, psearchrect)
          != MS_SUCCESS ) {
        msDebug( "msDrawRasterLayerLow(%s): unable to reproject map request rectangle into layer projection, canceling.\n", layer->name );
        return MS_FAILURE;
      }
    }
    else if((map->projection.numargs > 0) && (tlp->projection.numargs > 0) &&
        !EQUAL(tlp->projection.args[0], "auto")) {
      if( msProjectRect(&map->projection, &tlp->projection, psearchrect)
          != MS_SUCCESS ) {
        msDebug( "msDrawRasterLayerLow(%s): unable to reproject map request rectangle into layer projection, canceling.\n", layer->name );
        return MS_FAILURE;
      }
    }
#endif
    return msLayerWhichShapes(tlp, *psearchrect, MS_FALSE);
}

/************************************************************************/
/*                msDrawRasterCleanupTileLayer()                        */
/*                                                                      */
/*      Cleanup the tile layer.                                         */
/************************************************************************/

void msDrawRasterCleanupTileLayer(layerObj* tlp,
                                  int tilelayerindex)
{
    msLayerClose(tlp);
    if(tilelayerindex == -1) {
      freeLayer(tlp);
      free(tlp);
    }
}

/************************************************************************/
/*                   msDrawRasterIterateTileIndex()                     */
/*                                                                      */
/*      Iterate over the tile layer.                                    */
/************************************************************************/

int msDrawRasterIterateTileIndex(layerObj *layer,
                                 layerObj* tlp,
                                 shapeObj* ptshp, /* input-output */
                                 int tileitemindex,
                                 int tilesrsindex,
                                 char* tilename, /* output */
                                 size_t sizeof_tilename,
                                 char* tilesrsname, /* output */
                                 size_t sizeof_tilesrsname)
{
      int status;

      status = msLayerNextShape(tlp, ptshp);
      if( status == MS_FAILURE || status == MS_DONE ) {
        return status;
      }

      if(layer->data == NULL || strlen(layer->data) == 0 ) { /* assume whole filename is in attribute field */
        strlcpy( tilename, ptshp->values[tileitemindex], sizeof_tilename);
      } else
        snprintf(tilename, sizeof_tilename, "%s/%s", ptshp->values[tileitemindex], layer->data);

      tilesrsname[0] = '\0';

      if( tilesrsindex >= 0 )
      {
        if(ptshp->values[tilesrsindex] != NULL )
          strlcpy( tilesrsname, ptshp->values[tilesrsindex], sizeof_tilesrsname );
      }

      msFreeShape(ptshp); /* done with the shape */

      return status;
}

/************************************************************************/
/*                   msDrawRasterBuildRasterPath()                      */
/*                                                                      */
/*      Build the path of the raster to open.                           */
/************************************************************************/

int msDrawRasterBuildRasterPath(mapObj *map, layerObj *layer,
                                const char* filename,
                                char szPath[MS_MAXPATHLEN] /* output */)
{
    /*
    ** If using a tileindex then build the path relative to that file if SHAPEPATH is not set.
    */
    if(layer->tileindex && !map->shapepath) {
      char tiAbsFilePath[MS_MAXPATHLEN];
      char *tiAbsDirPath = NULL;

      msTryBuildPath(tiAbsFilePath, map->mappath, layer->tileindex); /* absolute path to tileindex file */
      tiAbsDirPath = msGetPath(tiAbsFilePath); /* tileindex file's directory */
      msBuildPath(szPath, tiAbsDirPath, filename);
      free(tiAbsDirPath);
    } else {
      msTryBuildPath3(szPath, map->mappath, map->shapepath, filename);
    }

    return MS_SUCCESS;
}

/************************************************************************/
/*                   msDrawRasterGetCPLErrorMsg()                       */
/*                                                                      */
/*      Return the CPL error message, and filter out sensitive info.    */
/************************************************************************/

const char* msDrawRasterGetCPLErrorMsg(const char* decrypted_path,
                                       const char* szPath)
{
      const char *cpl_error_msg = CPLGetLastErrorMsg();

      /* we wish to avoid reporting decrypted paths */
      if( cpl_error_msg != NULL
          && strstr(cpl_error_msg,decrypted_path) != NULL
          && strcmp(decrypted_path,szPath) != 0 )
        cpl_error_msg = NULL;

      /* we wish to avoid reporting the stock GDALOpen error messages */
      if( cpl_error_msg != NULL
          && (strstr(cpl_error_msg,"not recognised as a supported") != NULL
              || strstr(cpl_error_msg,"does not exist") != NULL) )
        cpl_error_msg = NULL;

      if( cpl_error_msg == NULL )
        cpl_error_msg = "";

      return cpl_error_msg;
}

/************************************************************************/
/*                   msDrawRasterLoadProjection()                       */
/*                                                                      */
/*      Handle TILESRS or PROJECTION AUTO for each tile.                */
/************************************************************************/

int msDrawRasterLoadProjection(layerObj *layer,
                               GDALDatasetH hDS,
                               const char* filename,
                               int tilesrsindex,
                               const char* tilesrsname)
{
    /*
    ** Generate the projection information if using TILESRS.
    */
    if( tilesrsindex >= 0 )
    {
        const char *pszWKT;
        if( tilesrsname[0] != '\0' )
            pszWKT = tilesrsname;
        else
            pszWKT = GDALGetProjectionRef( hDS );
        if( pszWKT != NULL && strlen(pszWKT) > 0 ) {
          if( msOGCWKT2ProjectionObj(pszWKT, &(layer->projection),
                                    layer->debug ) != MS_SUCCESS ) {
          char  szLongMsg[MESSAGELENGTH*2];
          errorObj *ms_error = msGetErrorObj();

          snprintf( szLongMsg, sizeof(szLongMsg),
                    "%s\n"
                    "PROJECTION '%s' cannot be used for this "
                    "GDAL raster (`%s').",
                    ms_error->message, pszWKT, filename);
          szLongMsg[MESSAGELENGTH-1] = '\0';

          msSetError(MS_OGRERR, "%s","msDrawRasterLayer()",
                     szLongMsg);

          return MS_FAILURE;
        }
      }
    }
    /*
    ** Generate the projection information if using AUTO.
    */
    else if (layer->projection.numargs > 0 &&
        EQUAL(layer->projection.args[0], "auto")) {
      const char *pszWKT;

      pszWKT = GDALGetProjectionRef( hDS );

      if( pszWKT != NULL && strlen(pszWKT) > 0 ) {
        if( msOGCWKT2ProjectionObj(pszWKT, &(layer->projection),
                                   layer->debug ) != MS_SUCCESS ) {
          char  szLongMsg[MESSAGELENGTH*2];
          errorObj *ms_error = msGetErrorObj();

          snprintf( szLongMsg, sizeof(szLongMsg),
                    "%s\n"
                    "PROJECTION AUTO cannot be used for this "
                    "GDAL raster (`%s').",
                    ms_error->message, filename);
          szLongMsg[MESSAGELENGTH-1] = '\0';

          msSetError(MS_OGRERR, "%s","msDrawRasterLayer()",
                     szLongMsg);

          return MS_FAILURE;
        }
      }
    }

    return MS_SUCCESS;
}
#endif // defined(USE_GDAL)

567 568 569 570 571 572 573 574 575
#if defined(USE_GDAL)

typedef enum
{
    CDRT_OK,
    CDRT_RETURN_MS_FAILURE,
    CDRT_CONTINUE_NEXT_TILE
} CheckDatasetReturnType;

576
/************************************************************************/
577
/*              msDrawRasterLayerLowCheckDataset()                      */
578 579
/************************************************************************/

580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 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
static
CheckDatasetReturnType msDrawRasterLayerLowCheckDataset(mapObj *map,
                                     layerObj *layer,
                                     GDALDatasetH hDS,
                                     const char* decrypted_path,
                                     const char* szPath)
{
    /*
    ** If GDAL doesn't recognise it, and it wasn't successfully opened
    ** Generate an error.
    */
    if(hDS == NULL) {
      int ignore_missing = msMapIgnoreMissingData(map);
      const char *cpl_error_msg = msDrawRasterGetCPLErrorMsg(decrypted_path, szPath);

      if(ignore_missing == MS_MISSING_DATA_FAIL) {
        msSetError(MS_IOERR, "Corrupt, empty or missing file '%s' for layer '%s'. %s", "msDrawRasterLayerLow()", szPath, layer->name, cpl_error_msg );
        return(CDRT_RETURN_MS_FAILURE);
      } else if( ignore_missing == MS_MISSING_DATA_LOG ) {
        if( layer->debug || layer->map->debug ) {
          msDebug( "Corrupt, empty or missing file '%s' for layer '%s' ... ignoring this missing data.  %s\n", szPath, layer->name, cpl_error_msg );
        }
        return(CDRT_CONTINUE_NEXT_TILE);
      } else if( ignore_missing == MS_MISSING_DATA_IGNORE ) {
        return(CDRT_CONTINUE_NEXT_TILE);
      } else {
        /* never get here */
        msSetError(MS_IOERR, "msIgnoreMissingData returned unexpected value.", "msDrawRasterLayerLow()");
        return(CDRT_RETURN_MS_FAILURE);
      }
    }

    return CDRT_OK;
}
#endif

/************************************************************************/
/*              msDrawRasterLayerLowOpenDataset()                       */
/************************************************************************/

void* msDrawRasterLayerLowOpenDataset(mapObj *map, layerObj *layer,
                                      const char* filename,
                                      char szPath[MS_MAXPATHLEN],
                                      char** p_decrypted_path)
624
{
625
#if !defined(USE_GDAL)
626
  msSetError(MS_MISCERR,
627 628 629
             "Attempt to render a RASTER (or WMS) layer but without\n"
             "GDAL support enabled.  Raster rendering requires GDAL.",
             "msDrawRasterLayerLow()" );
630 631
  *p_decrypted_path = NULL;
  return NULL;
632
#else /* defined(USE_GDAL) */
633
  const char* pszPath;
634

635
  msGDALInitialize();
636

637 638
  if(layer->debug == MS_TRUE)
    msDebug( "msDrawRasterLayerLow(%s): Filename is: %s\n", layer->name, filename);
639

640 641 642 643 644 645 646 647 648 649 650
  if( strncmp(filename, "<VRTDataset", strlen("<VRTDataset")) == 0 )
  {
    pszPath = filename;
  }
  else
  {
    msDrawRasterBuildRasterPath(map, layer, filename, szPath);
    pszPath = szPath;
  }
  if(layer->debug == MS_TRUE)
    msDebug("msDrawRasterLayerLow(%s): Path is: %s\n", layer->name, pszPath);
651

652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    /*
    ** Note: because we do decryption after the above path expansion
    ** which depends on actually finding a file, it essentially means that
    ** fancy path manipulation is essentially disabled when using encrypted
    ** components. But that is mostly ok, since stuff like sde,postgres and
    ** oracle georaster do not use real paths.
    */
  *p_decrypted_path = msDecryptStringTokens( map, pszPath );
  if( *p_decrypted_path == NULL )
    return NULL;

  msAcquireLock( TLOCK_GDAL );
  return GDALOpenShared( *p_decrypted_path, GA_ReadOnly );
#endif
}

/************************************************************************/
/*                msDrawRasterLayerLowCloseDataset()                    */
/************************************************************************/

void msDrawRasterLayerLowCloseDataset(layerObj *layer, void* hDS)
{
#if !defined(USE_GDAL)
    (void)hDS;
#else
    if( hDS )
    {
      const char *close_connection;
      close_connection = msLayerGetProcessingKey( layer,
                       "CLOSE_CONNECTION" );

      if( close_connection == NULL && layer->tileindex == NULL )
        close_connection = "DEFER";

      if( close_connection != NULL
          && strcasecmp(close_connection,"DEFER") == 0 ) {
        GDALDereferenceDataset( (GDALDatasetH)hDS );
      } else {
        GDALClose( (GDALDatasetH)hDS );
      }
      msReleaseLock( TLOCK_GDAL );
    }
#endif
}
696 697


698 699 700 701 702 703 704 705 706 707 708
/************************************************************************/
/*                msDrawRasterLayerLowCheckIfMustDraw()                 */
/*                                                                      */
/*      Return 1 if the layer should be drawn.                          */
/************************************************************************/

int msDrawRasterLayerLowCheckIfMustDraw(mapObj *map, layerObj *layer)
{
#if !defined(USE_GDAL)
  return 0;
#else
709
  if(!layer->data && !layer->tileindex && !(layer->connectiontype==MS_KERNELDENSITY)) {
710 711
    if(layer->debug == MS_TRUE)
      msDebug( "msDrawRasterLayerLow(%s): layer data and tileindex NULL ... doing nothing.", layer->name );
712 713 714 715
    return(0);
  }

  if((layer->status != MS_ON) && (layer->status != MS_DEFAULT)) {
716 717
    if(layer->debug == MS_TRUE)
      msDebug( "msDrawRasterLayerLow(%s): not status ON or DEFAULT, doing nothing.", layer->name );
718 719 720 721 722
    return(0);
  }

  if(map->scaledenom > 0) {
    if((layer->maxscaledenom > 0) && (map->scaledenom > layer->maxscaledenom)) {
723 724 725
      if(layer->debug == MS_TRUE)
        msDebug( "msDrawRasterLayerLow(%s): skipping, map scale %.2g > MAXSCALEDENOM=%g\n",
                 layer->name, map->scaledenom, layer->maxscaledenom );
726 727 728
      return(0);
    }
    if((layer->minscaledenom > 0) && (map->scaledenom <= layer->minscaledenom)) {
729 730 731
      if(layer->debug == MS_TRUE)
        msDebug( "msDrawRasterLayerLow(%s): skipping, map scale %.2g < MINSCALEDENOM=%g\n",
                 layer->name, map->scaledenom, layer->minscaledenom );
732 733 734 735 736 737
      return(0);
    }
  }

  if(layer->maxscaledenom <= 0 && layer->minscaledenom <= 0) {
    if((layer->maxgeowidth > 0) && ((map->extent.maxx - map->extent.minx) > layer->maxgeowidth)) {
738 739 740
      if(layer->debug == MS_TRUE)
        msDebug( "msDrawRasterLayerLow(%s): skipping, map width %.2g > MAXSCALEDENOM=%g\n", layer->name,
                 (map->extent.maxx - map->extent.minx), layer->maxgeowidth );
741 742 743
      return(0);
    }
    if((layer->mingeowidth > 0) && ((map->extent.maxx - map->extent.minx) < layer->mingeowidth)) {
744 745 746
      if(layer->debug == MS_TRUE)
        msDebug( "msDrawRasterLayerLow(%s): skipping, map width %.2g < MINSCALEDENOM=%g\n", layer->name,
                 (map->extent.maxx - map->extent.minx), layer->mingeowidth );
747 748 749 750
      return(0);
    }
  }

751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
  return 1;
#endif
}

/************************************************************************/
/*                        msDrawRasterLayerLow()                        */
/*                                                                      */
/*      Check for various file types and act appropriately.  Handle     */
/*      tile indexing.                                                  */
/************************************************************************/

int msDrawRasterLayerLow(mapObj *map, layerObj *layer, imageObj *image,
                         rasterBufferObj *rb )
{
    return msDrawRasterLayerLowWithDataset(map, layer, image, rb, NULL);
}

int msDrawRasterLayerLowWithDataset(mapObj *map, layerObj *layer, imageObj *image,
                                    rasterBufferObj *rb, void* hDatasetIn )
{
  /* -------------------------------------------------------------------- */
  /*      As of MapServer 6.0 GDAL is required for rendering raster       */
  /*      imagery.                                                        */
  /* -------------------------------------------------------------------- */
#if !defined(USE_GDAL)
  msSetError(MS_MISCERR,
             "Attempt to render a RASTER (or WMS) layer but without\n"
             "GDAL support enabled.  Raster rendering requires GDAL.",
             "msDrawRasterLayerLow()" );
  return MS_FAILURE;

#else /* defined(USE_GDAL) */
  int status, done;
  char *filename=NULL, tilename[MS_MAXPATHLEN], tilesrsname[1024];

  layerObj *tlp=NULL; /* pointer to the tile layer either real or temporary */
  int tileitemindex=-1, tilelayerindex=-1, tilesrsindex=-1;
  shapeObj tshp;

  char szPath[MS_MAXPATHLEN] = { 0 };
  char *decrypted_path = NULL;
  int final_status = MS_SUCCESS;

  rectObj searchrect;
  GDALDatasetH  hDS;
  double  adfGeoTransform[6];
  void *kernel_density_cleanup_ptr = NULL;

  if(layer->debug > 0 || map->debug > 1)
    msDebug( "msDrawRasterLayerLow(%s): entering.\n", layer->name );

  if( hDatasetIn == NULL &&
      !msDrawRasterLayerLowCheckIfMustDraw(map, layer) ) {
    return MS_SUCCESS;
  }

  msGDALInitialize();
808

809 810
  if(layer->tileindex) { /* we have an index file */
    msInitShape(&tshp);
811
    searchrect = map->extent;
812

813 814 815 816 817 818 819
    status = msDrawRasterSetupTileLayer(map, layer,
                           &searchrect,
                           MS_FALSE,
                           &tilelayerindex,
                           &tileitemindex,
                           &tilesrsindex,
                           &tlp);
820 821 822 823
    if(status != MS_SUCCESS) {
      if (status != MS_DONE)
        final_status = status;
      goto cleanup;
824 825 826 827
    }
  }

  done = MS_FALSE;
828
  while(done != MS_TRUE) {
829

830
    if(layer->tileindex) {
831 832 833 834
      status = msDrawRasterIterateTileIndex(layer, tlp, &tshp,
                                            tileitemindex, tilesrsindex,
                                            tilename, sizeof(tilename),
                                            tilesrsname, sizeof(tilesrsname));
835 836 837
      if( status == MS_FAILURE) {
        final_status = MS_FAILURE;
        break;
838 839 840 841 842 843 844 845
      }

      if(status == MS_DONE) break; /* no more tiles/images */
      filename = tilename;
    } else {
      filename = layer->data;
      done = MS_TRUE; /* only one image so we're done after this */
    }
846 847
    
    if(layer->connectiontype == MS_KERNELDENSITY) {
848
      msAcquireLock( TLOCK_GDAL );
849 850
      status = msComputeKernelDensityDataset(map, image, layer, &hDS, &kernel_density_cleanup_ptr);
      if(status != MS_SUCCESS) {
851
        msReleaseLock( TLOCK_GDAL );
852 853 854 855 856 857 858 859 860
        final_status = status;
        goto cleanup;
      }
      done = MS_TRUE;
      if(msProjectionsDiffer(&map->projection,&layer->projection)) {
        char *mapProjStr = msGetProjectionString(&(map->projection));

        /* Set the projection to the map file projection */
        if (msLoadProjectionString(&(layer->projection), mapProjStr) != 0) {
861 862
          GDALClose( hDS );
          msReleaseLock( TLOCK_GDAL );
863 864 865 866 867
          msSetError(MS_CGIERR, "Unable to set projection on interpolation layer.", "msDrawRasterLayerLow()");
          return(MS_FAILURE);
        }
        free(mapProjStr);
      }
868 869 870 871 872 873 874 875 876 877 878
    } else {
      if(strlen(filename) == 0) continue;
      if( hDatasetIn )
      {
        hDS = (GDALDatasetH)hDatasetIn;
      }
      else
      {
        hDS = (GDALDatasetH)msDrawRasterLayerLowOpenDataset(
                                map, layer, filename, szPath, &decrypted_path);
      }
879
    }
880

881 882 883 884
    if( hDatasetIn == NULL )
    {
        CheckDatasetReturnType eRet =
            msDrawRasterLayerLowCheckDataset(map,layer,hDS,decrypted_path,szPath);
885

886 887
        msFree( decrypted_path );
        decrypted_path = NULL;
888

889 890 891 892 893 894 895 896 897
        if( eRet == CDRT_CONTINUE_NEXT_TILE )
        {
            msReleaseLock( TLOCK_GDAL );
            continue;
        }
        if( eRet == CDRT_RETURN_MS_FAILURE )
        {
            msReleaseLock( TLOCK_GDAL );
            return MS_FAILURE;
898
        }
899
    }
900

901 902
    if( msDrawRasterLoadProjection(layer, hDS, filename, tilesrsindex, tilesrsname) != MS_SUCCESS )
    {
903 904 905 906 907
        if( hDatasetIn == NULL )
        {
          GDALClose( hDS );
          msReleaseLock( TLOCK_GDAL );
        }
908 909
        final_status = MS_FAILURE;
        break;
910
    }
911

912
    msGetGDALGeoTransform( hDS, map, layer, adfGeoTransform );
913

914
    /*
915 916 917 918 919 920 921 922
    ** We want to resample if the source image is rotated, if
    ** the projections differ or if resampling has been explicitly
    ** requested, or if the image has north-down instead of north-up.
    */
#ifdef USE_PROJ
    if( ((adfGeoTransform[2] != 0.0 || adfGeoTransform[4] != 0.0
          || adfGeoTransform[5] > 0.0 || adfGeoTransform[1] < 0.0 )
         && layer->transform )
923 924 925 926 927
        || msProjectionsDiffer( &(map->projection),
                                &(layer->projection) )
        || CSLFetchNameValue( layer->processing, "RESAMPLE" ) != NULL ) {
      status = msResampleGDALToMap( map, layer, image, rb, hDS );
    } else
928 929
#endif
    {
930 931 932 933 934 935 936 937 938 939
      if( adfGeoTransform[2] != 0.0 || adfGeoTransform[4] != 0.0 ) {
        if( layer->debug || map->debug )
          msDebug(
            "Layer %s has rotational coefficients but we\n"
            "are unable to use them, projections support\n"
            "needs to be built in.",
            layer->name );

      }
      status = msDrawRasterLayerGDAL(map, layer, image, rb, hDS );
940 941
    }

942
    if( status == -1 ) {
943 944 945 946 947
      if( hDatasetIn == NULL )
      {
        GDALClose( hDS );
        msReleaseLock( TLOCK_GDAL );
      }
948 949
      final_status = MS_FAILURE;
      break;
950 951
    }

952
    /*
953 954
    ** Should we keep this file open for future use?
    ** default to keeping open for single data files, and
955 956
    ** to closing for tile indexes
    */
957 958 959 960 961 962 963 964 965 966 967
    if(layer->connectiontype == MS_KERNELDENSITY) {
      /*
      ** Fix issue #5330
      ** The in-memory kernel density heatmap gdal dataset handle (hDS) gets re-used
      ** but the associated rasterband cache doesn't get flushed, which causes old data
      ** to be rendered instead of the newly generated imagery. To fix, simply close the
      ** the handle and prevent further re-use.
      ** Note that instead of this workaround, we could explicitely set 
      ** CLOSE_CONNECTION=ALWAYS on the kerneldensity layer.
      */
      GDALClose( hDS );
968
      msReleaseLock( TLOCK_GDAL );
969 970
    }
    else {
971 972
      if( hDatasetIn == NULL)
        msDrawRasterLayerLowCloseDataset(layer, hDS);
973
    }
974

975 976 977 978
  } /* next tile */

cleanup:
  if(layer->tileindex) { /* tiling clean-up */
979
    msDrawRasterCleanupTileLayer(tlp, tilelayerindex);
980
  }
981 982 983
  if(layer->connectiontype == MS_KERNELDENSITY && kernel_density_cleanup_ptr) {
    msCleanupKernelDensityDataset(map, image, layer, kernel_density_cleanup_ptr);
  }
984 985

  return final_status;
986 987

#endif /* defined(USE_GDAL) */
988 989 990 991 992 993
}

/************************************************************************/
/*                         msDrawReferenceMap()                         */
/************************************************************************/

994 995
imageObj *msDrawReferenceMap(mapObj *map)
{
996 997 998
  double cellsize;
  int x1,y1,x2,y2;
  char szPath[MS_MAXPATHLEN];
999
  int status = MS_SUCCESS;
1000 1001

  imageObj   *image = NULL;
1002
  styleObj style;
1003 1004


1005 1006 1007
  rendererVTableObj *renderer = MS_MAP_RENDERER(map);
  rasterBufferObj *refImage = (rasterBufferObj*)calloc(1,sizeof(rasterBufferObj));
  MS_CHECK_ALLOC(refImage, sizeof(rasterBufferObj), NULL);
1008

1009
  if(MS_SUCCESS != renderer->loadImageFromFile(msBuildPath(szPath, map->mappath, map->reference.image),refImage)) {
1010 1011
    msSetError(MS_MISCERR,"error loading reference image %s","msDrawREferenceMap()",szPath);
    return NULL;
1012 1013 1014
  }

  image = msImageCreate(refImage->width, refImage->height, map->outputformat,
1015
                        map->web.imagepath, map->web.imageurl, map->resolution, map->defresolution, &(map->reference.color));
1016
  if(!image) return NULL;
1017

1018
  status = renderer->mergeRasterBuffer(image,refImage,1.0,0,0,0,0,refImage->width, refImage->height);
1019 1020
  msFreeRasterBuffer(refImage);
  free(refImage);
1021 1022
  if(UNLIKELY(status == MS_FAILURE))
    return NULL;
1023

1024
  /* make sure the extent given in mapfile fits the image */
1025
  cellsize = msAdjustExtent(&(map->reference.extent),
1026 1027 1028 1029
                            image->width, image->height);

  /* convert map extent to reference image coordinates */
  x1 = MS_MAP2IMAGE_X(map->extent.minx,  map->reference.extent.minx, cellsize);
1030
  x2 = MS_MAP2IMAGE_X(map->extent.maxx,  map->reference.extent.minx, cellsize);
1031 1032
  y1 = MS_MAP2IMAGE_Y(map->extent.maxy,  map->reference.extent.maxy, cellsize);
  y2 = MS_MAP2IMAGE_Y(map->extent.miny,  map->reference.extent.maxy, cellsize);
1033

1034 1035 1036
  initStyle(&style);
  style.color = map->reference.color;
  style.outlinecolor = map->reference.outlinecolor;
1037

1038 1039
  /* if extent are smaller than minbox size */
  /* draw that extent on the reference image */
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
  if( (abs(x2 - x1) > map->reference.minboxsize) ||
      (abs(y2 - y1) > map->reference.minboxsize) ) {
    shapeObj rect;
    lineObj line;
    pointObj points[5];
    msInitShape(&rect);

    line.point = points;
    line.numpoints = 5;
    rect.line = &line;
    rect.numlines = 1;
    rect.type = MS_SHAPE_POLYGON;

    line.point[0].x = x1;
    line.point[0].y = y1;
    line.point[1].x = x1;
    line.point[1].y = y2;
    line.point[2].x = x2;
    line.point[2].y = y2;
    line.point[3].x = x2;
    line.point[3].y = y1;
    line.point[4].x = line.point[0].x;
    line.point[4].y = line.point[0].y;

    line.numpoints = 5;

    if( map->reference.maxboxsize == 0 ||
        ((abs(x2 - x1) < map->reference.maxboxsize) &&
         (abs(y2 - y1) < map->reference.maxboxsize)) ) {
1069 1070 1071 1072
      if(UNLIKELY(MS_FAILURE == msDrawShadeSymbol(map, image, &rect, &style, 1.0))) {
        msFreeImage(image);
        return NULL;
      }
1073 1074 1075 1076 1077 1078 1079 1080 1081
    }

  } else { /* else draw the marker symbol */
    if( map->reference.maxboxsize == 0 ||
        ((abs(x2 - x1) < map->reference.maxboxsize) &&
         (abs(y2 - y1) < map->reference.maxboxsize)) ) {
      style.size = map->reference.markersize;

      /* if the marker symbol is specify draw this symbol else draw a cross */
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
      if(map->reference.marker || map->reference.markername) {
        pointObj point;
        point.x = (double)(x1 + x2)/2;
        point.y = (double)(y1 + y2)/2;

        if(map->reference.marker) {
          style.symbol = map->reference.marker;
        } else {
          style.symbol = msGetSymbolIndex(&map->symbolset,  map->reference.markername, MS_TRUE);
        }
1092

1093 1094 1095 1096
        if(UNLIKELY(MS_FAILURE == msDrawMarkerSymbol(map, image, &point, &style, 1.0))) {
          msFreeImage(image);
          return NULL;
        }
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 1124 1125 1126 1127 1128 1129 1130 1131
      } else {
        int x21, y21;
        shapeObj cross;
        lineObj lines[4];
        pointObj point[8];
        int i;
        /* determine the center point */
        x21 = MS_NINT((x1 + x2)/2);
        y21 = MS_NINT((y1 + y2)/2);

        msInitShape(&cross);
        cross.numlines = 4;
        cross.line = lines;
        for(i=0; i<4; i++) {
          cross.line[i].numpoints = 2;
          cross.line[i].point = &(point[2*i]);
        }
        /* draw a cross */
        cross.line[0].point[0].x = x21-8;
        cross.line[0].point[0].y = y21;
        cross.line[0].point[1].x = x21-3;
        cross.line[0].point[1].y = y21;
        cross.line[1].point[0].x = x21;
        cross.line[1].point[0].y = y21-8;
        cross.line[1].point[1].x = x21;
        cross.line[1].point[1].y = y21-3;
        cross.line[2].point[0].x = x21;
        cross.line[2].point[0].y = y21+3;
        cross.line[2].point[1].x = x21;
        cross.line[2].point[1].y = y21+8;
        cross.line[3].point[0].x = x21+3;
        cross.line[3].point[0].y = y21;
        cross.line[3].point[1].x = x21+8;
        cross.line[3].point[1].y = y21;

1132 1133 1134 1135
        if(UNLIKELY(MS_FAILURE == msDrawLineSymbol(map,image,&cross,&style,1.0))) {
          msFreeImage(image);
          return NULL;
        }
1136
      }
1137
    }
1138 1139 1140 1141
  }

  return(image);
}