Created
July 6, 2023 10:54
-
-
Save mcleary/0ad129d5e0cbe5476da0fda230df690c to your computer and use it in GitHub Desktop.
Function to load textures from disk using stb to OpenGL in Parallel. Not worth using if loading a small number of small textures
This file contains hidden or 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
std::map<std::string, GLint> LoadTextures(const std::vector<std::string>& InTextureFiles) | |
{ | |
struct TextureData | |
{ | |
std::int32_t TextureWidth = 0; | |
std::int32_t TextureHeight = 0; | |
std::uint8_t* Data = nullptr; | |
}; | |
std::mutex PrintMutex; | |
std::vector<std::thread> Threads; | |
std::map<std::string, std::future<TextureData>> TextureFutures; | |
for (const std::string& TextureFile : InTextureFiles) | |
{ | |
std::packaged_task<TextureData()> LoadTextureTask([&TextureFile, &PrintMutex] | |
{ | |
TextureData Data; | |
constexpr std::int32_t NumReqComponents = 3; | |
Data.Data = stbi_load(TextureFile.c_str(), &Data.TextureWidth, &Data.TextureHeight, 0, NumReqComponents); | |
assert(Data.Data); | |
return Data; | |
}); | |
TextureFutures.emplace(TextureFile, LoadTextureTask.get_future()); | |
Threads.emplace_back(std::move(LoadTextureTask)); | |
} | |
std::map<std::string, GLint> LoadedTextures; | |
for (std::pair<const std::string, std::future<TextureData>>& TextureFuturePair : TextureFutures) | |
{ | |
std::string TextureFile = TextureFuturePair.first; | |
TextureData Data = std::move(TextureFuturePair.second).get(); | |
// Gerar o Identifador da Textura | |
GLuint TextureId; | |
glGenTextures(1, &TextureId); | |
// Habilita a textura para ser modificada | |
glBindTexture(GL_TEXTURE_2D, TextureId); | |
// Copia a textura para a memória da GPU | |
const GLint Level = 0; | |
const GLint Border = 0; | |
glTexImage2D(GL_TEXTURE_2D, Level, GL_RGB, Data.TextureWidth, Data.TextureHeight, Border, GL_RGB, GL_UNSIGNED_BYTE, Data.Data); | |
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); | |
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); | |
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); | |
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); | |
glGenerateMipmap(GL_TEXTURE_2D); | |
glBindTexture(GL_TEXTURE_2D, 0); | |
stbi_image_free(Data.Data); | |
LoadedTextures[TextureFile] = TextureId; | |
} | |
for (std::thread& Thread : Threads) | |
{ | |
Thread.join(); | |
} | |
return LoadedTextures; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment