contour-creator/src/HeightMap.cpp

46 lines
1.4 KiB
C++
Raw Normal View History

#include <iostream>
2024-04-09 11:03:29 +00:00
#include <stdexcept>
2024-04-06 11:18:28 +00:00
#include <gdal/gdal.h>
#include "gdal/gdal_priv.h"
2024-04-09 11:03:29 +00:00
#include <gdal/gdal_frmts.h>
2024-04-06 11:18:28 +00:00
#include "contour_creator.hh"
2024-04-06 11:18:28 +00:00
HeightMap::HeightMap(const char* filepath)
{
2024-04-09 11:03:29 +00:00
// Open the file with gdal:
2024-04-06 11:18:28 +00:00
const GDALAccess eAccess = GA_ReadOnly;
GDALDatasetUniquePtr file;
2024-04-09 11:03:29 +00:00
GDALRegister_GTiff();
2024-04-06 11:18:28 +00:00
file = GDALDatasetUniquePtr(GDALDataset::FromHandle(GDALOpen( filepath, eAccess )));
if( !file )
{
2024-04-09 11:03:29 +00:00
throw std::runtime_error("Could not open tif file!");
2024-04-06 11:18:28 +00:00
}
// The heigthmap only has one band
auto band = file->GetBands()[0];
2024-04-09 11:03:29 +00:00
2024-04-06 11:18:28 +00:00
// write the attrributes
2024-04-08 15:34:03 +00:00
this->width = band->GetXSize();
this->height = band->GetYSize();
this->min = band->GetMinimum();
this->max = band-> GetMaximum();
this->reference_system = *(file->GetSpatialRef());
2024-04-06 11:18:28 +00:00
2024-04-08 15:34:03 +00:00
this->data = (float *) CPLMalloc(sizeof(float)*width*height);
2024-04-09 11:03:29 +00:00
CPLErr error = band->RasterIO( GF_Read, 0, 0, width, height,
2024-04-08 15:34:03 +00:00
this->data, width, height, GDT_Float32,
2024-04-06 11:18:28 +00:00
0, 0 );
2024-04-09 11:03:29 +00:00
if (error) { throw std::runtime_error("Could not read tif file!"); }
2024-04-06 11:18:28 +00:00
band->FlushCache();
}
float HeightMap::get_pixel(int x, int y)
{
// all the pixels are in an array of floats from left to right, top to bottom
2024-04-08 15:34:03 +00:00
int offset = ((this->width * y) + x);
2024-04-17 08:43:46 +00:00
//std::cout << " offset: " << offset << " " << x << ","<< y;
2024-04-06 11:18:28 +00:00
return *(this->data + offset);
}