• Advertisement
Sign in to follow this  

OpenGL texture isn't working. ( first time ogl )

This topic is 4916 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello guys! I am not doing fanzy 3d stuff.. I am trying to draw a simple quad with a texture using SDL + OpenGl! The problem is that my quad is white.. but I should have the texture on it! uh? :| I don't get error messages when I load the SDL_Surface! Thank you very much! :) Here is the source code: main.cpp

#include "game_header.hpp"

#ifdef _WIN32
#undef main
#endif

LogFile LOG("logfile.log");


int main(int argc, char **argv)
{
	SDL_Surface *screen;
	bool running(true);


        init_SDL_OGL( screen, 640, 480 );
	GL_Texture* texture = new GL_Texture( "galaxien.bmp" );
	
	Quad quad( texture );
	
	
	
	SDL_Event event;
	
	while( running == true )
    {
		

		while(SDL_PollEvent(&event))
        {
			switch(event.type)
            {
    			case SDL_KEYDOWN:
                    				running = false;
                    				break;
    			case SDL_QUIT:
                    				running = false;
                    				break;
			}
		}
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);		
        quad.draw( 300, 300 );

		SDL_GL_SwapBuffers();
	}
        delete texture;
        return 0;
}


game_header.hpp
#include "eng_header.hpp"


eng_header.hpp
#include <SDL.h>
#include <SDL_opengl.h>


#include "eng_logfile.hpp"
#include "eng_init.hpp"
#include "eng_texture.hpp"
#include "eng_quad.hpp"


initSDL_OGL.hpp
#ifndef __ENG_INIT_HPP__
#define __ENG_INIT_HPP__

bool init_SDL_OGL( SDL_Surface* screen, const int w, const int h );

#endif


initSDL_OGL.cpp
#include "eng_header.hpp"

bool init_SDL_OGL( SDL_Surface* screen, const int w, const int h )
{
    // SDL:
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
		LOG << "Could not init SDL" << ENDL;
		exit( 1 );
	}
	atexit( SDL_Quit );

	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	screen = SDL_SetVideoMode( w, h, 0, SDL_OPENGL);
	if ( !screen )
    {
		LOG << "Couldn't set video mode!" << ENDL;
		exit(1);
	}
    
    
    // OGL:
    glViewport(0, 0, screen->w, screen->h);

	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	glOrtho(0, screen->w, screen->h, 0, -1.0, 1.0);

	glMatrixMode( GL_MODELVIEW );
	glLoadIdentity();
 
    return true;   
}    


eng_texture.hpp

#ifndef __ENG_TEXTURE_HPP__
#define __ENG_TEXTURE_HPP__

class GL_Texture
{
    public:
              GL_Texture( void );
              GL_Texture( const char* filename );
              
              ~GL_Texture( void );
              bool init( const char* filename );
              bool initTexture( void );
              
              int getW( void ) const{ return w; }
              int getH( void ) const{ return h; }
              unsigned getTexture( void ) const{ return texture; }
    private:
              SDL_Surface*  sprite;
              unsigned      texture;
              
              int w, h;
};
#endif


eng_texture.cpp
#include "eng_header.hpp"


GL_Texture::GL_Texture( void )
 :w(0), h(0), sprite( NULL )
{
    
}   

 
GL_Texture::GL_Texture( const char* filename )
 :w(0), h(0), sprite( NULL )
{
    init( filename );
    initTexture();
}    




// inits the SDl-surface
bool GL_Texture::init( const char* filename )
{
    if( sprite != NULL )
    {	
		  SDL_FreeSurface( sprite );
		  sprite = NULL;
	}
	
    // Load the BMP file into a surface
	sprite = SDL_LoadBMP( filename );

    if ( sprite == NULL )
    {
	    LOG << "Couldn't load " << filename << " -- "  << ENDL; 
        return false;
    }
    if( SDL_SetColorKey(sprite, SDL_SRCCOLORKEY | SDL_RLEACCEL, SDL_MapRGB(sprite->format, 255, 0, 255)) < 0)
    {
	    LOG << "Couldn't set the ColorKey for " << filename << " -- "  << ENDL;
		return false;
	}
    

	w = sprite->w;
	h = sprite->h;
	return true;       
}



bool GL_Texture::initTexture( void )
{
    SDL_Surface*  conv;
    
    // convert to 32-bit RGBA format
  	conv = SDL_CreateRGBSurface( SDL_SWSURFACE, sprite->w, sprite->h, 32,
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
	   0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
#else
       0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
#endif
    
    SDL_BlitSurface( sprite, 0, conv, 0);
    
    glGenTextures( 1, &texture );
	glBindTexture( GL_TEXTURE_2D, texture );
	
	
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NICEST );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NICEST );
	
    glPixelStorei( GL_UNPACK_ROW_LENGTH, conv->pitch / conv->format->BytesPerPixel );
	glTexImage2D( GL_TEXTURE_2D, 0, 3, conv->w, conv->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, conv->pixels);
	glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 );

	SDL_FreeSurface(conv);
}   



GL_Texture::~GL_Texture( void )
{
    if( sprite )
    {
		 SDL_FreeSurface( sprite );
		 sprite = NULL;
    }	
}    


quad.hpp

#ifndef __ENG_QUAD_HPP__
#define __ENG_QUAD_HPP__

class Quad
{
    public:
             Quad( GL_Texture* const texture ); 
             void draw( const int x, const int y );
    private:
             GL_Texture* texture;
};

#endif


quad.cpp
#include "eng_header.hpp"

Quad::Quad( GL_Texture* const texture2 )
 :texture( texture2 )
{
}

void Quad::draw( const int x, const int y )
{
    
    glEnable( GL_TEXTURE_2D );
	glBindTexture( GL_TEXTURE_2D, texture->getTexture() );
    
    // Don't use texture-w / h later
    const int t_w = texture->getW();
    const int t_h = texture->getH();
    
    
    glBegin( GL_QUADS );
		glTexCoord2f( 0, 0 );	glVertex2i( x, y );              // x -- y
		glTexCoord2f( 1, 0 );	glVertex2i( x + t_w, y );        // x+w -- y         
  		glTexCoord2f( 1, 1 );	glVertex2i( x + t_w, y + t_h );  // x+w -- y+h
		glTexCoord2f( 0, 1 );	glVertex2i( x, y + t_h );        // x -- y+h  
	glEnd();
}        


[Edited by - rakoon2 on September 3, 2004 8:25:12 PM]

Share this post


Link to post
Share on other sites
Advertisement
I don't remember using SDL's built-in bmp loader to load textures. Its probably possible, but you should try a NEHE tutorial and use the GLAUX library first and setup a texture that way. SDL's bitmap loader might not have the data the way OpenGL needs it? Don't quote me on this, just an idea to help troubleshoot.


Share this post


Link to post
Share on other sites
Quote:
Original post by DerAnged
i dont see a glEnable(GL_TEXTURE_2D); annywhere in there.


its in the quad.cpp file in the Draw(). You should really put a glDisable(GL_TEXTURE_2D); at the end if you are done texturing to avoid issues...

Share this post


Link to post
Share on other sites
I heard that I shouldn't use glaux(glut?!).. to load bmps. (so they said he should use sdl)

So.. what library should I use? *confused* :| :)

Share this post


Link to post
Share on other sites
Quote:

glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NICEST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NICEST );

GL_NICEST is not valid texture filters. I suppose you mean GL_LINEAR.

Share this post


Link to post
Share on other sites
Ah! That's it! Thank you! :)



One more question:

How can I let all quads rotate? ( they should rotate around their own center. )




I tried the rotate function.. but then my quads were gone after a sec!



I am using the same function as in the nehe tutorial.
Maybe I must use a different function?! ( ortho mode )

Oh:

glBegin( GL_QUADS );
glTexCoord2f( 0, 0 ); glVertex2i( x, y ); // x -- y
glTexCoord2f( 1, 0 ); glVertex2i( x, y + t_h ); // x -- y + h
glTexCoord2f( 1, 1 ); glVertex2i( x + t_w, y + t_h ); // x+w -- y+h
glTexCoord2f( 0, 1 ); glVertex2i( x + t_w, y ); // x+w-- y
glEnd();



is this right to make a quad? my quad is not w * h why? :|

[Edited by - rakoon2 on September 4, 2004 3:02:12 AM]

Share this post


Link to post
Share on other sites
its probably because you dont specify things in pixels, its some arbitrary unit, 1 is actually decently sized, but make sure you translate it back say, 10, thats what i always do for my little demos, in case you dont know transformations yet

glMatrixMode(GL_MODELVIEW);
glTranslatef(0.0f, 0.0f, -10.0f);
//do your rendering


ok wow, i must be tired, im not confident i have the constant for glMatrixMode() right, im pretty sure, but not 100%, i think that means its bed time, but anywho, hope that helps
-Dan

Share this post


Link to post
Share on other sites
glRotate rotates about the origin, so if you want to rotate the quad about it's center, you have to move it's center to the origin.

Since the quad extends from [x, y] to [x+w, y+h], the center is located at [x+w/2, y+h/2]. So first translate the center to the origin, rotate, and translate back. Something like this.

glTranslate(x+w/2, y+h/2, 0);
glRotate(whatever);
glTranslate(-x-w/2, -y-h/2, 0);

Share this post


Link to post
Share on other sites
Thank you! Thank you that works fine if I use single quads! :)

But what about if I want to rotate the full scene?

Here a screenshot what I mean:
http://members.chello.at/ennemoser/tile_rotation.jpg

Is it possible to do that without those black "holes"?
What must I rotate the quads about? window_w/2 - window_h/2 ? hmm..

how about:
glTranslatef( window_w/2, window_h/2, 0);
glRotatef( angle, 0.0f, 0.0f, 1.0f);
glTranslatef( - window_w/2, -window_h/2, 0);


Thank you again ^^

[Edited by - rakoon2 on September 4, 2004 5:03:08 AM]

Share this post


Link to post
Share on other sites
What you see in that jpg is not the scene rotating, but each individual tile rotating around it's own center. That is why there is black space.

Share this post


Link to post
Share on other sites
Yes I know. :)

glTranslatef( window_w/2, window_h/2, 0);
glRotatef( angle, 0.0f, 0.0f, 1.0f);
glTranslatef( - window_w/2, -window_h/2, 0);

