Tuesday, October 19, 2021

Importing BMP images to use for texturing in glut and iostream

 In this post, we will be continuing from the previous post on how to make textures in glut, here. This is going to be a custom BMP import library, so you can very easily edit it to your liking. First, we also need to include iostream in the project.


#include <iostream>


Then, inside the texture function from the last post, we will need to change the parameters.


int texture(char *filename, int size)


The size integer is the width and height of the square image, but you can also replace it with two ints for the width and height, just remember to change all the size variables in the code though.

Next, we want to assign a few variables.


unsigned char * data;

unsigned char R, G, B;

FILE * file;


And then import and read the file.


file = fopen(filename, "rb");

if (file == NULL)return 0;

data = (unsigned char *)malloc(size * size * 3);

fseek(file, 128, 0);

fread(data, size * size * 3, 1, file);

fclose(file);


After, we want to convert the RGB values into usable stuff.

int index;

for (int i = 0; i < size * size; ++i)

{

index = i * 3;

B = data[index]; G = data[index + 1]; R = data[index + 2];

data[index] = R; data[index + 1] = G; data[index + 2] = B;

}


And finally, replace the last parameters and gl related stuff with this:

glGenTextures(1, &activeTexture);

glBindTexture(GL_TEXTURE_2D, activeTexture);

gluBuild2DMipmaps(GL_TEXTURE_2D, 3, size, size, GL_RGB, GL_UNSIGNED_BYTE, data);


glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);


free(data);

return 0;


It will be used the same way as the texturing in the last tutorial, except with different parameters like this:


glEnable(GL_TEXTURE_2D);

texture((char *)"cobbled.bmp", 64);

rectangle dirt1 = { 0, 0, 1, 1, 1.0, 0.0, 0.0 };

renderRectEntity(dirt1, false);

glDisable(GL_TEXTURE_2D);


cobbled.bmp is a 64x64 texture.

No comments:

Post a Comment

Importing BMP images to use for texturing in glut and iostream

 In this post, we will be continuing from the previous post on how to make textures in glut,  here . This is going to be a custom BMP import...