Skip to content

Instantly share code, notes, and snippets.

@archydragon
Created January 22, 2021 13:04
Show Gist options
  • Save archydragon/121fafb9221be5765cc243ae4b21f698 to your computer and use it in GitHub Desktop.
Save archydragon/121fafb9221be5765cc243ae4b21f698 to your computer and use it in GitHub Desktop.
unsigned int loadCubemap(const char* textureFile) {
stbi_set_flip_vertically_on_load(false);
const unsigned int horizontalChunks = 4;
const unsigned int verticalChunks = 3;
// positions for the layout:
// T
// L F R B
// D
const unsigned int positions[] = {
1, 2, // right
1, 0, // left
0, 1, // top
2, 1, // down
1, 1, // front
1, 3 // back
};
unsigned int textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
// load original file
int tWidth, tHeight, nrChannels;
unsigned char* data = stbi_load(textureFile, &tWidth, &tHeight, &nrChannels, 0);
if (data == NULL) {
std::cout << "Failed to load skybox texture." << std::endl;
stbi_image_free(data);
return 0;
}
const unsigned int chunkWidth = tWidth / horizontalChunks;
const unsigned int chunkHeight = tHeight / verticalChunks;
// cut fragments
for (int i = 0; i < 6; i++) {
const int len = chunkWidth * chunkHeight * nrChannels;
unsigned char* chunkData;
chunkData = (unsigned char*)malloc(len * sizeof(char));
for (unsigned int line = 0; line < chunkHeight; line++) {
int readOffset = (tWidth * positions[i * 2] * chunkHeight) + (tWidth * line) +
(chunkWidth * positions[i * 2 + 1]);
int writeOffset = line * chunkWidth;
// multiply nrChannels in the very end to reduce copy-pasting a bit
std::copy_n(data + (readOffset * nrChannels), chunkWidth * nrChannels,
chunkData + (writeOffset * nrChannels));
}
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, chunkWidth, chunkHeight, 0,
GL_RGB, GL_UNSIGNED_BYTE, chunkData);
free(chunkData);
}
// unload original image data
stbi_image_free(data);
// set texture cube global parameters
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return textureID;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment