davidlao
davidlao

Reputation: 81

Texture is uncentered

So, I'm trying to do a very basic program in OpenGL. Everything went fine, had issues with texturing but now it's all solved.

But now, I have a little issue. The texture shows, but it isn't "centered". I tried changing the vertex positions, but nope, it doesn't work.

Here's an image showing what's happening:

Here's an image showing what's happening

Here's some code that might help:

My includes:

#include"GL/glew.h"
#include"GL/glut.h"
#include"GLFW/glfw3.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

#include <stdio.h>
#include "SOIL/SOIL.h"

Main code (i hid some code lines):

int image_width, image_height;
unsigned char* image = SOIL_load_image("face.png", &image_width, &image_height, NULL, 
SOIL_LOAD_RGBA);

GLuint texture0;

glBindTexture(GL_TEXTURE_2D, texture0);
glGenTextures(1, &texture0);
glActiveTexture(GL_TEXTURE0);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

if (image)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, 
GL_UNSIGNED_BYTE, image);
}
else
{
cout << "ERROR::TEXTURE_LOADING_fAILED" << "\n";
}

//Draw first 2 vertices
glEnable(GL_TEXTURE_2D);

glBegin(GL_QUADS);
glColor3ub(255, 255, 255); //Start vert. color

glTexCoord2f(-.5f, .5f); glVertex2f(-.5, .5); //A
glTexCoord2f(.5f, .5f); glVertex2f(.5, .5); //B
glTexCoord2f(.5f, -.5f); glVertex2f(.5, -.5); //C
glTexCoord2f(-.5f, -.5f); glVertex2f(-.5, -.5); //D

glEnd();

SOIL_free_image_data(image);

glFlush();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glutPostRedisplay();

What I want to do is center the texture to its own center. It's already on (0,0), but I can't manage to "re-center" the texture. Can anyone help me? I'd appreciate it, I'm very VERY new to OpenGL stuff.

Upvotes: 1

Views: 67

Answers (1)

Rabbid76
Rabbid76

Reputation: 210998

The texture coordinates need to be in range [0.0, 1.0]:

glTexCoord2f(0.0f, 1.0f); glVertex2f(-.5, .5); //A
glTexCoord2f(1.0f, 1.0f); glVertex2f(.5, .5); //B
glTexCoord2f(1.0f, 0.0f); glVertex2f(.5, -.5); //C
glTexCoord2f(0.0f, 0.0f); glVertex2f(-.5, -.5); //D

(0, 0) is the bottom left and (1, 1) is the top right coordinate of the texture. You want to map the bottom left of the texture to the vertex coordinate (-0.5, -0.5) and the top right of the texture to the vertex coordinate (0.5, 0.5).

Upvotes: 3

Related Questions