From 07cdfc19b7ab39db73d3ac097556b23f2e4a90ce Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Thu, 28 Jan 2021 20:27:54 +0000 Subject: Basic support for loading a heightmap from an image --- game/terrain.cpp | 32 ++++++++++++++++++++++++++++++++ game/terrain.h | 2 ++ 2 files changed, 34 insertions(+) (limited to 'game') diff --git a/game/terrain.cpp b/game/terrain.cpp index fc98f08..3e5c187 100644 --- a/game/terrain.cpp +++ b/game/terrain.cpp @@ -9,6 +9,8 @@ #include #include #include +#include +#include Terrain::Terrain() : m_vertexArrayObject {}, m_vertexArrayBuffers {}, texture {Texture::cachedTexture.get("res/terrain.png")} @@ -62,6 +64,36 @@ Terrain::Terrain() : finish(size, size, resolution); } +Terrain::Terrain(const std::string & fileName) : + m_vertexArrayObject {}, m_vertexArrayBuffers {}, texture {Texture::cachedTexture.get("res/terrain.png")} +{ + constexpr auto resolution {100}; + + int width, height, numComponents; + unsigned char * data = stbi_load((fileName).c_str(), &width, &height, &numComponents, STBI_grey); + + if (!data) { + throw std::runtime_error {"Unable to load heightmap: " + fileName}; + } + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + vertices.reserve((width * height) + 4); + + for (auto z = 0; z < height; z += 1) { + for (auto x = 0; x < width; x += 1) { + vertices.emplace_back( + glm::vec3 {resolution * (x - (width / 2)), ((float)data[x + (z * width)] * 0.1F) - 1.5F, + resolution * (z - (height / 2))}, + glm::vec2 {(x % 2) / 2.01, (z % 2) / 2.01}, glm::vec3 {0, 1, 0}); + } + } + stbi_image_free(data); + + finish(width, height, resolution); +} + void Terrain::finish(unsigned int width, unsigned int height, unsigned int resolution) { diff --git a/game/terrain.h b/game/terrain.h index 0edf4bd..64c4f96 100644 --- a/game/terrain.h +++ b/game/terrain.h @@ -8,6 +8,7 @@ #include #include #include +#include #include class Shader; @@ -16,6 +17,7 @@ class Texture; class Terrain : public WorldObject, public Renderable { public: Terrain(); + explicit Terrain(const std::string &); ~Terrain() override; NO_COPY(Terrain); NO_MOVE(Terrain); -- cgit v1.2.3