is right. :p

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By LifeArtist
      Good Evening,
      I want to make a 2D game which involves displaying some debug information. Especially for collision, enemy sights and so on ...
      First of I was thinking about all those shapes which I need will need for debugging purposes: circles, rectangles, lines, polygons.
      I am really stucked right now because of the fundamental question:
      Where do I store my vertices positions for each line (object)? Currently I am not using a model matrix because I am using orthographic projection and set the final position within the VBO. That means that if I add a new line I would have to expand the "points" array and re-upload (recall glBufferData) it every time. The other method would be to use a model matrix and a fixed vbo for a line but it would be also messy to exactly create a line from (0,0) to (100,20) calculating the rotation and scale to make it fit.
      If I proceed with option 1 "updating the array each frame" I was thinking of having 4 draw calls every frame for the lines vao, polygons vao and so on. 
      In addition to that I am planning to use some sort of ECS based architecture. So the other question would be:
      Should I treat those debug objects as entities/components?
      For me it would make sense to treat them as entities but that's creates a new issue with the previous array approach because it would have for example a transform and render component. A special render component for debug objects (no texture etc) ... For me the transform component is also just a matrix but how would I then define a line?
      Treating them as components would'nt be a good idea in my eyes because then I would always need an entity. Well entity is just an id !? So maybe its a component?
      Regards,
      LifeArtist
    • By QQemka
      Hello. I am coding a small thingy in my spare time. All i want to achieve is to load a heightmap (as the lowest possible walking terrain), some static meshes (elements of the environment) and a dynamic character (meaning i can move, collide with heightmap/static meshes and hold a varying item in a hand ). Got a bunch of questions, or rather problems i can't find solution to myself. Nearly all are deal with graphics/gpu, not the coding part. My c++ is on high enough level.
      Let's go:
      Heightmap - i obviously want it to be textured, size is hardcoded to 256x256 squares. I can't have one huge texture stretched over entire terrain cause every pixel would be enormous. Thats why i decided to use 2 specified textures. First will be a tileset consisting of 16 square tiles (u v range from 0 to 0.25 for first tile and so on) and second a 256x256 buffer with 0-15 value representing index of the tile from tileset for every heigtmap square. Problem is, how do i blend the edges nicely and make some computationally cheap changes so its not obvious there are only 16 tiles? Is it possible to generate such terrain with some existing program?
      Collisions - i want to use bounding sphere and aabb. But should i store them for a model or entity instance? Meaning i have 20 same trees spawned using the same tree model, but every entity got its own transformation (position, scale etc). Storing collision component per instance grats faster access + is precalculated and transformed (takes additional memory, but who cares?), so i stick with this, right? What should i do if object is dynamically rotated? The aabb is no longer aligned and calculating per vertex min/max everytime object rotates/scales is pretty expensive, right?
      Drawing aabb - problem similar to above (storing aabb data per instance or model). This time in my opinion per model is enough since every instance also does not have own vertex buffer but uses the shared one (so 20 trees share reference to one tree model). So rendering aabb is about taking the model's aabb, transforming with instance matrix and voila. What about aabb vertex buffer (this is more of a cosmetic question, just curious, bumped onto it in time of writing this). Is it better to make it as 8 points and index buffer (12 lines), or only 2 vertices with min/max x/y/z and having the shaders dynamically generate 6 other vertices and draw the box? Or maybe there should be just ONE 1x1x1 cube box template moved/scaled per entity?
      What if one model got a diffuse texture and a normal map, and other has only diffuse? Should i pass some bool flag to shader with that info, or just assume that my game supports only diffuse maps without fancy stuff?
      There were several more but i forgot/solved them at time of writing
      Thanks in advance
    • By RenanRR
      Hi All,
      I'm reading the tutorials from learnOpengl site (nice site) and I'm having a question on the camera (https://learnopengl.com/Getting-started/Camera).
      I always saw the camera being manipulated with the lookat, but in tutorial I saw the camera being changed through the MVP arrays, which do not seem to be camera, but rather the scene that changes:
      Vertex Shader:
      #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec2 aTexCoord; out vec2 TexCoord; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(aPos, 1.0f); TexCoord = vec2(aTexCoord.x, aTexCoord.y); } then, the matrix manipulated:
      ..... glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); .... glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); ourShader.setMat4("view", view); .... model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); ourShader.setMat4("model", model);  
      So, some doubts:
      - Why use it like that?
      - Is it okay to manipulate the camera that way?
      -in this way, are not the vertex's positions that changes instead of the camera?
      - I need to pass MVP to all shaders of object in my scenes ?
       
      What it seems, is that the camera stands still and the scenery that changes...
      it's right?
       
       
      Thank you
       
    • By dpadam450
      Sampling a floating point texture where the alpha channel holds 4-bytes of packed data into the float. I don't know how to cast the raw memory to treat it as an integer so I can perform bit-shifting operations.

      int rgbValue = int(textureSample.w);//4 bytes of data packed as color
      // algorithm might not be correct and endianness might need switching.
      vec3 extractedData = vec3(  rgbValue & 0xFF000000,  (rgbValue << 8) & 0xFF000000, (rgbValue << 16) & 0xFF000000);
      extractedData /= 255.0f;
    • By Devashish Khandelwal
      While writing a simple renderer using OpenGL, I faced an issue with the glGetUniformLocation function. For some reason, the location is coming to be -1.
      Anyone has any idea .. what should I do?
  • Advertisement