Last active
June 19, 2017 14:46
-
-
Save victorholt/497642bdc2eb5a0a372e73244805fac3 to your computer and use it in GitHub Desktop.
LodeNode Image Loading for Terrain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Storage for our 16bit pixel. | |
union uimage_data | |
{ | |
uint16_t s; | |
uint8_t b[2]; | |
}; | |
Image* LoadHeightmap(const String& heightmapFilePath) | |
{ | |
std::vector<unsigned char> pngData; | |
std::vector<unsigned char> image; | |
unsigned width = 0, height = 0; | |
lodepng::State state; | |
unsigned error = lodepng::load_file(pngData, heightmapFilePath.CString()); | |
if (!error) { | |
error = lodepng::decode(image, width, height, pngData, LCT_GREY, 16); | |
} | |
if (error) { | |
URHO3D_LOGERROR(String("Unable to load raw PNG file @ ") + heightmapFilePath); | |
return nullptr; | |
} | |
// Map our data. | |
Image* heightmap = new Image(context_); | |
unsigned components = 2; | |
unsigned dataLen = width * height * components; | |
unsigned char* pixelData = new unsigned char[dataLen]; | |
heightmap->SetSize(width, height, components); | |
// Check if our image is 16 bit or 8 bit | |
if (state.info_png.color.bitdepth == 16) { | |
unsigned imgDataIndex = 0; | |
unsigned index = 0; | |
unsigned sDataLen = static_cast<unsigned>(image.size() / 2); | |
uimage_data* sData = new uimage_data[sDataLen]; | |
// Copy over the pixel data into our storage. | |
for (index = 0; index < sDataLen; index += 2, imgDataIndex += 1) { | |
sData[imgDataIndex].b[0] = image[index + 1]; | |
sData[imgDataIndex].b[1] = image[index]; | |
} | |
// Update our pixel data for Urho3D. | |
imgDataIndex = 0; | |
for (index = 0; index < dataLen; index += components, imgDataIndex += 2) { | |
pixelData[index] = sData[imgDataIndex].b[0]; | |
pixelData[index + 1] = sData[imgDataIndex].b[1]; | |
} | |
delete [] sData; | |
} else { | |
std::copy(image.begin(), image.end(), pixelData); | |
} | |
heightmap->SetData(pixelData); | |
return heightmap; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment