Display a pgm image using openGl - c++

So i am writing a program using openGl on C++.I want to load an image and then display it in a NxN grid form.
I loaded the image and stored its data in an array and then proceeded to use the following method to achieve my goal:
void fillGrid(){
ifstream myfile("paper.pgm");
ofstream otherfile;
otherfile.open("test.txt");
string line;
string buffer;
fstream afile;
if (myfile.is_open())
{
int counter=0;
while (getline(myfile, line))
{
if(counter>2){
buffer=buffer+line;
}
counter++;
}
pixels=new float[1600];
int i=0;
string delimiters = " ,";
size_t current;
size_t next = -1;
do
{
current = next + 1;
next = buffer.find_first_of( delimiters, current );
if(i<=1600){
pixels[i]=myAtof (buffer.substr(current));
paper[i]=pixels[i];
}
i++;
}
while (next != string::npos);
for(int j=0;j<=1600;j++){
otherfile<<paper[j]<<" "<< j<<endl;
}
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glBindTexture(GL_TEXTURE_2D, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 140, 140, 0, GL_RGB, GL_FLOAT, paper);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_REPEAT);
}
}
This function opens the file containing the image data, loads the image in the pixels array at first and then at the paper array that i use in glTexImage2D.MyAtof() is a function i built to convert a string into a float. The data is properly passed from the file to the array, i've tested it.
After ther fillGrid function the following function is called t do the repaint:
void drawGrid2(void)
{
for(int i=-240;i<240;i+=40){
for(int j=-300;j<=300;j+=40){
drawSquare2(i,j);
}
}
}
And also:
void drawSquare2(int x,int y)
{
glBindTexture(GL_TEXTURE_2D, 1);
glBegin(GL_QUADS); //Start drawing quad
glVertex2f(x,y); //first coordinate x y
glVertex2f(x+40,y); //second coordinate
glVertex2f(x+40,y+40); //third coordinate
glVertex2f(x,y+40); //last coordinate
glEnd(); //Stop drawing quads
glFlush ();
}
Main:
int main (int argc, char** argv)
{
glutInit (&argc, argv); // Initialize GLUT.
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // Set display mode.
glutInitWindowPosition (0, 0); // Set top-left display-window position.
glutInitWindowSize (600, 500); // Set display-window width and height.
glutCreateWindow ("Main"); // Create display window.
init (); // Execute initialization procedure.
glutDisplayFunc (display); // Send graphics to display window.
glutKeyboardFunc(processEscKey);
glutMainLoop (); // Display everything and wait.
return 0;
}
Other functions:
void init (void)
{
// glClearColor (1.0, 1.0, 1.0, 0.0); // Set display-window color to white.
glClearColor (0.0, 0.0, 0.0, 1.0);//black
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glMatrixMode (GL_PROJECTION); // Set projection parameters.
gluOrtho2D(-300,300,-300,300);//0,width,0,height
}
void processEscKey(unsigned char key, int x, int y)
{
if(key==27){
exit(0);
}
else if(key==98){
fillGrid();
drawGrid2();
}
}
Is this the correct way to create a texture and display an image with openGl?
The file compiles but the result isn't what i want.
I wanted an 15x15 grid of squares, with each square containing the image.
Before the repaint the result was this.
After the repaint the result is this.
I used different functions for the first repaint and the the second one.
Since the first one is working i didnt post it.

OpenGL's default texture minification filter is GL_NEAREST_MIPMAP_LINEAR. Your texture is not mipmap complete, so texturing will not work in this mode. You should set glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); (or GL_LINEAR).
You also seem to try to set the texture maginification filter here:
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_REPEAT);
butt GL_REPEAT is not a valid filter mode at all.

Related

Load jpg image as texture - freeimage, opengl

I tried to load jpg image with FreeImage Library. I used this code, but the result was only white window. I think to use this image like background and after that to load object file.
It`s the code, that i used:
#include <windows.h>
#include <GL/glut.h>
#include <iostream>
#include <FreeImage.h>
FIBITMAP *loadImage(const char *filename)
{
FIBITMAP *dib1 = NULL;
FREE_IMAGE_FORMAT fif = FreeImage_GetFIFFromFilename(filename);
dib1 = FreeImage_Load(fif, filename, JPEG_DEFAULT);
if (!dib1)
{
std::cerr << "Erreur ouverture d\'image" << std::endl;
exit (0);
}
std::cerr << "Success" << std::endl;
return dib1;
}
GLuint loadTexture (FIBITMAP * dib1)
{
GLuint tex_id = 0;
int x, y;
int height, width;
RGBQUAD rgbquad;
FREE_IMAGE_TYPE type;
BITMAPINFOHEADER *header;
type = FreeImage_GetImageType(dib1);
height = FreeImage_GetHeight(dib1);
width = FreeImage_GetWidth(dib1);
header = FreeImage_GetInfoHeader(dib1);
int scanLineWidh = ((3*width)%4 == 0) ? 3*width : ((3*width)/4)*4+4;
unsigned char * texels= (GLubyte*)calloc(height*scanLineWidh, sizeof(GLubyte));
for (x=0 ; x<width ; x++)
for (y=0 ; y<height; y++)
{
FreeImage_GetPixelColor(dib1,x,y,&rgbquad);
texels[(y*scanLineWidh+3*x)]=((GLubyte*)&rgbquad)[2];
texels[(y*scanLineWidh+3*x)+1]=((GLubyte*)&rgbquad)[1];
texels[(y*scanLineWidh+3*x)+2]=((GLubyte*)&rgbquad)[0];
}
glGenTextures (1, &tex_id);
glBindTexture (GL_TEXTURE_2D, tex_id);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB,
width, height, 0, GL_RGB,
GL_UNSIGNED_BYTE, texels);
free(texels);
return tex_id;
}
void display(void)
{
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glutSwapBuffers(); //swap the buffers
}
int main(int argc, char **argv) {
FIBITMAP *dib1 = loadImage("planina.jpg");
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutInitWindowSize(800,450);
glutInitWindowPosition(20,20);
glutCreateWindow("Loader");
//glutReshapeFunc(reshape);
//glutDisplayFunc(display);
loadTexture(dib1);
FreeImage_Unload(dib1);
glutMainLoop();
return 0;
}
What I am doing wrong?
This is your display function:
void display(void)
{
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glutSwapBuffers(); //swap the buffers
}
And what's immediately apparent is, that the only thing it does is
setting a clear color
clear the window
load an identity matrix
displays the result
What's lacking is any kind of actually drawing something. You have to draw some triangles or quads with the texture applied for the texture to actually show up somehow.

Opengl C++: texture code textures all models with the same texture

I created a class to hold my models information. I have to models rendering correctly and the textures properly wrapping, but for some reason if I have multiple models it will texture all of my models in just 1 texture as you can see in this image: http://imgur.com/d0glIwF
Any ideas why this might be happening?
This is my code:
struct BitMapFile
{
int sizeX;
int sizeY;
unsigned char *data;
};
// Routine to read a bitmap file.
// Works only for uncompressed bmp files of 24-bit color.
BitMapFile *getBMPData(string filename)
{
BitMapFile *bmp = new BitMapFile;
unsigned int size, offset, headerSize;
// Read input file name.
ifstream infile(filename.c_str(), ios::binary);
// Get the starting point of the image data.
infile.seekg(10);
infile.read((char *) &offset, 4);
// Get the header size of the bitmap.
infile.read((char *) &headerSize,4);
// Get width and height values in the bitmap header.
infile.seekg(18);
infile.read( (char *) &bmp->sizeX, 4);
infile.read( (char *) &bmp->sizeY, 4);
// Allocate buffer for the image.
size = bmp->sizeX * bmp->sizeY * 24;
bmp->data = new unsigned char[size];
// Read bitmap data.
infile.seekg(offset);
infile.read((char *) bmp->data , size);
// Reverse color from bgr to rgb.
int temp;
for (int i = 0; i < size; i += 3)
{
temp = bmp->data[i];
bmp->data[i] = bmp->data[i+2];
bmp->data[i+2] = temp;
}
return bmp;
}
class Model
{
public:
Model(string modelFilename, string textureFilename);
float getCenterX() { return m_CenterX; }
float getCenterY() { return m_CenterY; }
float getCenterZ() { return m_CenterZ; }
void SetCenterX(float x) { m_CenterX = x; }
void SetCenterY(float y) { m_CenterY = y; }
void SetCenterZ(float z) { m_CenterZ = z; }
void LoadTexture(string fileName);
//load model function
void Draw();
private:
float m_CenterX, m_CenterY, m_CenterZ, m_Width, m_Height, m_Depth;
string m_ModelFilename;
int m_Texture;
string m_TextureName;
};
Model::Model(string modelFilename, string textureFilename)
{
m_ModelFilename = modelFilename;
m_TextureName = textureFilename;
//load model function//
LoadTexture(m_TextureName);
}
void Model::LoadTexture(string TextureName)
{
// Local storage for bmp image data.
BitMapFile *image[1];
string filename = TextureName;
filename.append(".bmp");
// Load the texture.
image[0] = getBMPData(filename);
// Bind grass image to texture index[i].
glBindTexture(GL_TEXTURE_2D, m_Texture); //makes room for our texture
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);
glTexImage2D(GL_TEXTURE_2D, //always GL_TEXTURE_2D
0, //0 for now
GL_RGB, //format opengl uses to read textures
image[0]->sizeX, //width
image[0]->sizeY, //height
0, //the border of the image
GL_RGB, //GL_RGB because pixels are stored in RGB format
GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE because pixels are stored as unsigned numbers
image[0]->data); //actual pixel data
}
void Model::Draw()
{
glPushMatrix();
glTranslatef(m_CenterX, m_CenterY, m_CenterZ);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_Texture);
glBegin(GL_TRIANGLES);
//my code for drawing the model to the screen. it isn't the problem so i removed it
glEnd();
glDisable(GL_TEXTURE_2D);
glPopMatrix();
}
Model model;
Model model1;
// Drawing routine.
void drawScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
model.SetCenterX(0);
model.SetCenterY(0);
model.SetCenterZ(12);
model.Draw();
model1.SetCenterX(12);
model1.SetCenterY(10);
model1.SetCenterZ(0);
model1.Draw();
glutSwapBuffers();
}
void setup(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
//model = Model("monkey.obj", "launch");
model = Model("cube.obj", "launch");
model1 = Model("cube.obj", "grass");
// Specify how texture values combine with current surface color values.
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
}
Thank you in advance.
The problem is that you're not creating a texture id. You can do that using the glGenTextures function. In your case I would put it at the beginning of the LoadTexture method - just ask it for 1 texture id and save what it gives you back into m_Texture.
Remember that, like everything you create using glGen*, it should also be deleted when you're done with it using glDelete* (glDeleteTextures in this case).
Also, consider moving to more modern OpenGL with shaders and vertex arrays. This is a very broad topic, unfortunately. There are lots of tutorials and books available, I learned from OpenGL Superbible, though I hear that some people don't like it very much...

OpenGl texturing ........ ppm background

i am using a ppm loader to set image as a background , but there is a problem
in colors here is the code and the image that i am use .
http://imgur.com/w732d6j
http://imgur.com/mJr26Ik
here is the code .....
texture.h
#ifndef TEXTURE_H
#define TEXTURE_H
struct Image
{
unsigned char* pixels;
int width;
int height;
int numChannels;
};
class Texture
{
public:
Texture ();
void Prepare (int texN);
void ReadPPMImage (char *fn);
GLuint texName;
Image image;
};
#endif
texture.cpp
#include <fstream>
#include <glut.h>
#pragma warning (disable : 4996)
#include "Texture.h"
Texture::Texture ()
{
}
void Texture::Prepare (int texN)
{
texName = texN;
glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
glBindTexture (GL_TEXTURE_2D, texName);
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);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width,
image.height, 0, GL_RGB, GL_UNSIGNED_BYTE,
image.pixels);
}
void Texture::ReadPPMImage (char* fn)
{
int tmpint;
char str[100];
FILE* inFile = fopen (fn,"rb");
if (inFile == NULL)
{
printf ("Can't open input file %s. Exiting.\n",fn);
exit (1);
}
fscanf (inFile,"P%d\n", &tmpint);
if (tmpint != 6)
{
printf ("Input file is not ppm. Exiting.\n");
exit (1);
}
// skip comments embedded in header
fgets (str,100,inFile);
while (str[0]=='#')
fgets(str,100,inFile);
// read image dimensions
sscanf (str,"%d %d",&image.width, &image.height);
fgets (str,100,inFile);
sscanf (str,"%d",&tmpint);
if (tmpint != 255)
printf("Warning: maxvalue is not 255 in ppm file\n");
image.numChannels = 3;
image.pixels = (unsigned char*) malloc (image.numChannels * image.width * image.height * sizeof (unsigned char));
if (image.pixels == NULL)
{
printf ("Can't allocate image of size %dx%d. Exiting\n", image.width, image.height);
exit (1);
}
else
printf("Reading image %s of size %dx%d\n", fn, image.width, image.height);
fread (image.pixels, sizeof (unsigned char), image.numChannels * image.width * image.height, inFile);
fclose (inFile);
}
Main.cpp
#include <glut.h>
#include "Texture.h"
#pragma warning (disable : 4996)
const float fMinX = -5.0, fMinY = -5.0, fNearZ = 1.0,
fMaxX = 5.0 , fMaxY = 5.0 , fFarZ = 10.0;
Texture ImageOne ;
void Init ()
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glEnable (GL_DEPTH_TEST);
glGenTextures (1, &ImageOne.texName);
ImageOne.ReadPPMImage("wood_1.ppm");
ImageOne.Prepare(1) ;
}
void Reshape (int width, int height)
{
glViewport (0, 0, width, height);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho (fMinX, fMaxX, fMinY, fMaxY, fNearZ, fFarZ);
glMatrixMode (GL_MODELVIEW);
glLoadIdentity ();
}
void Display ()
{
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable (GL_TEXTURE_2D);
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
glBindTexture (GL_TEXTURE_2D, ImageOne.texName);
glBegin(GL_QUADS);
glTexCoord2f(0,1);
glVertex3f(-5.5,5,-6);
glTexCoord2f(0,0);
glVertex3f(-5.5,-5,-6);
glTexCoord2f(1,0);
glVertex3f(5,-5,-6);
glTexCoord2f(1,1);
glVertex3f(5,5,-6);
glEnd();
glDisable(GL_TEXTURE_2D);
glutSwapBuffers ();
glFlush ();
}
void main (int argc, char **argv)
{
// init GLUT and create window
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowPosition(100,100);
glutInitWindowSize(500,500);
glutCreateWindow ("OpenGL - Rotating Cubes");
Init ();
// register callbacks
glutDisplayFunc (Display);
glutReshapeFunc (Reshape);
glutIdleFunc (Display); // used in animation
// enter GLUT event processing cycle
glutMainLoop();
}
Why are you using
glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
?
It does not make sense for your use case (and perfectly explays the "inversion" of the color values). You probably want GL_REPLACE or GL_MODULATE.

Incorrect output texture on quad

I'm trying to display the text in my application using freetype. At first I thought that this built-in function (which would be quite natural for the library intended to draw the text). But there was only a function to display the symbol.Then I decided to take the characters one by one into a texture. But here again I was disappointed: all guides one texture uses a single image (probably glTexSubImage2D can help me?).Now I put a symbol on the texture and texture to opengl element.Here's my code (it's quite messy, but now I'm just trying to understand how it works):
//init:
if (FT_Init_FreeType(&ft)) {
fprintf(stderr, "Could not init freetype library\n");
return 0;
}
if (FT_New_Face(ft, fontfilename, 0, &face)) {
fprintf(stderr, "Could not open font %s\n", fontfilename);
return 0;
}
FT_Set_Pixel_Sizes(face, 0, 48); FT_GlyphSlot g = face->glyph;
and from display():
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1.0 ,1.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();//load identity matrix
std::string s = "QWERTYOG0l ";
for(int i = 0; i < s.size(); i++){
FT_Load_Char( face, s[i], FT_LOAD_RENDER );
FT_GlyphSlot g = face->glyph;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
gluBuild2DMipmaps( GL_TEXTURE_2D,
GL_RED,
g->bitmap.width,
g->bitmap.rows,
GL_RED,
GL_UNSIGNED_BYTE,
g->bitmap.buffer );
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);glVertex3f(0.1f*i-0.1,0.07f,0.0f); //top left
glTexCoord2f(0.0f, 1.0f);glVertex3f(0.1f*i,0.07f,0.0f); //top right
glTexCoord2f(1.0f, 1.0f);glVertex3f(0.1f*i,-0.07f,0.0f); // bottom right
glTexCoord2f(1.0f, 0.0f);glVertex3f(0.1f*i-0.1,-0.07f,0.0f); //bottom left
glEnd();
}
As you can see the "O" and "T" is correct (if I change bottom left and top right corners of texture it will be absolutely correct). But other symbols seems like shifted (for example "E" is shifted at left from top to bottom).
The full code:
#include <math.h>
#include <iostream>
#include <GL/glew.h>
#include <GL/glut.h>
#include <ft2build.h>
#include FT_FREETYPE_H
FT_Library ft;
FT_Face face;
const char *fontfilename = "LucidaTypewriterBold.ttf";
GLuint texture[10];
GLint uniform_mytexture;
int setup() {
if (FT_Init_FreeType(&ft)) {
fprintf(stderr, "Could not init freetype library\n");
return 0;
}
if (FT_New_Face(ft, fontfilename, 0, &face)) {
fprintf(stderr, "Could not open font %s\n", fontfilename);
return 0;
}
FT_Set_Pixel_Sizes(face, 0, 48);
FT_Load_Char( face, 'O', FT_LOAD_RENDER );
FT_GlyphSlot g = face->glyph;
glGenTextures(1, &texture[0]); // Create The Texture
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, g->bitmap.width, g->bitmap.rows, GL_RED, GL_UNSIGNED_BYTE, g->bitmap.buffer);
return 1;
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1.0 ,1.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();//load identity matrix
std::string s = "QWERTYOG0l ";
for(int i = 0; i < s.size(); i++){
FT_Load_Char( face, s[i], FT_LOAD_RENDER );
FT_GlyphSlot g = face->glyph;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
gluBuild2DMipmaps( GL_TEXTURE_2D,
GL_RED,
g->bitmap.width,
g->bitmap.rows,
GL_RED,
GL_UNSIGNED_BYTE,
g->bitmap.buffer );
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);glVertex3f(0.1f*i-0.1,0.07f,0.0f); //top left
glTexCoord2f(0.0f, 1.0f);glVertex3f(0.1f*i,0.07f,0.0f); //top right
glTexCoord2f(1.0f, 1.0f);glVertex3f(0.1f*i,-0.07f,0.0f); // bottom right
glTexCoord2f(1.0f, 0.0f);glVertex3f(0.1f*i-0.1,-0.07f,0.0f); //bottom left
glEnd();
}
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, texture[0]); // Select Our Texture
// glUniform1i(uniform_mytexture, /*GL_TEXTURE*/0);
glutPostRedisplay();
glutSwapBuffers();
}
void TimerFunction(int value)
{
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowSize(800,600);
glutCreateWindow("Hello World");
//glutTimerFunc(30, TimerFunction, 1);
glewInit();
glEnable (GL_TEXTURE_2D);
setup();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
I have been looking into this for a bit, and while this answer is possibly incomplete, maybe it can help you figure it out.
Preliminary Note
Before I get to what I have found, I need to point out a problem with your texture coordinates. You have this:
glTexCoord2f(0.0f, 0.0f);glVertex3f(0.1f*i-0.1,0.07f,0.0f); //top left
glTexCoord2f(0.0f, 1.0f);glVertex3f(0.1f*i,0.07f,0.0f); //top right
glTexCoord2f(1.0f, 1.0f);glVertex3f(0.1f*i,-0.07f,0.0f); // bottom right
glTexCoord2f(1.0f, 0.0f);glVertex3f(0.1f*i-0.1,-0.07f,0.0f); //bottom left
when it should look like this:
glTexCoord2f(0.0f, 0.0f);glVertex3f(0.1f*i-0.1,0.07f,0.0f); //top left
glTexCoord2f(1.0f, 0.0f);glVertex3f(0.1f*i,0.07f,0.0f); //top right
glTexCoord2f(1.0f, 1.0f);glVertex3f(0.1f*i,-0.07f,0.0f); // bottom right
glTexCoord2f(0.0f, 1.0f);glVertex3f(0.1f*i-0.1,-0.07f,0.0f); //bottom left
note how the top left corresponds to 0, 0 in texture coordinates, and 1, 1 corresponds to the bottom right. This is because (kind of guessing here) freetype puts treats the top left as its origin.
The Stuff That May Help
Freetype will not generate a bitmap whose dimensions are necessarily power-of-two, which is often required for mipmapping (see: https://gamedev.stackexchange.com/a/7929 ).
So if you want to test this (note: do not actually use this in your code; this is only for illustration) you can replace your gluBuild2DMipmaps call in display with the following (be sure to #include <cstring>:
int pitch = g->bitmap.pitch;
if (pitch < 0) {
pitch = -pitch;
}
unsigned char data[4096] = {0};
for (int row = 0; row < g->bitmap.rows; ++row) {
std::memcpy(data + 64 * row, g->bitmap.buffer + pitch * row, pitch);
}
gluBuild2DMipmaps(
GL_TEXTURE_2D,
GL_RGBA,
64,
64,
GL_RED,
GL_UNSIGNED_BYTE,
data
);
What it does is copy the bitmap buffer to the upper left corner of a different 64x64-byte buffer, and then builds the mipmaps from that. This is the result:
Further Notes
My illustration code is bad because it copies the bitmap data for each glyph every redraw, and it does not take into account the actual size of the bitmap buffer, or if pitch is greater than 64. You also probably do not want to be (re)generating your mipmaps every redraw, either, but if you are just trying to learn how to get words into OpenGL do not worry about it :)
Edit: I had to use a different font than you because I do not have yours.
As tecu said, the correct solution is using textures with power of two size.
Also before that answer i found another solution:
glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); before gluBuild2DMipmaps. But here you get more problems like gray border around texture.
For those who are asking similar goals I want to share my experience:
Make black on a transparent background:
GLfloat swizzleMask[] = { 0,0,0, GL_RED};
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask);
UPD there is a more simple and obvious solution withput using an OpenGL extension.
gluBuild2DMipmaps( GL_TEXTURE_2D,
GL_ALPHA,
g->bitmap.width,
g->bitmap.rows,
GL_RGBA,
GL_UNSIGNED_BYTE,
g->bitmap.buffer )
Connect all the letters in a single texture
I think that this is better for perfomance, but not sure that I change the right way.
if(text[i] == ' ') left += 20; else
for (int row = 0; row < g->bitmap.rows; ++row) {
std::memcpy(data + left + 64*(strSize*(row + 64 - g->bitmap_top))
, g->bitmap.buffer + pitch * row, pitch);
}
left += g->advance.x >> 6;
It will better if you calculate width and height (and round to power of two) before connecting in data array.
If you want kerning you should write its own slower implementation of memcpy, where you will add (not fully change) the value and check exceeding of UCHAR_MAX.
My final result:

OpenGL renders texture all white

I'm attempting to render a .png image as a texture. However, all that is being rendered is a white square.
I give my texture a unique int ID called texID, read the pixeldata into a buffer 'image' (declared in the .h file). I load my pixelbuffer, do all of my OpenGL stuff and bind that pixelbuffer to a texture for OpenGL. I then draw it all using glDrawElements.
Also I initialize the texture with a size of 32x32 when its contructor is called, therefore i doubt it is related to a power of two size issue.
Can anybody see any mistakes in my OpenGL GL_TEXTURE_2D setup that might give me a block white square.
#include "Texture.h"
Texture::Texture(int width, int height, string filename)
{
const char* fnPtr = filename.c_str(); //our image loader accepts a ptr to a char, not a string
printf(fnPtr);
w = width; //give our texture a width and height, the reason that we need to pass in the width and height values manually
h = height;//UPDATE, these MUST be P.O.T.
unsigned error = lodepng::decode(image,w,h,fnPtr);//lodepng's decode function will load the pixel data into image vector
//display any errors with the texture
if(error)
{
cout << "\ndecoder error " << error << ": " << lodepng_error_text(error) <<endl;
}
for(int i = 0; i<image.size(); i++)
{
printf("%i,", image.at(i));
}
printf("\nImage size is %i", image.size());
//image now contains our pixeldata. All ready for OpenGL to do its thing
//let's get this texture up in the video memory
texGLInit();
}
void Texture::texGLInit()
{
//WHERE YOU LEFT OFF: glGenTextures isn't assigning an ID to textures. it stays at zero the whole time
//i believe this is why it's been rendering white
glGenTextures(1, &textures);
printf("\ntexture = %u", textures);
glBindTexture(GL_TEXTURE_2D, textures);//evrything we're about to do is about this texture
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
//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);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
//glDisable(GL_COLOR_MATERIAL);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8,w,h,0, GL_RGBA, GL_UNSIGNED_BYTE, &image);
//we COULD free the image vectors memory right about now.
}
void Texture::draw(point centerPoint, point dimensions)
{
glEnable(GL_TEXTURE_2D);
printf("\nDrawing block at (%f, %f)",centerPoint.x, centerPoint.y);
glBindTexture(GL_TEXTURE_2D, textures);//bind the texture
//create a quick vertex array for the primitive we're going to bind the texture to
printf("TexID = %u",textures);
GLfloat vArray[8] =
{
centerPoint.x-(dimensions.x/2), centerPoint.y-(dimensions.y/2),//bottom left i0
centerPoint.x-(dimensions.x/2), centerPoint.y+(dimensions.y/2),//top left i1
centerPoint.x+(dimensions.x/2), centerPoint.y+(dimensions.y/2),//top right i2
centerPoint.x+(dimensions.x/2), centerPoint.y-(dimensions.y/2)//bottom right i3
};
//create a quick texture array (we COULD create this on the heap rather than creating/destoying every cycle)
GLfloat tArray[8] =
{
0.0f,0.0f, //0
0.0f,1.0f, //1
1.0f,1.0f, //2
1.0f,0.0f //3
};
//and finally.. the index array...remember, we draw in triangles....(and we'll go CW)
GLubyte iArray[6] =
{
0,1,2,
0,2,3
};
//Activate arrays
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
//Give openGL a pointer to our vArray and tArray
glVertexPointer(2, GL_FLOAT, 0, &vArray[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &tArray[0]);
//Draw it all
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_BYTE, &iArray[0]);
//glDrawArrays(GL_TRIANGLES,0,6);
//Disable the vertex arrays
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D);
//done!
/*glBegin(GL_QUADS);
glTexCoord2f(0.0f,0.0f);
glVertex2f(centerPoint.x-(dimensions.x/2), centerPoint.y-(dimensions.y/2));
glTexCoord2f(0.0f,1.0f);
glVertex2f(centerPoint.x-(dimensions.x/2), centerPoint.y+(dimensions.y/2));
glTexCoord2f(1.0f,1.0f);
glVertex2f(centerPoint.x+(dimensions.x/2), centerPoint.y+(dimensions.y/2));
glTexCoord2f(1.0f,0.0f);
glVertex2f(centerPoint.x+(dimensions.x/2), centerPoint.y-(dimensions.y/2));
glEnd();*/
}
Texture::Texture(void)
{
}
Texture::~Texture(void)
{
}
I'll also include the main class' init, where I do a bit more OGL setup before this.
void init(void)
{
printf("\n......Hello Guy. \n....\nInitilising");
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,XSize,0,YSize);
glEnable(GL_TEXTURE_2D);
myBlock = new Block(0,0,offset);
glClearColor(0,0.4,0.7,1);
glLineWidth(2); // Width of the drawing line
glMatrixMode(GL_MODELVIEW);
glDisable(GL_DEPTH_TEST);
printf("\nInitialisation Complete");
}
Update: adding in the main function where I first setup my OpenGL window.
int main(int argc, char** argv)
{
glutInit(&argc, argv); // GLUT Initialization
glutInitDisplayMode(GLUT_RGBA|GLUT_DOUBLE); // Initializing the Display mode
glutInitWindowSize(800,600); // Define the window size
glutCreateWindow("Gem Miners"); // Create the window, with caption.
printf("\n========== McLeanTech Systems =========\nBecoming Sentient\n...\n...\n....\nKILL\nHUMAN\nRACE \n");
init(); // All OpenGL initialization
//-- Callback functions ---------------------
glutDisplayFunc(display);
glutKeyboardFunc(mykey);
glutSpecialFunc(processSpecialKeys);
glutSpecialUpFunc(processSpecialUpKeys);
//glutMouseFunc(mymouse);
glutMainLoop(); // Loop waiting for event
}
Here's the usual checklist for whenever textures come out white:
OpenGL context created and being bound to current thread when attemting to load texture?
Allocated texture ID using glGenTextures?
Are the parameters format and internal format to glTex[Sub]Image… valid OpenGL tokens allowed as input for this function?
Is mipmapping being used?
YES: Supply all mipmap layers – optimally set glTexParameteri GL_TEXTURE_BASE_LEVEL and GL_TEXTURE_MAX_LEVEL, as well as GL_TEXTURE_MIN_LOD and GL_TEXTURE_MAX_LOG.
NO: Turn off mipmap filtering by setting glTexParameteri GL_TEXTURE_MIN_FILTER to GL_NEAREST or GL_LINEAR.