Related
I am not sure why why code doesn't show a rotating cube. I am looking for the reason why. I think it has something to do with the perspective or view but I am not sure. I just need to understand why I can't get a simple cube onto the screen.
#include <iostream>
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#include "LoadShader.hpp" // just a function in a header that returns a GLuint for a shaderProgram
#define FS1 "shader1.frag"
#define VS1 "shader1.vert"
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/string_cast.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <assimp/cimport.h>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;
// The MAIN function, from here we start the application and run the game loop
int main()
{
// Init GLFW
glfwInit( );
// Set all the required options for GLFW
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 );
glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE );
glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );
// Create a GLFWwindow object that we can use for GLFW's functions
GLFWwindow *window = glfwCreateWindow( WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr );
int screenWidth, screenHeight;
glfwGetFramebufferSize( window, &screenWidth, &screenHeight );
if ( nullptr == window )
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate( );
return EXIT_FAILURE;
}
glfwMakeContextCurrent( window );
// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
glewExperimental = GL_TRUE;
// Initialize GLEW to setup the OpenGL Function pointers
if ( GLEW_OK != glewInit( ) )
{
std::cout << "Failed to initialize GLEW" << std::endl;
return EXIT_FAILURE;
}
glEnable( GL_DEPTH_TEST ) ;
//glDepthFunc( GL_LESS ) ;
// Define the viewport dimensions
glViewport( 0, 0, screenWidth, screenHeight );
//glMatrixMode(GL_PROJECTION);
// Set up vertex data (and buffer(s)) and attribute pointers
GLfloat vertices[ ] =
{ // verticies a0 // colors a1
// front
-1.0, -1.0, 1.0, .70f , 0.32f , 0.31f ,
1.0, -1.0, 1.0, .20f , 0.4f , 0.21f ,
1.0, 1.0, 1.0, .50f , 0.32f , 0.71f ,
-1.0, 1.0, 1.0, .60f , 0.62f , 0.11f ,
// back
-1.0, -1.0, -1.0, .30f , 0.87f , 0.60f ,
1.0, -1.0, -1.0, .30f , 0.87f , 0.f ,
1.0, 1.0, -1.0, .10f , 0.f , 0.60f ,
-1.0, 1.0, -1.0, .20f , 0.87f , 0.60f ,
// side Right
1.0f , 1.0 , 1.0 , .45f , .3f , .4f ,
1.0 , -1.0 , 1.0 , .5f , .8f, .1f ,
1.0 , -1.0 , -1.0 , .3f , .6f , .0f ,
1.0 , 1.0 , -1.0 , .45f , .87f , .53f ,
// left Side
-1.0f , 1.0 , 1.0 , .45f , .23f , .54f ,
-1.0 , -1.0 , 1.0 , .51f , .84f, .81f ,
-1.0 , -1.0 , -1.0 , .6f , .4f , .78f ,
-1.0 , 1.0 , -1.0 , .45f , .87f , .53f ,
//top
-1.f , 1.f , 1.f , .35f , .87f , .54f ,
-1.f , 1.f , -1.f , .45f , .98f, .92f ,
1.f , 1.f , 1.f , .50f , 0.f , .32f ,
1.f , 1.f , -1.f , 1.f , .72f , .87f ,
// bottom
-1.f , -1.f , 1.f , .35f , .87f , .54f ,
-1.f , -1.f , -1.f , .45f , .98f, .92f ,
1.f , -1.f , 1.f , .50f , .89f , .32f ,
1.f , -1.f , -1.f , 0.f , .72f , .87f
};
GLuint indices[ ] =
{
0 , 1 , 2 , 0 , 2 , 3 ,
4 , 5 , 6 , 4 , 6 , 7 ,
8 , 9 , 10 , 8 , 10 , 11 ,
12 , 13 , 14 , 12 , 14 , 15 ,
16 , 19 , 18 , 16 , 17 , 19 ,
20 , 23 , 22 , 20 , 21 , 23
} ;
int numOfIndices = sizeof( indices ) / sizeof ( GLuint ) ;
std::cout << numOfIndices << std::endl ;
GLuint VAO , VBO , EBO ;
glGenVertexArrays( 1 , &VAO ) ;
glBindVertexArray( VAO ) ;
glGenBuffers( 1 , &VBO ) ;
glBindBuffer( GL_ARRAY_BUFFER , VBO ) ;
glBufferData( GL_ARRAY_BUFFER , sizeof( vertices ) , vertices , GL_STATIC_DRAW ) ;
glVertexAttribPointer( 0 , 3 , GL_FLOAT , GL_FALSE , 6 * sizeof(GLfloat) , ( GLvoid * ) 0 ) ;
glEnableVertexAttribArray( 0 ) ;
glVertexAttribPointer( 1 , 3 , GL_FLOAT , GL_FALSE , 6 * sizeof(GLfloat) , (GLvoid*)(3 * sizeof(GL_FLOAT)) ) ;
glEnableVertexAttribArray( 1 ) ;
glGenBuffers( 1 , &EBO ) ;
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER , EBO ) ;
glBufferData( GL_ELEMENT_ARRAY_BUFFER , sizeof( indices ) , indices , GL_STATIC_DRAW ) ;
GLuint program = LoadShaders( VS1 , FS1 ) ;
glUseProgram( program ) ;
float rotationDegrees = 1.f ;
float fov = 1.0f ;
glm::mat4 view;
view = glm::lookAt(glm::vec3( 0.0f, 1.0f, -3.0f),
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 projectionMatrix = glm::perspective( fov , ( ( float ) HEIGHT ) / WIDTH , 1.f , 10.0f ) ;
glm::mat4 modelTransform = glm::translate( glm::mat4( 1.f ) , glm::vec3( .0f , -3.0f , -3.0f ) ) ;
glm::mat4 rotation = glm::rotate( glm::mat4(1.f) , rotationDegrees , glm::vec3( 1.f , 1.f , 0.f ) ) ;
//glm::mat4 rotation = glm::rotate( rotation1 , 30.f , glm::vec3( 0.f , 2.f , 0.f ) ) ;
glm::mat4 fullTransform = projectionMatrix * modelTransform * rotation ;
GLuint transformLocation = glGetUniformLocation( program , "uModelTranslate" ) ;
GLuint projectionLocation = glGetUniformLocation( program , "uProjectionMatrix" ) ;
//modelTransform = modelTransform * rotation ;
glUniformMatrix4fv( transformLocation , 1 , GL_FALSE , &modelTransform[0][0] ) ;
glUniformMatrix4fv( projectionLocation , 1 , GL_FALSE , &fullTransform[0][0] ) ;
bool canUp , canDown , canL , canR , canW , canS ,canA , canD , canQ , canE ;
canQ = true ;
canE = true ;
canD= true ;
canA = true ;
canUp = true ;
canS = true ;
canDown = true ;
canR = true ;
canL = true ;
canW = true ;
float nearF = 0.1f ;
float zZ = -3.0 ;
float yY = 1.0f ;
float xX = 0.f ;
while ( !glfwWindowShouldClose( window ) )
{
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents( );
rotationDegrees += .0001f ;
if( rotationDegrees >= 360 )
{
rotationDegrees =0 ;
}
view = glm::lookAt(glm::vec3( yY , xX, zZ),
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 rotation = glm::rotate( glm::mat4(1.f) , rotationDegrees , glm::vec3( 1.f , 1.f , 0.f ) ) ;
glm::mat4 projectionMatrix = glm::perspective(glm::radians(fov), (float) WIDTH / (float)HEIGHT , nearF, 10.0f);
glm::mat4 fullTransform = projectionMatrix * view * rotation ;
glUniformMatrix4fv( projectionLocation , 1 , GL_FALSE , &fullTransform[0][0] ) ;
// Render
// Clear the colorbuffer
glClearColor( 0.f, 0.f, 0.f, 1.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
if (glfwGetKey(window,GLFW_KEY_ESCAPE) == GLFW_PRESS )
{
glfwSetWindowShouldClose(window,true);
}
if (glfwGetKey(window,GLFW_KEY_UP) == GLFW_PRESS && canUp )
{
canUp = false ;
fov += 1.f ;
std::cout << fov << std::endl ;
}
if (glfwGetKey(window,GLFW_KEY_UP) != GLFW_PRESS && !canUp )
{
canUp = true ;
}
if (glfwGetKey(window,GLFW_KEY_DOWN) == GLFW_PRESS && canDown)
{
canDown = false ;
fov += -1.f ;
std::cout << fov << std::endl ;
}
if (glfwGetKey(window,GLFW_KEY_DOWN) != GLFW_PRESS && !canDown)
{
canDown = true ;
}
if (glfwGetKey(window,GLFW_KEY_ESCAPE) == GLFW_PRESS )
{
glfwSetWindowShouldClose(window,true);
}
if (glfwGetKey(window,GLFW_KEY_LEFT) == GLFW_PRESS && canL )
{
canL = false ;
nearF += 1.f ;
std::cout << nearF << std::endl ;
}
if (glfwGetKey(window,GLFW_KEY_LEFT) != GLFW_PRESS && !canL )
{
canL = true ;
}
if (glfwGetKey(window,GLFW_KEY_RIGHT) == GLFW_PRESS && canR)
{
canR = false ;
nearF += -1.f ;
std::cout << nearF << std::endl ;
}
if (glfwGetKey(window,GLFW_KEY_RIGHT) != GLFW_PRESS && !canR)
{
canR = true ;
}
if (glfwGetKey(window,GLFW_KEY_W) == GLFW_PRESS && canW)
{
canW = false ;
zZ += -1.f ;
std::cout << zZ << std::endl ;
}
if (glfwGetKey(window,GLFW_KEY_W) != GLFW_PRESS && !canW)
{
canW = true ;
}
if (glfwGetKey(window,GLFW_KEY_S) == GLFW_PRESS && canS)
{
canS = false ;
zZ += +1.f ;
std::cout << zZ << std::endl ;
}
if (glfwGetKey(window,GLFW_KEY_S) != GLFW_PRESS && !canS)
{
canS = true ;
}
if (glfwGetKey(window,GLFW_KEY_A) == GLFW_PRESS && canA)
{
canA = false ;
xX += +1.f ;
std::cout << xX << std::endl ;
}
if (glfwGetKey(window,GLFW_KEY_A) != GLFW_PRESS && !canA)
{
canA = true ;
}
if (glfwGetKey(window,GLFW_KEY_D) == GLFW_PRESS && canD)
{
canD = false ;
xX += -1.f ;
std::cout << xX << std::endl ;
}
if (glfwGetKey(window,GLFW_KEY_D) != GLFW_PRESS && !canD)
{
canD = true ;
}
if (glfwGetKey(window,GLFW_KEY_Q) == GLFW_PRESS && canQ)
{
canQ = false ;
yY += -1.f ;
std::cout << yY << std::endl ;
}
if (glfwGetKey(window,GLFW_KEY_Q) != GLFW_PRESS && !canQ)
{
canQ = true ;
}
if (glfwGetKey(window,GLFW_KEY_E) == GLFW_PRESS && canE)
{
canE = false ;
yY += 1.f ;
std::cout << yY << std::endl ;
}
if (glfwGetKey(window,GLFW_KEY_E) != GLFW_PRESS && !canE)
{
canE = true ;
}
//glUseProgram( program ) ;
glDrawElements( GL_TRIANGLES , numOfIndices , GL_UNSIGNED_INT , 0 ) ;
// Swap the screen buffers
glfwSwapBuffers( window );
}
glfwTerminate( );
return EXIT_SUCCESS;
}
The unit of the angle for glm::perspective and glm::rotate is radians. A field of view of 1° is far to small.
The translation component of the modelTransform matrix moves the object out of the viewing frustum and has to be reduced.
Furthermore I recommend to enable the Depth Test.
e.g.:
float rotationDegrees = 0.0f;
float fov = 90.0f;
float nearF = 0.1f;
float zZ = -3.0;
float yY = 1.0f;
float xX = 0.0f;
glEnable(GL_DEPTH_TEST);
while (!glfwWindowShouldClose(wnd))
{
glm::mat4 rotation = glm::rotate(glm::mat4(1.0f), glm::radians(rotationDegrees), glm::vec3(1.0f , 1.0f , 0.0f)) ;
glm::mat4 modelTransform = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.5f, 0.0f)) ;
glm::mat4 view = glm::lookAt(glm::vec3(yY , xX, zZ), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 modelview = view * modelTransform * rotation;
glm::mat4 projectionMatrix = glm::perspective(glm::radians(fov), (float)WIDTH / (float)HEIGHT, nearF, 10.0f);
rotationDegrees += 1.0f;
glUniformMatrix4fv(transformLocation, 1, GL_FALSE, glm::value_ptr(modelview));
glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, glm::value_ptr(projectionMatrix));
// [...]
}
Vertex shader:
#version 330 core
layout (location = 0) in vec3 inPos;
layout (location = 1) in vec3 inColor;
out vec3 vertCol;
uniform mat4 uProjectionMatrix;
uniform mat4 uModelTranslate;
void main()
{
vertCol = inColor;
gl_Position = uProjectionMatrix * uModelTranslate * vec4(inPos.xyz, 1.0);
}
Is it possible to map texture to Sphere that are generated by parametric equation and rendered using GL_POINTS primitive ? If it is possible, how is it be done and inside my code, I copy the code image loading code from the web and load it as it is instructed. One thing that I did not followed them is specifying the vertex for the texture coordinate, which I am not sure how to specify it exactly when render it with Sphere and with GL_POINTS primitive.
I am using the old OpenGL2 for my project and doing a solar system simulation
Here is the repository to the code and it is public
This is how I generate the sphere
// void Sphere::render () method, inside src/sphere.cpp - line 28
void Sphere::render () {
unsigned int angle = 0, angle2 = 0;
const double degree_to_rad = 3.14 / 180.0;
double value = .0, value2 = .0;
if ( this -> texture_file_name != "" ) {
glEnable ( GL_TEXTURE_2D );
glBindTexture( GL_TEXTURE_2D, this -> texture );
}
glBegin ( GL_POINTS );
for ( ; angle < 360; ++ angle ) {
value = angle * degree_to_rad;
for ( ; angle2 < 180; ++ angle2 ) {
value2 = angle2 * degree_to_rad;
/*/////////////////////////////////////////////
// do I need to do sth in here like glTexCoord2d ( ... ) ?
////////////////////////////////////////////*/
glVertex3d (
this -> calculateX ( value, value2 ),
this -> calculateY ( value, value2 ),
this -> calculateZ ( value )
);
}
angle2 = 0;
}
glEnd ();
if ( this -> texture_file_name != "" ) {
glDisable ( GL_TEXTURE_2D );
}
};
// void Sphere::draw () method, src/sphere.cpp - line 75
void Sphere::draw () {
glPushMatrix ();
glTranslated (
this -> coordinate [ 0 ],
this -> coordinate [ 1 ],
this -> coordinate [ 2 ]
);
glRotated (
this -> angle_degree,
this -> rotation [ 0 ],
this -> rotation [ 1 ],
this -> rotation [ 2 ]
);
this -> render ();
glPopMatrix ();
};
double Sphere::calculateX ( const double theta_degree_angle, const double phi_degree_angle ) {
return this -> radius * sin ( theta_degree_angle ) * cos ( phi_degree_angle );
};
double Sphere::calculateY ( const double theta_degree_angle, const double phi_degree_angle ) {
return this -> radius * sin ( theta_degree_angle ) * sin ( phi_degree_angle );
};
double Sphere::calculateZ ( const double theta_degree_angle ) {
return this -> radius * cos ( theta_degree_angle );
};
This is my loadTexture method
void Object::loadTexture () {
int & w = this -> texture_width, & h = this -> texture_height;
unsigned char * data = new unsigned char [ w * h * 3 ];
FILE * file;
try {
file = fopen ( this -> texture_file_name.c_str () , "rb" );
if ( !file ) return;
fread ( data, w * h * 3, 1, file );
fclose ( file );
} catch ( std::exception & error ) {
std::cout << "Loading Texture Error: " << error.what () << std::endl;
}
glGenTextures ( 1, & this -> texture );
glBindTexture ( GL_TEXTURE_2D, this -> texture );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, data );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL );
glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
delete [] data;
};
void Object::setTexture ( const char * file_name, const int width, const int height ) {
this -> texture_file_name = file_name;
this -> texture_width = width;
this -> texture_height = height;
this -> loadTexture ();
};
This is my main.cpp
// main.cpp
// gloabl vars
NonStd::Sphere sun = NonStd::Sphere ( 10 );
NonStd::Sphere earth = NonStd::Sphere ( 3 );
NonStd::Sphere moon = NonStd::Sphere ( 1 );
NonStd::Object space = NonStd::Object ();
void render ();
void modelInit ();
void idle ();
void windowOnChange ( int width, int height );
void mouseOnDrag ( int x, int y );
int main ( int args_len, char ** args_context ) {
glutInit ( &args_len, args_context );
glutInitDisplayMode ( GLUT_SINGLE );
glutInitWindowSize ( WINDOW_WIDTH, WINDOW_HEIGHT );
glutInitWindowPosition ( 100, 100 );
glutCreateWindow ( "Solar System Simulation" );
glEnable ( GL_NORMALIZE );
glEnable ( GL_COLOR_MATERIAL );
// all models initialization
modelInit ();
// event handlers
glutDisplayFunc ( render );
glutReshapeFunc ( windowOnChange );
// glutMotionFunc ( mouseOnDrag );
// global idle func
glutIdleFunc ( idle );
glutMainLoop ();
return 0;
};
void render () {
glClearColor ( .2, .3, .5, .8 );
glClear ( GL_COLOR_BUFFER_BIT );
if ( sun.isObjectShown () ) {
sun.draw ();
}
if ( earth.isObjectShown () ) {
earth.draw ();
}
if ( moon.isObjectShown () ) {
moon.draw ();
}
glFlush ();
};
void modelInit () {
// object visibility default is false
sun.setVisible ( true );
// move to proper position to for object for better viewing
sun.translateZ ( -90.0 );
// set object texture
sun.setTexture ( "resources/earth.jpg", 100, 100 );
// spin default is false, toggle it for spinning
sun.toggleSpin ();
earth.setVisible ( true );
earth.translateZ ( -90.0 );
earth.translateX ( 26.0 );
earth.setTexture ( "resources/earth.jpg", 100, 100 );
earth.toggleSpin ();
earth.setSpinSpeed ( 2 );
moon.setVisible ( true );
moon.translateZ ( -90.0 );
moon.translateX ( 20.0 );
moon.setTexture ( "resources/earth.jpg", 100, 100 );
moon.toggleSpin ();
};
After I set the texture on my sphere object, the sphere turn into this yellow color and before setting the texture, it was white, does this mean the texture already set but I have not yet specify the texture coordinate for it ?
FYI: The project said it is 2D, but actually I am doing it in 3D just to clarify it.
A sphere can either be created by tessellating an existing object like a icosahedron, or by stacking discs.
Stacking discs:
The following code creates a sphere by stacking up a number of discs (layers). Each layer has circumferenceTiles tiles around its circum. The U texture coordinate is wrapped arund the circum. The V texture coordinate is wrapped from the south pole to the north pole of the sphere.
void CreateSphereMesh( int layers, int circumferenceTiles, std::vector<float> &va, std::vector<int> &ia )
{
const float pi = 3.1414927f;
// create the vertex attributes
va.reserve( (layers+1)*(circumferenceTiles+1)*5 ); // 5 floats: x, y, z, u, v
for ( int il = 0; il <= layers; ++ il )
{
float layer_rel = (float)il / (float)layers;
float layer_ang = (1.0f - 2.0f * layer_rel) * pi/2.0f ;
float layer_sin = std::sin( layer_ang );
float layer_cos = std::cos( layer_ang );
for ( int ic = 0; ic <= circumferenceTiles; ic ++ )
{
float circum_rel = (float)ic / (float)circumferenceTiles;
float cricum_ang = circum_rel * 2.0f*pi - pi;
float circum_sin = std::sin( cricum_ang );
float circum_cos = std::cos( cricum_ang );
va.push_back( layer_cos * circum_cos ); // x
va.push_back( layer_cos * circum_sin ); // y
va.push_back( layer_sin ); // z
va.push_back( circum_rel ); // u
va.push_back( 1.0f - layer_rel ); // v
}
}
// create the face indices
ia.reserve( layers*circumferenceTiles*6 );
for ( int il = 0; il < layers; ++ il )
{
for ( int ic = 0; ic < circumferenceTiles; ic ++ )
{
int i0 = il * (circumferenceTiles+1) + ic;
int i1 = i0 + 1;
int i3 = i0 + circumferenceTiles+1;
int i2 = i3 + 1;
int faces[]{ i0, i1, i2, i0, i2, i3 };
ia.insert(ia.end(), faces+(il==0?3:0), faces+(il==layers-1?3:6));
}
}
}
An vertex array object for the fixed function pipline can be specified like this:
GLuint vao;
glGenVertexArrays( 1, &vao );
glBindVertexArray( vao );
GLuint vbo;
glGenBuffers( 1, &vbo );
glBindBuffer( GL_ARRAY_BUFFER, vbo );
glBufferData( GL_ARRAY_BUFFER, va.size()*sizeof(*va.data()), va.data(), GL_STATIC_DRAW );
GLuint ibo;
glGenBuffers( 1, &ibo );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ibo );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, ia.size()*sizeof(*ia.data()), ia.data(), GL_STATIC_DRAW );
glVertexPointer( 3, GL_FLOAT, 5*sizeof(*va.data()), 0 );
glEnableClientState( GL_VERTEX_ARRAY );
glTexCoordPointer( 2, GL_FLOAT, 5*sizeof(*va.data()), (void*)(3*sizeof(*va.data())) );
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
glBindVertexArray( 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
For modern OpenGL the generic vertex attribute data arrays have to be defined like this:
GLint avert_loc = ....;
GLint atexc_loc = ....;
glVertexAttribPointer( avert_loc, 3, GL_FLOAT, GL_FALSE, 5*sizeof(*va.data()), 0 );
glEnableVertexAttribArray( avert_loc );
glVertexAttribPointer( atexc_loc, 2, GL_FLOAT, GL_FALSE, 5*sizeof(*va.data()), (void*)(3*sizeof(*va.data())) );
glEnableVertexAttribArray( atexc_loc );
Finall the drawing operation:
glEnable( GL_TEXTURE_2D ); // for fixed function pipeline only
glBindVertexArray( vao );
glDrawElements( GL_TRIANGLES, (GLsizei)ia.size(), GL_UNSIGNED_INT, 0 );
glBindVertexArray( 0 );
Preview:
I want to draw multiple polygons in one buffer, here is my conception of how I think it should work, but it does not.
This is what I have:
GLuint VertexArrayID;
GLuint vao;
GLuint program;
typedef struct object{
GLuint vao;
GLuint numVertices;
} object;
object objects[MAX_VERTEX_COUNT];
Here I create VBO:
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, VertexArrayID);
glBufferData(GL_ARRAY_BUFFER, 2 * vertex_count * sizeof(float), data, GL_STATIC_DRAW);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(data), data);
glUseProgram(program);
GLuint vPosition = glGetAttribLocation(program, "vPosition");
glEnableVertexAttribArray(vPosition);
glVertexAttribPointer(vPosition, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
glVertexPointer(2, GL_FLOAT, 0, NULL);
glEnableClientState(GL_VERTEX_ARRAY);
//glDrawArrays(GL_TRIANGLE_FAN, 0, vertex_count);
And I made loop like that, but I think, when I put vao in objects[i].vao, every time when I came through that loop, it does the same without this loop, but I am not sure.
for (int i = 0; i < 5; i++)
{
objects[i].vao = vao;
glBindVertexArray(objects[i].vao);
objects[i].numVertices = vertex_count;
glDrawArrays(GL_TRIANGLE_FAN, 0, objects[i].numVertices);
}
glDisableClientState(GL_VERTEX_ARRAY);
Maybe you have some ideas?
Here I have an Image2D class object that is used to render basic 2D Images that works with my GUI hierarchy. My Shader Engine is quite large for I have a system to manage Shaders using template types. It also uses a Batch Process and all of my Assets that are loaded into memory are saved into a Storage class that handles the clean up of their memory footprint. It is too large of a project to show everything necessary to be able to compile a working program, but here is an example of a generated renderable object from within my ShaderEngine.
Image2d.h
class Image2d : public VisualMko {
private:
TextureInfo m_textureInfo;
// --- Only For Version 1.0 ---
// VBO //
unsigned m_vboTexture; //
unsigned m_vboPosition; //
unsigned m_vboIndices; //
// //
// VAO //
unsigned m_vao; //
// ------------------------- //
// version 2.0 variables below
glm::vec2 m_offsetPosition;
public:
Image2d( float fWidth, float fHeight, TextureInfo::FilterQuality filterQuality, bool generateMipMap, const std::string& strTextureFilename, const std::string& strId );
Image2d( const glm::uvec2& origin, const glm::uvec2& size, const std::string& strTextureFilename, const std::string& strId = std::string() );
virtual ~Image2d();
void setOffsetPosition( const glm::vec2& offset );
virtual void clearTextureInfos() override;
void render() override;
TextureInfo getTextureInfo() const;
void setTextureInfo( const TextureInfo& textureInfo );
private:
Image2d( const Image2d& c ); // Not Implemented
Image2d& operator=( const Image2d& c );
}; // Image2d
} // namespace vmk
#endif // IMAGE2D_H
Image2d.cpp
#include "stdafx.h"
#include "Image2d.h"
#include "AssetStorage.h"
#include "ShaderManager.h" // Only Needed For Version 1.0
#include "TextureFileReader.h"
namespace vmk {
// ----------------------------------------------------------------------------
// Image2d()
// Creates A Rectangular 2D Imgae Of The Size Specified And Stores It In A
// Vertex Array Object For Rendering. The Surface Verts Are Defined Like:
// width
// <------->
// v0 --- v2 ^
// : / : | height
// : / : |
// v1 --- v3 v
//
Image2d::Image2d( float fWidth, float fHeight, TextureInfo::FilterQuality filterQuality, bool generateMipMap, const std::string& strTextureFilename, const std::string& strId ) :
VisualMko( glm::uvec2(), strId ),
m_vboTexture( 0 ),
m_vboPosition( 0 ),
m_vboIndices( 0 ),
m_vao( 0 ) {
if ( fWidth <= 0 || fHeight <= 0 ) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " Invalid image size (" << fWidth << "," << fHeight << ") must be more then 0 in each dimension.";
throw ExceptionHandler( strStream );
}
// Save TextureID
TextureFileReader textureFileReader( strTextureFilename );
m_textureInfo = textureFileReader.getOrCreateTextureInfo( filterQuality, generateMipMap, false );
// Define Texture Coordinates
std::vector<float> vTextureCoordinates;
vTextureCoordinates.push_back( 0.0f );
vTextureCoordinates.push_back( 1.0f );
vTextureCoordinates.push_back( 0.0f );
vTextureCoordinates.push_back( 0.0f );
vTextureCoordinates.push_back( 1.0f );
vTextureCoordinates.push_back( 1.0f );
vTextureCoordinates.push_back( 1.0f );
vTextureCoordinates.push_back( 0.0f );
// Define Vertex Positions (x,y,z)
std::vector<float> vVertexPositions;
vVertexPositions.push_back( 0.0f );
vVertexPositions.push_back( fHeight );
vVertexPositions.push_back( 0.0f );
vVertexPositions.push_back( 0.0f );
vVertexPositions.push_back( 0.0f );
vVertexPositions.push_back( 0.0f );
vVertexPositions.push_back( fWidth );
vVertexPositions.push_back( fHeight );
vVertexPositions.push_back( 0.0f );
vVertexPositions.push_back( fWidth );
vVertexPositions.push_back( 0.0f );
vVertexPositions.push_back( 0.0f );
// Define 2 Triangle Faces
std::vector<unsigned char> vIndices;
vIndices.push_back( 0 );
vIndices.push_back( 1 );
vIndices.push_back( 2 );
vIndices.push_back( 3 );
// Create Vertex Array Object
glGenVertexArrays( 1, &m_vao );
glBindVertexArray( m_vao ); // Start Array
m_pShaderManager->setAttribute( A_COLOR, COLOR_WHITE );
// Create Position Buffer And Store On Video Card
glGenBuffers( 1, &m_vboPosition );
glBindBuffer( GL_ARRAY_BUFFER, m_vboPosition );
glBufferData( GL_ARRAY_BUFFER, vVertexPositions.size() * sizeof( vVertexPositions[0] ), &vVertexPositions[0], GL_STATIC_DRAW );
m_pShaderManager->enableAttribute( A_POSITION );
// Create Texture Coordinate Buffer
glGenBuffers( 1, &m_vboTexture );
glBindBuffer( GL_ARRAY_BUFFER, m_vboTexture );
glBufferData( GL_ARRAY_BUFFER, vTextureCoordinates.size() * sizeof( vTextureCoordinates[0] ), &vTextureCoordinates[0], GL_STATIC_DRAW );
m_pShaderManager->enableAttribute( A_TEXTURE_COORD0 );
// Create Index Buffer
glGenBuffers( 1, &m_vboIndices );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_vboIndices );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, vIndices.size() * sizeof( vIndices[0] ), &vIndices[0], GL_STATIC_DRAW );
glBindVertexArray( 0 ); // Stop Array
// Disable Attribute Pointers
m_pShaderManager->disableAttribute( A_POSITION );
m_pShaderManager->disableAttribute( A_TEXTURE_COORD0 );
// THIS MUST BE AFTER: Vertex Array Buffer Is Unbound!
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); // Stop Buffer Index
glBindBuffer( GL_ARRAY_BUFFER, 0 ); // Stop Buffer
} // Image2d - v1.0
// ----------------------------------------------------------------------------
// Image2d()
Image2d::Image2d( const glm::uvec2& origin, const glm::uvec2& size, const std::string& strTextureFilename, const std::string& strId ) :
VisualMko( size, strId ),
m_vboTexture( 0 ),
m_vboPosition( 0 ),
m_vboIndices( 0 ),
m_vao( 0 ) {
m_version = 2;
TextureFileReader textureFileReader( strTextureFilename );
m_textureInfo = textureFileReader.getOrCreateTextureInfo( TextureInfo::FILTER_NONE, false, false );
m_config.uTextureId = m_textureInfo.uTextureId;
if ( 0 == m_textureInfo.size.x || 0 == m_textureInfo.size.y ) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " size of " << strTextureFilename << " is invalid " << m_textureInfo.size;
throw ExceptionHandler( strStream );
}
// Verify Image Fits Inside Texture
if ( m_textureInfo.size.x < size.x + origin.x || m_textureInfo.size.y < size.y + origin.y ) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " " << strTextureFilename << " size is " << m_textureInfo.size
<< " which is too small for an image that is " << size
<< " pixels in size, with an origin point set at " << origin ;
throw ExceptionHandler( strStream );
}
glm::vec2 textureCoordScaleFactor( 1.0f / static_cast<float>( m_textureInfo.size.x ),
1.0f / static_cast<float>( m_textureInfo.size.y ) );
glm::vec2 texCoordBottomLeft = glm::vec2( textureCoordScaleFactor.x * origin.x,
textureCoordScaleFactor.y * ( m_textureInfo.size.y - origin.y - size.y ) );
glm::vec2 texCoordTopRight = glm::vec2( textureCoordScaleFactor.x * ( origin.x + size.x ),
textureCoordScaleFactor.y * (m_textureInfo.size.y - origin.y ) );
// Set Colors And Texture Coordinates (Position Will Be Updated In Render Function
m_vVertices.push_back( GuiVertex( glm::vec2(), COLOR_WHITE, glm::vec2( texCoordBottomLeft.x, texCoordTopRight.y ) ) );
m_vVertices.push_back( GuiVertex( glm::vec2(), COLOR_WHITE, glm::vec2( texCoordBottomLeft.x, texCoordBottomLeft.y ) ) );
m_vVertices.push_back( GuiVertex( glm::vec2(), COLOR_WHITE, glm::vec2( texCoordTopRight.x, texCoordTopRight.y ) ) );
m_vVertices.push_back( GuiVertex( glm::vec2(), COLOR_WHITE, glm::vec2( texCoordTopRight.x, texCoordBottomLeft.y ) ) );
} // Image2d() - v2.0
// ----------------------------------------------------------------------------
// ~Image2d()
Image2d::~Image2d() {
if ( 1 == m_version ) {
// Destroy Objects
if ( m_vboTexture != 0 ) {
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glDeleteBuffers( 1, &m_vboTexture );
m_vboTexture = 0;
}
if ( m_vboPosition != 0 ) {
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glDeleteBuffers( 1, &m_vboPosition );
m_vboPosition = 0;
}
if ( m_vboIndices != 0 ) {
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glDeleteBuffers( 1, &m_vboIndices );
m_vboIndices = 0;
}
if ( m_vao != 0 ) {
glBindVertexArray( 0 );
glDeleteVertexArrays( 1, &m_vao );
m_vao = 0;
}
}
} // Image2d
// ----------------------------------------------------------------------------
// setOffsetPosition()
void Image2d::setOffsetPosition( const glm::vec2& offset ) {
if ( offset.x != m_offsetPosition.x || offset.y != m_offsetPosition.y ) {
m_offsetPosition = offset;
m_transformMatrix.updateTranslation = true;
}
} // setOffsetPosition
// ----------------------------------------------------------------------------
// clearTextureInfos()
void Image2d::clearTextureInfos() {
if ( m_pAssetStorage->removeTextureInfo( m_textureInfo.uTextureId ) ) {
m_textureInfo = TextureInfo();
}
} // clearTextureInfos
// ----------------------------------------------------------------------------
// render()
void Image2d::render() {
if ( 1 == m_version ) {
m_pShaderManager->setTexture( 0, U_TEXTURE0_SAMPLER_2D, m_textureInfo.uTextureId );
glBindVertexArray( m_vao );
glDrawElements( GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, nullptr );
glBindVertexArray( 0 );
} else {
// Version 2.0
// Update Vertices
if ( m_transformMatrix.updateTranslation || m_transformMatrix.updateScale || m_transformMatrix.updateRotation ) {
m_transformMatrix.updateTranslation = m_transformMatrix.updateScale = m_transformMatrix.updateRotation = false;
// Order Of Operations Matter Here!
glm::mat4 matrix; // identity
if ( m_transformMatrix.hasTranslation ) {
matrix[3][0] = m_transformMatrix.translation.x;
matrix[3][1] = m_transformMatrix.translation.y;
}
if ( m_transformMatrix.hasRotation ) {
matrix = glm::rotate( matrix, m_transformMatrix.fRotationAngleDegrees, glm::vec3( 0.0f, 0.0f, -1.0f ) );
}
if ( m_transformMatrix.hasScale ) {
matrix = matrix * glm::mat4( m_transformMatrix.scale.x, 0.0f, 0.0f, 0.0f,
0.0f, m_transformMatrix.scale.y, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f );
}
// Center Offset
if ( m_offsetPosition.x != 0 || m_offsetPosition.y != 0 ) {
matrix = glm::translate( matrix, glm::vec3( -m_offsetPosition.x, -m_offsetPosition.y, 0.0f ) );
}
// Apply Transformation To All 4 Vertices
m_vVertices[0].position = glm::vec2( matrix * glm::vec4( 0, 0, 0, 1.0f ) );
m_vVertices[1].position = glm::vec2( matrix * glm::vec4( 0, m_size.y, 0, 1.0f ) );
m_vVertices[2].position = glm::vec2( matrix * glm::vec4( m_size.x, 0, 0, 1.0f ) );
m_vVertices[3].position = glm::vec2( matrix * glm::vec4( m_size.x, m_size.y, 0, 1.0f ) );
}
renderBatch();
}
} // render
// ----------------------------------------------------------------------------
// getTextureInfos()
TextureInfo Image2d::getTextureInfo() const {
return m_textureInfo;
} // getTextureInfo
// ----------------------------------------------------------------------------
// setTextureInfo()
void Image2d::setTextureInfo( const TextureInfo& textureInfo ) {
m_textureInfo = textureInfo;
} // setTextureInfo
} // namespace vmk
Now this class has two constructors which will get called depending on which version of the Image2d is being used. If I remember correctly version 1 does not use the BatchManager or Batch Process while version 2 does. If you look at the 1st Constructor. glBindVertexArray( 0 ); and glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); methods are called to stop the arrays and buffers. In render call in the first section of the if statement again we call glBindVertexArray( 0 ); to stop the array.
If you look at the destructor version 2 does not get cleaned up due to the fact that it is being used through the BatchManager and everything that is used through the BatchManager is automatically cleaned up and handled by my AssetStorage class. However, since version 1 of this class does not use the BatchManager it has to clean itself up and you can see the calls to glBindBuffer( BUFFER_ENUMERATED_TYPE, 0 ); followed by a glDeleteBuffers(...); call then setting the VBOs and VAO to 0.
If you would like to know more about this and how to successfully build a 3D Graphics ShaderEngine using modern OpenGL visit http://www.marekknows.com for this is where I have learned how to successfully use OpenGL. These works are not of my own design, but everything in this Engine was manually typed and debugged by following Marek's video tutorials.
I'm drawing sprites that are all in a buffer using glDrawElements.
To tell sprites what texture to be in the fragment shader I have uniform sampler2D textures[32]; each vertex has an index, which is passed to the fragment shader from the vertex shader:
color = texture(textures[index], fs_in.uv);
when I try draw my sprites with more than 1 texture active it gets the wrong textures in the top right corner
http://puu.sh/lyr5j/d8c2cf6c8f.png
I have no clue why this is happening have tried texture parameters
I cant seem to find anyone who has had a similar problem.
This is my renderer's init function (I am purposly passing the texid as float since I have heard ints don't work well (also tried))
glGenBuffers(1, &m_VDBO);
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VDBO);
glBufferData(GL_ARRAY_BUFFER, RENDERER_BUFFER_SIZE, 0, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(SHADER_VERTEX_INDEX);
glEnableVertexAttribArray(SHADER_UV_INDEX);
glEnableVertexAttribArray(SHADER_COLOR_INDEX);
glEnableVertexAttribArray(SHADER_TEXID_INDEX);
glVertexAttribPointer(SHADER_VERTEX_INDEX, 3, GL_FLOAT, GL_FALSE, RENDERER_VERTEX_SIZE, (const void *) offsetof(VertexData, VertexData::vertex));
glVertexAttribPointer(SHADER_UV_INDEX, 2, GL_FLOAT, GL_FALSE, RENDERER_VERTEX_SIZE, (const void *) offsetof(VertexData, VertexData::uv));
glVertexAttribPointer(SHADER_COLOR_INDEX, 4, GL_UNSIGNED_BYTE, GL_TRUE, RENDERER_VERTEX_SIZE, (const void *) offsetof(VertexData, VertexData::color));
glVertexAttribPointer(SHADER_TEXID_INDEX, 1, GL_FLOAT, GL_FALSE, RENDERER_VERTEX_SIZE, (const void *)offsetof(VertexData, VertexData::texID));
glBindBuffer(GL_ARRAY_BUFFER, 0);
const GLushort modelindices[] = { 0, 1, 2, 2, 3, 0 };
GLuint indices[RENDERER_INDICES_SIZE];
for (int i = 0; i < RENDERER_INDICES_SIZE; i += 6)
{
for (int o = 0; o < 6; o++)
{
indices[i + o] = modelindices[o] + (i / 6 * 4);
}
}
glGenBuffers(1, &m_IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, RENDERER_INDICES_SIZE * sizeof(GLuint), indices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
the flush function
glBindVertexArray(m_VAO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO);
for (int i = 0; i < m_TextureSlots.size(); i++)
{
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, m_TextureSlots[i]);
}
glDrawElements(GL_TRIANGLES, m_IndexCount, GL_UNSIGNED_INT, 0);
m_TextureSlots.clear();
m_IndexCount = 0;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
It is hard for me to see where your problem is coming from, the only thing I can suggest is taking a look at an Image2d class object constructor that I have. Now, my source depends on outside classes such as a ShaderManager class that relies heavily on template types and a Batch class and a BatchManager class to send over the vertices to the video card. Also this Image2d is an inherited object. However, this may serve as some help to you in tracking down your own problem. There are two different constructors for different versions of the implementation depending on which version of OpenGL and GLSL is being used. If I remember correctly version 2 uses the BatchManager to send the vertices to the video card where version 1 doesn't which can be seen within the render() method.
Image2d v1.0
// ----------------------------------------------------------------------------
// Image2d()
Image2d::Image2d( float fWidth, float fHeight, TextureInfo::FilterQuality filterQuality, bool generateMipMap, const std::string& strTextureFilename, const std::string& strId ) :
VisualMko( glm::uvec2(), strId ),
m_vboTexture( 0 ),
m_vboPosition( 0 ),
m_vboIndices( 0 ),
m_vao( 0 ) {
if ( fWidth <= 0 || fHeight <= 0 ) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " Invalid image size (" << fWidth << "," << fHeight << ") must be more then 0 in each dimension.";
throw ExceptionHandler( strStream );
}
// Save TextureId
TextureFileReader textureFileReader( strTextureFilename );
m_textureInfo = textureFileReader.getOrCreateTextureInfo( filterQuality, generateMipMap, false );
// Define Texture Co-Ordinates
std::vector<float> vTextureCoordinates;
vTextureCoordinates.push_back( 0.0f );
vTextureCoordinates.push_back( 1.0f );
vTextureCoordinates.push_back( 0 );
vTextureCoordinates.push_back( 0 );
vTextureCoordinates.push_back( 1.0f );
vTextureCoordinates.push_back( 1.0f );
vTextureCoordinates.push_back( 1.0f );
vTextureCoordinates.push_back( 0 );
// Define Vertex Positions (x,y,z)
std::vector<float> vVertexPositions;
vVertexPositions.push_back( 0 );
vVertexPositions.push_back( fHeight );
vVertexPositions.push_back( 0 );
vVertexPositions.push_back( 0 );
vVertexPositions.push_back( 0 );
vVertexPositions.push_back( 0 );
vVertexPositions.push_back( fWidth );
vVertexPositions.push_back( fHeight );
vVertexPositions.push_back( 0 );
vVertexPositions.push_back( fWidth );
vVertexPositions.push_back( 0 );
vVertexPositions.push_back( 0 );
// Define 2 Triangle Faces
std::vector<unsigned char> vIndices;
vIndices.push_back( 0 );
vIndices.push_back( 1 );
vIndices.push_back( 2 );
vIndices.push_back( 3 );
// Create Vertex Array Object
glGenVertexArrays( 1, &m_vao );
glBindVertexArray( m_vao ); // Start Array
m_pShaderManager->setAttribute( A_COLOR, COLOR_WHITE );
// Create Position Buffer And Store On Video Card
glGenBuffers( 1, & m_vboPosition );
glBindBuffer( GL_ARRAY_BUFFER, m_vboPosition );
glBufferData( GL_ARRAY_BUFFER, vVertexPositions.size() * sizeof( vVertexPositions[0] ), &vVertexPositions[0], GL_STATIC_DRAW );
m_pShaderManager->enableAttribute( A_POSITION );
// Create Texture Coordinate Buffer
glGenBuffers( 1, &m_vboTexture );
glBindBuffer( GL_ARRAY_BUFFER, m_vboTexture );
glBufferData( GL_ARRAY_BUFFER, vTextureCoordinates.size() * sizeof( vTextureCoordinates[0] ), &vTextureCoordinates[0], GL_STATIC_DRAW );
m_pShaderManager->enableAttribute( A_TEXTURE_COORD0 );
// Create Index Buffer
glGenBuffers( 1, &m_vboIndices );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_vboIndices );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, vIndices.size() * sizeof( vIndices[0] ), &vIndices[0], GL_STATIC_DRAW );
glBindVertexArray( 0 ); // Stop Array
// Disable Attribute Pointers
m_pShaderManager->disableAttribute( A_POSITION );
m_pShaderManager->disableAttribute( A_TEXTURE_COORD0 );
// THIS MUST BE AFTER Vertex Array Buffer Is Unbound!
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); // Stop Buffer Index
glBindBuffer( GL_ARRAY_BUFFER, 0 ); // Stop Buffer
// We have a Valid Image2d Save Filename
m_strFilename = strTextureFilename;
} // Image2D - v1.0
Image2D - v2.0
// ----------------------------------------------------------------------------
// Image2d()
Image2d::Image2d( const glm::uvec2& origin, const glm::uvec2& size, const std::string& strTextureFilename, const std::string& strId ) :
VisualMko( size, strId ),
m_vboTexture( 0 ),
m_vboPosition( 0 ),
m_vboIndices( 0 ),
m_vao( 0 ) {
m_version = 2;
TextureFileReader textureFileReader( strTextureFilename );
m_textureInfo = textureFileReader.getOrCreateTextureInfo( TextureInfo::FILTER_NONE, false, false );
m_config.uTextureId = m_textureInfo.uTextureId;
if ( 0 == m_textureInfo.size.x || 0 == m_textureInfo.size.y ) {
std::ostringstream strStream;
strStream << __FUNCTION__ << "size of " << strTextureFilename << " is invalid " << m_textureInfo.size;
throw ExceptionHandler( strStream );
}
// Verify Image Fits Inside Texture
if ( m_textureInfo.size.x < size.x + origin.x || m_textureInfo.size.y < size.y + origin.y ) {
std::ostringstream strStream;
strStream << __FUNCTION__ << " " << strTextureFilename << " size is " << m_textureInfo.size
<< " which is too small for an image that is " << size
<< " pixels in size, with an origin point set at " << origin ;
throw ExceptionHandler( strStream );
}
glm::vec2 textureCoordScaleFactor( 1.0f / static_cast<float>( m_textureInfo.size.x ),
1.0f / static_cast<float>( m_textureInfo.size.y ) );
glm::vec2 textureCoordBottomLeft = glm::vec2( textureCoordScaleFactor.x * origin.x,
textureCoordScaleFactor.y * ( m_textureInfo.size.y - origin.y - size.y ) );
glm::vec2 textureCoordTopRight = glm::vec2( textureCoordScaleFactor.x * ( origin.x + size.x ),
textureCoordScaleFactor.y * ( m_textureInfo.size.y - origin.y ) );
// Set Colors And Texture Coordinates (Position Will Be Updated In Render Function)
m_vVertices.push_back( GuiVertex( glm::vec2(), COLOR_WHITE, glm::vec2( textureCoordBottomLeft.x, textureCoordTopRight.y ) ) );
m_vVertices.push_back( GuiVertex( glm::vec2(), COLOR_WHITE, glm::vec2( textureCoordBottomLeft.x, textureCoordBottomLeft.y ) ) );
m_vVertices.push_back( GuiVertex( glm::vec2(), COLOR_WHITE, glm::vec2( textureCoordTopRight.x, textureCoordTopRight.y ) ) );
m_vVertices.push_back( GuiVertex( glm::vec2(), COLOR_WHITE, glm::vec2( textureCoordTopRight.x, textureCoordBottomLeft.y ) ) );
} // Image2d - v2.0
and here is my render() method
// ----------------------------------------------------------------------------
// render()
void Image2d::render() {
if ( 1 == m_version ) {
m_pShaderManager->setTexture( 0, U_TEXTURE0_SAMPLER_2D, m_textureInfo.uTextureId );
glBindVertexArray( m_vao );
glDrawElements( GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_BYTE, nullptr );
glBindVertexArray( 0 );
} else {
// Version 2.0
// Update Vertices
if ( m_transformMatrix.updateTranslation || m_transformMatrix.updateScale || m_transformMatrix.updateRotation ) {
m_transformMatrix.updateTranslation = m_transformMatrix.updateScale = m_transformMatrix.updateRotation = false;
// Order Of Operations Matter Here!
glm::mat4 matrix; // Identity
if ( m_transformMatrix.hasTranslation ) {
matrix[3][0] = m_transformMatrix.translation.x;
matrix[3][1] = m_transformMatrix.translation.y;
}
if ( m_transformMatrix.hasRotation ) {
matrix = glm::rotate( matrix, m_transformMatrix.fRotationAngleRadians, glm::vec3( 0.0f, 0.0f, -1.0f ) );
}
if ( m_transformMatrix.hasScale ) {
matrix = matrix * glm::mat4( m_transformMatrix.scale.x, 0.0f, 0.0f, 0.0f,
0.0f, m_transformMatrix.scale.y, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f );
}
// Center Offset
if ( m_offsetPosition.x != 0 || m_offsetPosition.y != 0 ) {
matrix = glm::translate( matrix, glm::vec3( -m_offsetPosition.x, -m_offsetPosition.y, 0.0f ) );
}
// Apply Transformation To All 4 Vertices
m_vVertices[0].position = glm::vec2( matrix * glm::vec4( 0, 0, 0, 1.0f ) );
m_vVertices[1].position = glm::vec2( matrix * glm::vec4( 0, m_size.y, 0, 1.0f ) );
m_vVertices[2].position = glm::vec2( matrix * glm::vec4( m_size.x, 0, 0, 1.0f ) );
m_vVertices[3].position = glm::vec2( matrix * glm::vec4( m_size.x, m_size.y, 0, 1.0f ) );
}
renderBatch();
}
} // render
Make sure that the sizes you are specifying in your glBufferData(GL_ARRAY_BUFFER, RENDERER_BUFFER_SIZE, 0, GL_DYNAMIC_DRAW);
is accurate. Also make sure that you are stopping your your VertexArray at the appropriate time as well as disabling your Attribute Pointers. Everything that you bound must be unbound, and for some types Order does matter!
In the following test program, I am trying to render a green square (250 x 250) in the bottom left corner of the screen (500 x 500).
I am using two buffer textures to pass in two int arrays (each array is of size 500 * 500) to the fragment shader. The arrays are simply populated with x (first array) and y (second array) values that correspond to all the (x, y) coordinates in screen space (this is shown in the init() part of the code below).
In the fragment shader, if the current fragment location (in screen space) is less than 250.0 in both the x and the y directions, that fragment is colored green. Otherwise, it is colored red. Images shown below.
Below is the full OpenGL code, along with the pass-through vertex shader (located in the main program) and a fragment shader (read in from a file). In the fragment shader, there are three tests (A, B, and C). Tests B and C are not working as expected. They draw the green square on the bottom right instead of the bottom left.
Test A (correct): The output of this code works as expected (a green square in bottom left corner of screen) when I use gl_FragCoord.xy in the conditional if check.
Test B (incorrect): If I use the buffer textures along with texelFetch to retrieve the x and y values of the current fragment and then use that in the conditional if check, the green square gets drawn in the lower right hand corner.
Test C (incorrect): If I forego the buffer textures and instead just compute the current fragment index and use a simple mod and division to to get the x, y indices, the green square is still drawn on the bottom right.
Any insight would be appreciated.
I'm using:
Ubuntu 12.04.5 LTS, 64 bit
glGetString(GL_VERSION) = 4.4.0 NVIDIA 331.113
Main Program: mytest.cc
// This program was modified from:
// https://www.opengl.org/discussion_boards/showthread.php/173917-samplerBuffer-example-needed
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#define GL_GLEXT_PROTOTYPES 1
#include <GL/gl.h>
#include <GL/glut.h>
using namespace std;
static const char Vertex_src[] =
"void main(void) \n"
"{ \n"
" gl_Position = ftransform(); \n"
"} \n";
std::string readFile(const char *filePath)
{
std::string content;
std::ifstream fileStream(filePath, std::ios::in);
if(!fileStream.is_open()) {
std::cerr << "Could not read file " << filePath << ". File does not exist." << std::endl;
return "";
}
std::string line = "";
while(!fileStream.eof()) {
std::getline(fileStream, line);
content.append(line + "\n");
}
fileStream.close();
return content;
}
void keybd ( unsigned char, int, int )
{
exit ( 0 ) ;
}
void reshape(int wid, int ht)
{
glViewport(0, 0, wid, ht);
}
void showGLerror ()
{
GLenum err ;
while ( (err = glGetError()) != GL_NO_ERROR )
fprintf ( stderr, "OpenGL Error: %s\n", gluErrorString ( err ) ) ;
}
void display ( void )
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewport(0, 0, 500, 500);
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
// Draw a full screen quad.
GLfloat s = 1.0;
glBegin(GL_QUADS);
glVertex3f(0.0f, 0.0f, 0.0f);
glVertex3f(s, 0.0f, 0.0f);
glVertex3f(s, s, 0.0f);
glVertex3f(0.0f, s, 0.0f);
glEnd();
glPopAttrib();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glutSwapBuffers () ;
glutPostRedisplay () ;
}
void showShaderInfo ( const char *what, GLuint handle )
{
int len = 0 ;
glGetObjectParameterivARB ( handle, GL_OBJECT_INFO_LOG_LENGTH_ARB, &len ) ;
if ( len > 0 )
{
int trueLen ;
char *s = new char [ len ] ;
glGetInfoLogARB ( handle, len, &trueLen, s ) ;
if ( trueLen > 0 && s [ 0 ] != '\0' )
fprintf ( stderr, "%s:\n%s\n", what, s ) ;
delete [] s ;
}
}
GLuint compileShader ( const char *src, GLenum type )
{
const char *type_str = type == GL_VERTEX_SHADER ? "vertex" : "fragment";
GLuint handle = glCreateShader( type ) ;
glShaderSource ( handle, 1, &src, 0 ) ;
glCompileShader( handle ) ;
GLint compiled ;
glGetShaderiv( handle, GL_COMPILE_STATUS, &compiled ) ;
if ( !compiled )
{
showShaderInfo ( type_str, handle ) ;
fprintf ( stderr, "Failed to compile %s shader.\n", type_str );
exit ( 1 ) ;
}
return handle ;
}
GLuint linkShaders ( GLuint vsHandle, GLuint fsHandle )
{
GLint linked ;
GLuint handle = glCreateProgram() ;
glAttachShader ( handle, vsHandle ) ;
glAttachShader ( handle, fsHandle ) ;
glLinkProgram ( handle ) ;
glGetProgramiv ( handle, GL_LINK_STATUS, & linked ) ;
if ( !linked )
{
showShaderInfo ( "Linking", handle ) ;
fprintf ( stderr, "Failed to link shader program.\n" ) ;
exit ( 1 ) ;
}
return handle ;
}
void init()
{
int arraySize = 500 * 500;
int *array_x = new int[arraySize];
int *array_y = new int[arraySize];
// Populate arrays.
for (int y = 0; y < 500; y++) {
for (int x = 0; x < 500; x++) {
array_x[(y * 500) + x] = x;
array_y[(y * 500) + x] = y;
}
}
const size_t size = sizeof( int ) * arraySize;
//// array_x
//
// Generate and fill buffer object
GLuint buffer;
glGenBuffers ( 1, &buffer );
glBindBuffer ( GL_TEXTURE_BUFFER, buffer );
glBufferData ( GL_TEXTURE_BUFFER, size, array_x, GL_STATIC_DRAW ); // Alloc & Fill
// Generate texture "wrapper" around buffer object
GLuint tex;
glGenTextures ( 1, &tex );
glActiveTexture( GL_TEXTURE0);
glBindTexture ( GL_TEXTURE_BUFFER, tex );
glTexBuffer ( GL_TEXTURE_BUFFER, GL_R32I, buffer );
//// array_y
//
// Generate and fill buffer object
GLuint buffer2;
glGenBuffers ( 1, &buffer2 );
glBindBuffer ( GL_TEXTURE_BUFFER, buffer2 );
glBufferData ( GL_TEXTURE_BUFFER, size, array_y, GL_STATIC_DRAW ); // Alloc & Fill
// Generate texture "wrapper" around buffer object
GLuint tex2;
glGenTextures ( 1, &tex2 );
glActiveTexture( GL_TEXTURE0 + 1);
glBindTexture ( GL_TEXTURE_BUFFER, tex2 );
glTexBuffer ( GL_TEXTURE_BUFFER, GL_R32I, buffer2 );
}
int main ( int argc, char **argv )
{
// Init GL context
glutInit ( &argc, argv ) ;
glutInitDisplayMode ( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE ) ;
glutInitWindowSize ( 500, 500 ) ;
glutCreateWindow ( "Shader Test" ) ;
glutDisplayFunc ( display ) ;
glutKeyboardFunc ( keybd ) ;
glutReshapeFunc ( reshape ) ;
// Create buffer object and its texture buffer object wrapper
init();
// Load and compile shaders
printf( "Compiling vertex shader...\n" );
GLuint vsHandle = compileShader ( Vertex_src, GL_VERTEX_SHADER );
printf( "Compiling fragment shader...\n" );
GLuint fsHandle = compileShader ( (readFile("mytest.glsl")).c_str(), GL_FRAGMENT_SHADER);
// Link shaders
printf( "Linking...\n" );
GLuint handle = linkShaders ( vsHandle, fsHandle ) ;
// Activate shader
glUseProgram( handle ) ;
// Populate uniform
// (buffer texture will be on TEXUNIT 0)
glUniform1i( glGetUniformLocation( handle, "tex" ), 0 );
// (buffer2 texture will be on TEXUNIT 1)
glUniform1i( glGetUniformLocation( handle, "tex2" ), 1 );
// Draw with shader
glutMainLoop () ;
return 0 ;
}
Fragment Shader: mytest.glsl
#version 130
#extension GL_EXT_gpu_shader4: enable
uniform isamplerBuffer tex;
uniform isamplerBuffer tex2;
void main(void)
{
int width = 500;
// Get the current screen index we are going to work on.
// (Used for TEST B and TEST C below.)
int index = int((gl_FragCoord.y * float(width)) + gl_FragCoord.x);
// TEST A: This works as expected.
/*if (gl_FragCoord.x < 250.0 && gl_FragCoord.y < 250.0) {
gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
}
else {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}*/
// TEST B: Use buffer textures to get the value of the arrays at
// the index computed above. This does not work as expected.
int x_i = int(texelFetch(tex, index).r);
int y_i = int(texelFetch(tex2, index).r);
if (x_i < 250 && y_i < 250) {
gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
}
else {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
// TEST C: Get the x, y screen space coordinates based on the index
// computed above. This does not work as expected.
/*int x_i = index % 500;
int y_i = index / 500;
if (x_i < 250 && y_i < 250) {
gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);
}
else {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}*/
}
Result of Test A
Test A http://www.shilpigupta.com/stack/TestA.png
Result of Test B and Test C
(Also notice the green line artifact at the top right of the image.)
Test B and Test C http://www.shilpigupta.com/stack/TestB.png
The mistake is how you calculate the index:
int index = int((gl_FragCoord.y * float(width)) + gl_FragCoord.x);
This code will only work if the fractional part of gl_FragCoord is zero. Note that OpenGL's window space is defined in such a way that pixel centers lie at half-integer positions ("at comma 5"). Without mutlisampling or other fancy settings, the fragment shader will be invoked exactly for pixel centers, so all of your gl_FragCoord values are at .5, which basically results in the shift in 0.5 * width pixels you are observing. (In the case B and C, the green area actually isn't a square, because one line in height is missing at the top, because you already start the bottom line at x_i=250).
The correct approach is
int index = int(gl_FragCoord.y) * width + int(gl_FragCoord.x);