I am working with textures in OpenGL and have came across a strange issue. Sometimes an image that's loaded in is pushed over to the right slightly. I will supply code and screen shots below.
#include <gl/glew.h>
#include <gl/glut.h>
#include <windows.h>
#include <stdio.h>
#include <SOIL.h>
const int WINDOW_WIDTH = 1024;
const int WINDOW_HEIGHT = 512;
GLuint Tex;
GLuint Tex2;
GLuint LoadTexture( const char * filename, int w, int h )
{
GLuint texture;
int width, height;
unsigned char * data;
FILE * file;
file = fopen( filename, "rb" );
if ( file == NULL ) return 0;
width = w;
height = h;
data = (unsigned char *)malloc( width * height * 3);
fread( data, width * height * 3, 1, file );
fclose( file );
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_NEAREST );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,GL_NEAREST );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,GL_REPEAT );
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,GL_RGB, GL_UNSIGNED_BYTE, data );
free( data );
return texture;
}
void Reshape( int width, int height )
{
glViewport( 0, 0, (GLsizei)width, (GLsizei)height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( 0.0f, WINDOW_WIDTH, 0.0f, WINDOW_HEIGHT, 1.0f, 100.0f );
glMatrixMode( GL_MODELVIEW );
}
void lightInit( void )
{
GLfloat lightWhite[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat lightBlack[] = { 0.0f, 0.0f, 0.0f, 1.0f };
GLfloat lightPos[] = { 0.0f, 0.0f, 0.0f, 1.0f };
glMaterialfv( GL_FRONT, GL_AMBIENT_AND_DIFFUSE, lightWhite );
glMaterialf( GL_FRONT, GL_SHININESS, 30 );
glLightfv( GL_LIGHT0, GL_AMBIENT, lightBlack );
glLightfv( GL_LIGHT0, GL_SPECULAR, lightWhite );
glLightfv( GL_LIGHT0, GL_DIFFUSE, lightWhite );
glLightfv( GL_LIGHT0, GL_POSITION, lightPos );
glEnable( GL_LIGHTING );
glEnable( GL_LIGHT0 );
glEnable( GL_COLOR_MATERIAL );
glEnable( GL_DEPTH_TEST );
}
void drawTexObj()
{
Tex = LoadTexture( "texture2.bmp", 1024, 512 );
if( Tex == 0 )
{
exit(0);
}
glEnable( GL_TEXTURE_2D );
glPushAttrib( GL_CURRENT_BIT );
glBegin( GL_QUADS );
glTexCoord2d( 0.0f, 0.0f );
glVertex2f( 0.0f, 0.0f );
glTexCoord2d( 0.0f, 1.0f );
glVertex2f( 0.0f, 512.0f );
glTexCoord2d( 1.0f, 1.0f );
glVertex2f( 1024.0f, 512.0f );
glTexCoord2d( 1.0f, 0.0f );
glVertex2f( 1024.0f, 0.0f );
glEnd();
glPopAttrib();
glDisable( GL_TEXTURE_2D );
glDeleteTextures( (GLsizei)1, &Tex );
}
void drawTexObj2()
{
Tex2 = LoadTexture( "texture.bmp", 1024, 512 );
if( Tex2 == 0 )
{
exit(0);
}
glEnable( GL_TEXTURE_2D );
glBegin( GL_QUADS );
glTexCoord2d( 0.0f, 0.0f );
glVertex2f( 0.0f, 0.0f );
glTexCoord2d( 0.0f, 1.0f );
glVertex2f( 0.0f, 256.0f );
glTexCoord2d( 1.0f, 1.0f );
glVertex2f( 512.0f, 256.0f );
glTexCoord2d( 1.0f, 0.0f );
glVertex2f( 512.0f, 0.0f );
glEnd();
glDisable( GL_TEXTURE_2D );
glDeleteTextures( (GLsizei)1, &Tex2 );
}
void Display()
{
glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glLoadIdentity();
glTranslatef( 0.0f, 0.0f, -1.0f );
drawTexObj();
drawTexObj2();
glutSwapBuffers();
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH );
glEnable( GL_DEPTH );
glutInitWindowPosition( 200, 100 );
glutInitWindowSize( 1024, 512 );
glutCreateWindow( "Texturing :D!" );
//lightInit();
glutDisplayFunc( Display );
glutIdleFunc( Display );
glutReshapeFunc( Reshape );
glutMainLoop();
}
This looks like an issue with reading the file in the first place. BMP files are not simple neat arrays of pixel bytes, so you can't just read in width*height*3 bytes. You will see the image data in there, (assuming 24 bpp storage), but there is also header information which will push the pixel data over on the display. I'm surprised that the 2nd bitmap looks OK, although this might be coincidence that the header matches the image width.
A better solution would be to use the Gdi to load the images...
GdiplusStartupInput lstartup_input;
GdiplusStartupOutput lstartup_output;
ULONG_PTR ltoken;
GdiplusStartup(<oken, &lstartup_input, &lstartup_output);
Bitmap *lbitmap;
lbitmap = new Bitmap(wszPath);
GdiplusShutdown(ltoken);
RGBQUAD *pBits = (RGBQUAD *) malloc(lbitmap->GetWidth() * lbitmap->GetHeight() * 4 * sizeof(BYTE));
lbitmapdata.Scan0 = pBits;
lbitmapdata.Width = lbitmap->GetWidth();
lbitmapdata.Height = lbitmap->GetHeight();
lbitmapdata.PixelFormat = PixelFormat32bppARGB;
lbitmapdata.Stride = lbitmap->GetWidth()*4;
Rect lrect(0,0,lbitmap->GetWidth(), lbitmap->GetHeight());
st = lbitmap->LockBits(&lrect, ImageLockModeUserInputBuf | ImageLockModeRead,
PixelFormat32bppARGB, &lbitmapdata);
ASSERT(st == Ok);
st = lbitmap->UnlockBits(&lbitmapdata); // Unlock straightaway, because we just want to extract the pixel data
ASSERT(st == Ok);
This snipped uses 4 bytes per-pixel, as I use the alpha channel, but from there you should be able to convert it as you need it. Here's a code snippet to convert the BGRA to RGB. (You could change the pixel format for UnlockBits to PixelFormat24bppRGB, but you might still need to swap the colours about - try it and see.)
BYTE *rgbBits = (malloc lbitmap->GetHeight() * lbitmap->GetWidth() * 3);
BYTE *rgbPtr = rgbBits;
pPixel = (RGBQUAD *)m_pBits;
for (li = 0; li < lbitmap->GetHeight() * lbitmap->GetWidth(); li++)
{
*(rgbPtr++) = pPixel->rgbRed;
*(rgbPtr++) = pPixel->rgbGreen;
*(rgbPtr++) = pPixel->rgbBlue;
pPixel++;
}
(Note that I just pulled this code out of my project, so it might need some cleaning up. Let me know.)
Related
I want to create a 1D texture with OpenGL's (old) fixed function pipeline, which interpolated through three colors.
After looking online: glTexImage1D is commonly referred to. I cannot find any good simple sample codes for this, and I wouldn't know how to return a (RGB) value from this.
Does OpenGL (fixed function) have any methods for creating a 1D Texture, and returning an RGB value from this?
Yup, glTexImage1D() + GL_TEXTURE_1D:
#include <GL/glew.h>
#include <GL/glut.h>
GLuint tex = 0;
void display()
{
glClear( GL_COLOR_BUFFER_BIT );
glEnable( GL_TEXTURE_1D );
glBindTexture( GL_TEXTURE_1D, tex );
glBegin(GL_TRIANGLES);
glTexCoord1f( 0.0f );
glVertex2f( -0.5f, -0.5f );
glTexCoord1f( 0.5f );
glVertex2f( 0.5f, -0.5f );
glTexCoord1f( 1.0f );
glVertex2f( 0.0f, 0.5f );
glEnd();
glutSwapBuffers();
}
int main( int argc, char** argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
glutInitWindowSize( 400, 400 );
glutCreateWindow( "GLUT" );
glewInit();
glGenTextures( 1, &tex );
glBindTexture( GL_TEXTURE_1D, tex );
unsigned char pixels[] =
{
255, 0, 0, 255,
0, 255, 0, 255,
0, 0, 255, 255,
};
glTexImage1D( GL_TEXTURE_1D, 0, GL_RGBA, 3, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels );
glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL );
glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glutDisplayFunc( display );
glutMainLoop();
return 0;
}
I've loaded a texture's ID into the tex variable, but when I bind the texture with this ID just before drawing a QUAD (seen in code below inside the renderScene function surrounded by the xxxxxxxxx... comments), no texture is getting applied to the QUAD; it remains colorless. No error messages either.
I've included all the texture-related things I've written in my program.
What else do I need to add/change?
#include<windows.h>
#include <GL/glut.h>
#include<iostream>
#include <stdlib.h>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
// (...)
GLuint loadBMP_custom(const char * imagepath);
GLuint tex = loadBMP_custom("texture.bmp");
GLuint loadBMP_custom( const char * imagepath )
{
GLuint texture;
int width, height;
unsigned char * data;
FILE * file;
file = fopen( imagepath, "rb" );
if ( file == NULL ) return 0;
width = 256;
height = 256;
data = (unsigned char *)malloc( width * height * 3 );
fread( data, width * height * 3, 1, file );
fclose( file );
for(int i = 0; i < width * height ; ++i)
{
int index = i*3;
unsigned char B,R;
B = data[index];
R = data[index+2];
data[index] = R;
data[index+2] = B;
}
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST );
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 );
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,GL_RGB, GL_UNSIGNED_BYTE, data );
free( data );
return texture;
}
// (...)
void renderScene(void)
{
glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Reset transformations
glLoadIdentity();
// Set the camera
gluLookAt( posX, 1.0f, posZ,
posX+vlx, posY+vly, posZ+vlz,
0.0f, 1.0f, 0.0f);
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
glBindTexture(GL_TEXTURE_2D, tex);
glBegin(GL_QUADS);
glTexCoord2f (0.0, 0.0);
glVertex3f(-100.0f, -0.02f, -100.0f);
glTexCoord2f (0.0, 1.0);
glVertex3f(-100.0f, -0.02f, 100.0f);
glTexCoord2f (1.0, 1.0);
glVertex3f( 100.0f, -0.02f, 100.0f);
glTexCoord2f (1.0, 0.0);
glVertex3f( 100.0f, -0.02f, -100.0f);
glEnd();
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// [Also display 3D blocks in space besides the above QUAD, which serves as ground]
glFlush();
glutSwapBuffers();
}
//(...)
int main(int argc, char **argv)
{
// (...)
glEnable (GL_TEXTURE_2D) ;
glutMainLoop();
return 1;
}
As mentioned in the comments, your method to load a BMP file is incorrect: even if you know how big the image is (256x256), you would still need to skip ahead to the pixel data part (usually 54 bytes, which is the usual size of the header).
So now you could write your own importer by reading the official spec over here: https://en.wikipedia.org/wiki/BMP_file_format
...Or also find many implementations on the web such as the one mentioned in this question: C++: Read bitmap wrong
Unless you find some easy-to-plug header(s)-only library, I would personally go against using a library to specifically deal with BMP files since it introduces extra dependencies for something quite easy to roll on your own (and at the same time, learn how to implement a simple file loader).
I was trying to make simple texturing, but heres an error appeared:
error: 'my_texture' does not name a type
Here there place where it appears(right after LoadTexture method):
GLuint my_texture;
my_texture = LoadTexture( "grass.bmp" );
Here's my code. Whats wrong?
#include <iostream>
#include <GL/gl.h>
#include <GL/glut.h>
#include <stdio.h> /* printf, scanf, NULL */
#include <stdlib.h> /* malloc, free, rand */
using namespace std;
float _angle = 0.5f;
GLuint LoadTexture( const char * filename )
{
GLuint texture;
int width, height;
unsigned char * data;
FILE * file;
file = fopen( filename, "rb" );
if ( file == NULL ) return 0;
width = 1024;
height = 512;
data = (unsigned char *)malloc( width * height * 3 );
fread( data, width * height * 3, 1, file );
fclose( file );
for(int i = 0; i < width * height ; ++i)
{
int index = i*3;
unsigned char B,R;
B = data[index];
R = data[index+2];
data[index] = R;
data[index+2] = B;
}
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,GL_MODULATE );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST );
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 );
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,GL_RGB, GL_UNSIGNED_BYTE, data );
free( data );
return texture;
}
GLuint my_texture;
my_texture = LoadTexture( "grass.bmp" );
void render(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity ();
gluPerspective(90.0, 640.0f/480.0f, 0.1, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity ();
gluLookAt(1, 1, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
glPushMatrix();
glRotatef(_angle, 0.0f,0.0f,1.0f);
glColor3f(0.0f,0.7f,0.0f);
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 0.0 );
glVertex3f( -0.5, 0.5 , 0 );
glVertex3f( 0.5 , 0.5, 0 );
glVertex3f( 0.5, -0.5, 0 );
glVertex3f( -0.5, -0.5, 0 );
glEnd();
glPopMatrix();
_angle +=0.03f;
// check OpenGL error
GLenum err;
while ((err = glGetError()) != GL_NO_ERROR) {
cerr << "OpenGL error: " << err << endl;
}
glutSwapBuffers();
glutPostRedisplay();
}
void init(){
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(640, 480);
glutCreateWindow("test");
glClearColor(0.2,0.2,0.2,0.0);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glutDisplayFunc(render);
glutMainLoop();
}
int main(int argc, char * argv[]) {
glutInit(&argc, argv);
init();
return 0;
}
These two lines appear outside of a function. You may only declare variables there, you can not put statements directly in this scope. Try:
GLuint my_texture = LoadTexture( "grass.bmp" );
This code initially uses one texture. I duplicated some functions to use two textures. There doesn't seem to be any errors but when I run I only see the black command window for a bit then it closes. Is there any additional line that I should add?
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "support.h"
using namespace std;
/* GLUT callback Handlers */
MYPOINT*ptsW,*ptsR;
MYFACE *faceW,*faceR;
GLuint *images;
GLubyte *image;
GLuint texture;
void loadImage(int n, int m, char *fName);
GLuint LoadTexture(int width, int height);
int n=200,m=200;
void constructBox();
void constructTri();
void init();
void showPictureW();
void showPictureR();
float rX=0, rY=0, rZ=0;
float tX=0, tY=0, tZ=-3.5;
float nr = -5.0;
float fr = -4.0;
float tpx = 1.0, tpy = 1.0;
float btx = -1.0, bty = -1.0;
float dZ =-2.0;
void init(){
constructBox();
loadImage(n,m,"wall.ppm");
constructTri();
loadImage(n,m,"roof.ppm");
}
void showPictureW(){
/* clear all pixels */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
texture = LoadTexture(n,m);
glEnable( GL_TEXTURE_2D );
glBindTexture( GL_TEXTURE_2D, texture );
glColor3d(1,1,1);
//face 1
glBegin( GL_POLYGON );
glTexCoord2d(1.0,1.0); glVertex3d(-1.0,1.0,-2.0);
glTexCoord2d(1.0,0.0); glVertex3d(-1,-1.0,-2.0); //1 -1
glTexCoord2d(0.0,0.0); glVertex3d(1.0,-1.0,-2.0); //-1 -1
glEnd();
//face 2
glBegin( GL_POLYGON );
glTexCoord2d(0.0,0.0); glVertex3d(1.0,-1.0,-2.0);
glTexCoord2d(0.0,1.0); glVertex3d(1.0,1.0,-2.0);
glTexCoord2d(1.0,1.0); glVertex3d(-1.0,1.0,-2.0); //1 -1
glEnd();
}
void showPictureR(){
/* clear all pixels */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
texture = LoadTexture(n,m);
glEnable( GL_TEXTURE_2D );
glBindTexture( GL_TEXTURE_2D, texture );
glColor3d(1,1,1);
//face 1
glBegin( GL_POLYGON );
glTexCoord2d(1.0,1.0); glVertex3d(-1.0,1.0,-2.0);
glTexCoord2d(1.0,0.0); glVertex3d(-1,-1.0,-2.0); //1 -1
glTexCoord2d(0.0,0.0); glVertex3d(1.0,-1.0,-2.0); //-1 -1
glEnd();
//face 2
glBegin( GL_POLYGON );
glTexCoord2d(0.0,0.0); glVertex3d(1.0,-1.0,0.0);
glTexCoord2d(0.0,1.0); glVertex3d(1.0,3.0,-2.0);
glTexCoord2d(1.0,1.0); glVertex3d(-1.0,3.0,-2.0); //1 -1
glEnd();
}
static void
resize(int width, int height)
{
const float ar = (float) width / (float) height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity() ;
init();
}
static void
display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(1,0,0);
glPushMatrix();
glTranslated(0,0,0);
glRotated(rX,0,0,1);
glRotated(rY,0,1,0);
glRotated(rZ,1,0,0);
showPictureW();
glPopMatrix();
glPushMatrix();
glTranslated(0,0,0);
glRotated(rX,0,0,1);
glRotated(rY,1,1,0);
glRotated(rZ,1,0,0);
showPictureR();
glPopMatrix();
glutSwapBuffers();
}
void constructBox()
{
int nPtsW = 8;
int nFaceW = 12;
ptsW = new MYPOINT[nPtsW];
faceW = new MYFACE[nFaceW];
getPoints(ptsW,"myVertWall.txt");
getFace(faceW,"myFaceWall.txt");
}
void constructTri()
{
int nPtsR = 6;
int nFaceR = 8;
ptsR = new MYPOINT[nPtsR];
faceR = new MYFACE[nFaceR];
getPoints(ptsR,"myVertRoof.txt");
getFace(faceR,"myFaceRoof.txt");
}
static void
key(unsigned char key, int x, int y)
{
switch (key)
{
case 27 :
case 'q':
exit(0);
break;
case '+':
break;
case 'x':
rX= rX + 0.5;
break;
case 'X':
rX= rX - 0.5;
break;
case 'y':
rY= rY + 0.5;
break;
case 'Y':
rY= rY - 0.5;
break;
case 'z':
rZ= rZ + 0.5;
break;
case 'Z':
rZ= rZ - 0.5;
break;
case 'd':
dZ = dZ+100.0;// horizontal movement to the left
printf("Nilai dZ=%.2f\n",dZ);
break;
case 'D':
dZ = dZ-100.0;// horizontal movement to the right
printf("Nilai dZ=%.2f\n",dZ);
break;
}
glutPostRedisplay();
}
static void
idle(void)
{
glutPostRedisplay();
}
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
/* Program entry point */
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(640,480);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("FreeGLUT Shapes");
glutReshapeFunc(resize);
glutDisplayFunc(display);
glutKeyboardFunc(key);
glutIdleFunc(idle);
glClearColor(1,1,1,1);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
glutMainLoop();
return EXIT_SUCCESS;
}
GLuint LoadTexture(int width, int height)
{
image = new BYTE[width*height*3*sizeof(BYTE)];
int nm = width*height;
for(int i=0;i<nm*3;i++)//copy each value 3 times
{
image[i] = (GLubyte)images[i];
image[i] = (GLubyte)images[i];
image[i] = (GLubyte)images[i];
}
bool wrap = true;
glGenTextures( 1, &texture );
// select our current texture
glBindTexture( GL_TEXTURE_2D, texture );
// select modulate to mix texture with color for shading
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
// when texture area is small, bilinear filter the closest mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
// when texture area is large, bilinear filter the first mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
// if wrap is true, the texture wraps over at the edges (repeat)
// ... false, the texture ends at the edges (clamp)
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap ? GL_REPEAT : GL_CLAMP );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,wrap ? GL_REPEAT : GL_CLAMP );
// build our texture mipmaps
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,
GL_RGB, GL_UNSIGNED_BYTE, image );
// free buffer
//free( data );
return texture;
}
void loadImage(int n, int m, char *fName)
{
FILE *fd;
int k, nm;
int i;
char bc[71];
float s;
unsigned int red, green, blue;
char c;
fd = fopen(fName,"r");
fscanf(fd,"%[^\n]",bc); // reads data from stream
printf("Nilai %s \n\n",bc);
if(bc[0]!='P'|| bc[1]!='3')
{
printf("%s Not a PPM file\n",bc);
exit(0);
}
printf("%s is a PPM file\n",bc);
fscanf(fd,"%s",bc);
printf("line 1 %s \n",bc);
fscanf(fd,"%s",bc);
printf("line 2 %s \n",bc);
fscanf(fd,"%s",bc);
printf("line 3 %s \n",bc);
fscanf(fd,"%s",bc);
printf("line 4 %s \n",bc);
fscanf(fd,"%c",&c);
ungetc(c,fd);
fscanf(fd,"%d %d %d", &n,&m,&k);
// printf("%d rows %d columns max value = %d\n",n,m,k);
nm = n*m;
images = new GLuint[3*sizeof(GLuint)*nm];
//s = 255./k;
for (i=0;i<nm;i++)
{
fscanf(fd,"%u %u %u", &red, &green, &blue);
images[3*nm-3*i-3] = red;
images[3*nm-3*i-2] = green;
images[3*nm-3*i-1] = blue;
}
int totSize = 3*nm;
int tot=0;
for(i=0;i<nm;i++)
{
// fprintf(stderr,"(%d,%d,%d) ", images[3*nm-3*i-3], images[3*nm-3*i-2], images[3*nm-3*i-1]);
tot++;
}
// printf("%d \n",tot);
}
The coordinates are still all over. I'm just trying if the two textures come out okay.
Try this:
#include <GL/glut.h>
#include <vector>
float rX=0, rY=0, rZ=0;
float dZ =-2.0;
static void key(unsigned char key, int x, int y)
{
switch (key)
{
case 27 :
case 'q':
exit(0);
break;
case '+':
break;
case 'x':
rX= rX + 0.5;
break;
case 'X':
rX= rX - 0.5;
break;
case 'y':
rY= rY + 0.5;
break;
case 'Y':
rY= rY - 0.5;
break;
case 'z':
rZ= rZ + 0.5;
break;
case 'Z':
rZ= rZ - 0.5;
break;
case 'd':
dZ = dZ+100.0;// horizontal movement to the left
break;
case 'D':
dZ = dZ-100.0;// horizontal movement to the right
break;
}
}
void showPictureW()
{
//face 1
glBegin( GL_TRIANGLES );
glTexCoord2d(1.0,1.0); glVertex3d(-1.0,1.0,-2.0);
glTexCoord2d(1.0,0.0); glVertex3d(-1,-1.0,-2.0); //1 -1
glTexCoord2d(0.0,0.0); glVertex3d(1.0,-1.0,-2.0); //-1 -1
//face 2
glTexCoord2d(0.0,0.0); glVertex3d(1.0,-1.0,-2.0);
glTexCoord2d(0.0,1.0); glVertex3d(1.0,1.0,-2.0);
glTexCoord2d(1.0,1.0); glVertex3d(-1.0,1.0,-2.0); //1 -1
glEnd();
}
void showPictureR()
{
//face 1
glBegin( GL_TRIANGLES );
glTexCoord2d(1.0,1.0); glVertex3d(-1.0,1.0,-2.0);
glTexCoord2d(1.0,0.0); glVertex3d(-1,-1.0,-2.0); //1 -1
glTexCoord2d(0.0,0.0); glVertex3d(1.0,-1.0,-2.0); //-1 -1
//face 2
glTexCoord2d(0.0,0.0); glVertex3d(1.0,-1.0,0.0);
glTexCoord2d(0.0,1.0); glVertex3d(1.0,3.0,-2.0);
glTexCoord2d(1.0,1.0); glVertex3d(-1.0,3.0,-2.0); //1 -1
glEnd();
}
GLuint texture1 = 0;
GLuint texture2 = 0;
static void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double w = glutGet( GLUT_WINDOW_WIDTH );
double h = glutGet( GLUT_WINDOW_HEIGHT );
double ar = w / h;
glFrustum(-ar, ar, -1.0, 1.0, 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity() ;
glEnable( GL_TEXTURE_2D );
glColor3ub(255,255,255);
glBindTexture( GL_TEXTURE_2D, texture1 );
glPushMatrix();
glTranslated(0,0,0);
glRotated(rX,0,0,1);
glRotated(rY,0,1,0);
glRotated(rZ,1,0,0);
showPictureW();
glPopMatrix();
glBindTexture( GL_TEXTURE_2D, texture2 );
glPushMatrix();
glTranslated(0,0,0);
glRotated(rX,0,0,1);
glRotated(rY,1,1,0);
glRotated(rZ,1,0,0);
showPictureR();
glPopMatrix();
glutSwapBuffers();
}
static void idle(void)
{
glutPostRedisplay();
}
GLuint LoadTexture(int width, int height, unsigned int component )
{
std::vector< unsigned char > image( width*height*3 );
for(int i=0;i< width*height*3; i += 3)
{
image[i+0] = 0;
image[i+1] = 0;
image[i+2] = 0;
image[i+component] = rand() % 255;
}
bool wrap = true;
GLuint texture = 0;
glGenTextures( 1, &texture );
// select our current texture
glBindTexture( GL_TEXTURE_2D, texture );
// select modulate to mix texture with color for shading
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
// when texture area is small, bilinear filter the closest mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
// when texture area is large, bilinear filter the first mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
// if wrap is true, the texture wraps over at the edges (repeat)
// ... false, the texture ends at the edges (clamp)
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap ? GL_REPEAT : GL_CLAMP );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,wrap ? GL_REPEAT : GL_CLAMP );
// build our texture mipmaps
gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGB, width, height, GL_RGB, GL_UNSIGNED_BYTE, &image[0] );
return texture;
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(640,480);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("FreeGLUT Shapes");
glutDisplayFunc(display);
glutKeyboardFunc(key);
glutIdleFunc(idle);
glClearColor(1,1,1,1);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
srand( 0 );
texture1 = LoadTexture( 256, 256, 0 );
texture2 = LoadTexture( 256, 256, 1 );
glutMainLoop();
return EXIT_SUCCESS;
}
I have an assignment to do, but i can't seem to trully comprehend it.
The assignment is as follows : Adding a texture to background (solar system), adding texture to 2 objects (drawn shapes) and adding an animation where the two objects have to bounce from eachother & from far walls (as in end of screen).
I have managed to do everything except the animation.
How can I do this kind of animation?
p.s. animation in there is the best i could come up with.
#include <gl/glut.h>
#include <gl/gl.h >
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
float x;
float y;
unsigned char *imageData;
int imageRows, imageCols;
extern void loadBMP(char *);
char cotton1[] = "cotton1.bmp";
char cotton2[] = "cotton2.bmp";
char fons[] = "solar.bmp";
GLuint texture[3];
float cube[1], Vcube[1];
/* GLUT callback Handlers */
void init()
{
cube[0]=0;
Vcube[0]=0.01;
cube[1]=0;
Vcube[1]=0.01;
glShadeModel(GL_SMOOTH);
glGenTextures( 3, &texture[0] );
loadBMP(cotton1);
glBindTexture( GL_TEXTURE_2D, texture[0] );
glTexImage2D(GL_TEXTURE_2D, 0, 3, imageCols, imageRows,
0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
loadBMP(cotton2);
glBindTexture( GL_TEXTURE_2D, texture[1] );
glTexImage2D(GL_TEXTURE_2D, 0, 3, imageCols, imageRows,
0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
loadBMP(fons);
glBindTexture( GL_TEXTURE_2D, texture[2] );
glTexImage2D(GL_TEXTURE_2D, 0, 3, imageCols, imageRows,
0, GL_RGB, GL_UNSIGNED_BYTE, imageData);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
}
static void
resize(int width, int height)
{
const float ar = (float) width / (float) height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity() ;
}
static void
idle(void)
{
glutPostRedisplay();
}
void animation()
{
cube[1]+=Vcube[1];
if (cube[1]<0.1)
{ Vcube[1]+=Vcube[1]; }
if (cube[1]>0.095)
{ Vcube[1]=-0.01; }
if (cube[1]<0)
{ Vcube[1]=+0.01; }
glTranslatef(cube[1],0,0);
Sleep(100);
glutPostRedisplay();
}
void animation2()
{
cube[0]+=Vcube[0];
if (cube[0]<(-0.1))
{ Vcube[0]-=0.01; }
if (cube[0]>0)
{ Vcube[0]-=0.01; }
if (cube[0]<0.1)
{ Vcube[0]+=0.01; }
glTranslatef(cube[0],0,0);
Sleep(100);
glutPostRedisplay();
}
void display() {
glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT);
//Background
glLoadIdentity();
glBindTexture( GL_TEXTURE_2D, texture[2]);
glEnable( GL_TEXTURE_2D );
glPushMatrix();
glBegin( GL_QUADS );
glTexCoord2f(1.0,1.0); glVertex2f(-1.0,1.0);
glTexCoord2f(0.0,1.0); glVertex2f(1.0,1.0);
glTexCoord2f(0.0,0.0); glVertex2f(1.0,-1.0);
glTexCoord2f(1.0,0.0); glVertex2f(-1.0,-1.0);
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
animation();
//TEXTURE 1
glBindTexture( GL_TEXTURE_2D, texture[0]);
glEnable( GL_TEXTURE_2D );
glPushMatrix();
glBegin( GL_TRIANGLE_FAN );
glTexCoord2f(0.5f, 0.5f); glVertex2f( 0.5f, 0.0f); //center
glTexCoord2f(1.0f, 0.5f); glVertex2f( 0.8f+x, 0.0f); //right
glTexCoord2f(0.75f, 1.0f); glVertex2f( 0.55f+x, 0.3f+x); //top right
glTexCoord2f(0.25f, 1.0f); glVertex2f( 0.35f-x, 0.3f+x); //Top left
glTexCoord2f(0.0f, 0.5f); glVertex2f( 0.25f-x, 0.0f); //left
glTexCoord2f(0.25f, 0.0f); glVertex2f( 0.45f-x,-0.3f-x); //bottom left
glTexCoord2f(0.75f, 0.0f); glVertex2f( 0.7f+x, -0.2f-x); //bottom right
glTexCoord2f(1.0f, 0.5f); glVertex2f( 0.8f+x, 0.0f); //right
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
//TEXTURE 2
animation2();
glBindTexture( GL_TEXTURE_2D, texture[1]);
glEnable( GL_TEXTURE_2D );
glPushMatrix();
glBegin( GL_TRIANGLE_FAN );
glTexCoord2f(0.5f, 0.5f); glVertex2f( -0.5f, 0.0f); //center
glTexCoord2f(1.0f, 0.5f); glVertex2f( -0.2f+y, 0.0f); //right
glTexCoord2f(0.75f, 1.0f); glVertex2f( -0.4f+y, 0.2f+y); //top right
glTexCoord2f(0.25f, 1.0f); glVertex2f( -0.7f-y, 0.1f+y); //Top left
glTexCoord2f(0.0f, 0.5f); glVertex2f( -0.8f-y, 0.0f); //left
glTexCoord2f(0.25f, 0.0f); glVertex2f( -0.7f-y, -0.1f-y); //bottom left
glTexCoord2f(0.75f, 0.0f); glVertex2f( -0.3f+y, -0.2f-y); //bottom right
glTexCoord2f(1.0f, 0.5f); glVertex2f( -0.2f+y, 0.0f); //right
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glutSwapBuffers();
glFlush();
}
static void
key(unsigned char key, int a, int b)
{
switch (key)
{
case 27 :
case 'q':
exit(0);
break;
case '+':
if ((x+0.01)<0.98)
x=x+0.01;
if ((y+0.01)<0.98)
y=y+0.01;
break;
case '-':
if ((x-0.1)>(-0.15))
x=x-0.01;
if ((y-0.1)>(-0.10))
y=y-0.01;
break;
case 'o':
if ((x+0.01)<0.98)
x=x+0.01;
break;
case 'p':
if ((x-0.1)>(-0.15))
x=x-0.01;
break;
case '[':
if ((y+0.01)<0.98)
y=y+0.01;
break;
case ']':
if ((y-0.1)>(-0.10))
y=y-0.01;
break;
}
glutPostRedisplay();
}
int main(int argc, char *argv[]) {
glutInit(&argc, argv);
glutInitWindowSize(640, 640);
glutInitWindowPosition(50, 50);
glutCreateWindow("Assignment number 3");
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutReshapeFunc(resize);
glutDisplayFunc(display);
glutKeyboardFunc(key);
glutIdleFunc(idle);
glClearColor(1.0, 1.0, 1.0, 1.0);
init();
glutMainLoop();
return EXIT_SUCCESS;
}
Problem 1: You mistake OpenGL for a scene graph. Take your animation1 function for example:
void animation2(
)
{
cube[0] += Vcube[0];
if( cube[0] < ( -0.1 ) ) {
Vcube[0] -= 0.01;
}
if( cube[0] > 0 ) {
Vcube[0] -= 0.01;
}
if( cube[0] < 0.1 ) {
Vcube[0] += 0.01;
}
glTranslatef( cube[0], 0, 0 );
Sleep( 100 );
glutPostRedisplay( );
}
That glTranslatef there at the end will just trash around on whatever matrix is currently active in the OpenGL context. That's not how to do it.
Next problem: You're calling the animation functions from the drawing code. At the point of drawing all the scene state should be determined. Also, calling that animation function will sleep in your display function. That's not how to do it.
Okay, what to do: First put all the animation progressor functions into the idle loop. Don't sleep, instead measure the time between animation iterations and advance the animation accordingly. Don't call glutPostRedisplay in the animation functions. At the end of the idle handler yes, but not in the animators. In the drawing code use the evaluated animation state to place objects accordingly. Use the matrix stack (glPushMatrix, glPopMatrix) to keep things nicely separated.
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* for gettimeofday */
#include <sys/time.h>
/* In general, littering your program with global variables should be avoided.
* I admit, that sometimes even I don't adhere to this rule, and especially
* using GLUT it takes to jump several very arcane hoops to avoid it.
* So in this case, yes, having global variables is in order.
*
* The principle idea of global variables is to put data into them, that is
* valid and the same for the whole of the program. More importantly they
* must not be used to pass around data.
*
* It's also a good idea to make those variables static, so that they are
* contained withing this compilation unit.
*/
static float x;
static float y;
/* This is not how globals should be used. They're used to pass data around between
* functions. DON'T DO THAT!
*
* Also this misses the extern keyword. Unless the compilation unit loading the
* bmp files declares those being extern, hence relying on another compilation unit
* to expose them like this, this code is likely to break.
unsigned char *imageData;
int imageRows, imageCols;
extern void loadBMP(char *);
* BTW: You don't need the extern keyword here.
* Instead have a nice little function that loads a BMP file and puts it into a
* newly allocated texture object.
*/
GLuint loadBmpToTexture(char const * const filename)
{
/* Implementation of this left as an exercise to the reader */
return 0;
}
static double ftime(void)
{
/* Now this is a bit complicated: There's no portable high resolution
* timer function. On Linux and Unices (hence also MacOS X) you have
* gettimeofday, on Windows there are the High Performance Counters.
* ... Totally annoying.
* Look here for a comparison:
* http://www.songho.ca/misc/timer/timer.html
*
* Since I'm on a Linux box this is using gettimeofday
*/
struct timeval t;
gettimeofday(&t, NULL);
return 1.0*t.tv_sec + 1e-6*t.tv_usec;
}
/* In this variable we store the time of the last iteration of the animation
* loop to determine the time to time difference for the next one. */
static double last_T;
/* Actually those should be of type char const * const
* This is one of the finer details of C. The arrays like you've declared them
* here are mutable, but of constant size.
* However you normally don't want string constant be like this. The preferred
* modus operandi is to have the string constants in read only memory and pointers
* to them. Like this:
*/
char const * const cotton1 = "cotton1.bmp";
char const * const cotton2 = "cotton2.bmp";
char const * const fons = "solar.bmp";
/* Okay, now consider what would happen if you had several objects, not just two or
* three? How would you keep track of all those indices? Really, that's bad style.
* If you've data belonging together, like state of an object, put it into a struct
* and then also use useful variable names.
*/
GLuint texture_background;
typedef struct s_Cube {
float x, V_x;
GLuint texture;
} Cube;
/* also we can statically initialize here */
Cube cube[2] = {
{-0.05, 0.01, 0},
{0.05, -0.02, 0}
};
/* GLUT callback Handlers */
static void init(void)
{
/* loadBmpToTexture is defined to return 0 in case of failure
* which is also the OpenGL default texture object, so this
* fails safely. */
texture_background = loadBmpToTexture(fons);
cube[0].texture = loadBmpToTexture(cotton1);
cube[1].texture = loadBmpToTexture(cotton2);
glClearColor( 0.0, 0.5, 0.7, 1.0 );
last_T = ftime();
}
static void animation(
float const speed
)
{
/* The objective is to let the cubes bounce into each other
* (collision) and with the walls. First the collision: */
if( cube[0].x > cube[1].x && cube[0].V_x > 0 && cube[1].V_x < 0 ) {
/* cubes bounced off each other. Exchange their velocities */
double const V_x = cube[0].V_x;
cube[0].V_x = cube[1].V_x;
cube[1].V_x = V_x;
double const x = cube[0].x;
cube[0].x = cube[1].x;
cube[1].x = x;
}
/* and the wall bounce */
if( cube[0].x < -0.1 && cube[0].V_x < 0 ) {
/* left cube bounced into left wall */
cube[0].V_x *= -1;
}
if( cube[1].x > 0.1 && cube[1].V_x > 0 ) {
/* right cube bounced into left wall */
cube[1].V_x *= -1;
}
cube[0].x += speed * cube[0].V_x;
cube[1].x += speed * cube[1].V_x;
}
/* Ideally we'd use a precise animation loop interleaved with event processing here.
* Unfortunately GLUT doesn't offer those, so we use this arcane kludge.
*
* It would get a bit more robust by putting the whole timing into the display function
* but better abandon GLUT and get a true event loop.
*/
static void idle(
void )
{
const double now_T = ftime();
const double delta_T = now_T - last_T;
last_T = now_T;
const double speed = delta_T * 60;
animation( speed );
glutPostRedisplay( );
}
static void display(void)
{
/* We try to be as stateless as possible. Yes, in the face of a statefull
* API, like OpenGL, this may sound a bit pedantic. */
const int width = glutGet(GLUT_WINDOW_WIDTH);
const int height = glutGet(GLUT_WINDOW_HEIGHT);
const float ar = ( float ) width / ( float ) height;
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
/* It's really best practice to set everything related to drawing
* – and that includes the projection – in the drawing function */
glViewport( 0, 0, width, height );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho(-ar, ar, -1, 1, -1, 1);
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
//Background
if(texture_background) {
glBindTexture( GL_TEXTURE_2D, texture_background );
glEnable( GL_TEXTURE_2D );
glBegin( GL_QUADS );
glTexCoord2f( 1.0, 1.0 );
glVertex2f( -1.0, 1.0 );
glTexCoord2f( 0.0, 1.0 );
glVertex2f( 1.0, 1.0 );
glTexCoord2f( 0.0, 0.0 );
glVertex2f( 1.0, -1.0 );
glTexCoord2f( 1.0, 0.0 );
glVertex2f( -1.0, -1.0 );
glEnd();
glDisable( GL_TEXTURE_2D );
}
//TEXTURE 1
glBindTexture( GL_TEXTURE_2D, cube[1].texture );
glEnable( GL_TEXTURE_2D );
/* Remember we're still in modelview matrix mode.
* This push creates a copy of the currently modelview matrix,
* for our disposal. With a following pop we restore to the
* state saved now. Pushes and Pops nest. */
glPushMatrix();
/* This applies our animation position to the modelview matrix.
* All geometry drawing to follow is subject to this additional
* transformation, until the matrix changes again. */
glTranslatef(cube[1].x, 0, 0);
glBegin( GL_TRIANGLE_FAN );
glTexCoord2f( 0.5f, 0.5f );
glVertex2f( 0.5f, 0.0f ); //center
glTexCoord2f( 1.0f, 0.5f );
glVertex2f( 0.8f + x, 0.0f ); //right
glTexCoord2f( 0.75f, 1.0f );
glVertex2f( 0.55f + x, 0.3f + x ); //top right
glTexCoord2f( 0.25f, 1.0f );
glVertex2f( 0.35f - x, 0.3f + x ); //Top left
glTexCoord2f( 0.0f, 0.5f );
glVertex2f( 0.25f - x, 0.0f ); //left
glTexCoord2f( 0.25f, 0.0f );
glVertex2f( 0.45f - x, -0.3f - x ); //bottom left
glTexCoord2f( 0.75f, 0.0f );
glVertex2f( 0.7f + x, -0.2f - x ); //bottom right
glTexCoord2f( 1.0f, 0.5f );
glVertex2f( 0.8f + x, 0.0f ); //right
glEnd( );
glPopMatrix( );
glDisable( GL_TEXTURE_2D );
//TEXTURE 2
/* in the original code you didn't use the other texture,
* Probably because you lost track of variables and indices. */
glBindTexture( GL_TEXTURE_2D, cube[0].texture );
glEnable( GL_TEXTURE_2D );
glPushMatrix();
glTranslatef(cube[0].x, 0, 0);
glBegin( GL_TRIANGLE_FAN );
glTexCoord2f( 0.5f, 0.5f );
glVertex2f( -0.5f, 0.0f ); //center
glTexCoord2f( 1.0f, 0.5f );
glVertex2f( -0.2f + y, 0.0f ); //right
glTexCoord2f( 0.75f, 1.0f );
glVertex2f( -0.4f + y, 0.2f + y ); //top right
glTexCoord2f( 0.25f, 1.0f );
glVertex2f( -0.7f - y, 0.1f + y ); //Top left
glTexCoord2f( 0.0f, 0.5f );
glVertex2f( -0.8f - y, 0.0f ); //left
glTexCoord2f( 0.25f, 0.0f );
glVertex2f( -0.7f - y, -0.1f - y ); //bottom left
glTexCoord2f( 0.75f, 0.0f );
glVertex2f( -0.3f + y, -0.2f - y ); //bottom right
glTexCoord2f( 1.0f, 0.5f );
glVertex2f( -0.2f + y, 0.0f ); //right
glEnd();
glPopMatrix();
glDisable( GL_TEXTURE_2D );
glutSwapBuffers();
/* Your glFinish here was totally pointless.
* First it would belong _before_ glutSwapBuffers.
* Second glutSwapBuffers implies a glFinish, so it's totally redundant. */
}
static void key(
unsigned char key,
int a,
int b )
{
switch ( key ) {
case 27:
case 'q':
exit( 0 );
break;
case '+':
if( ( x + 0.01 ) < 0.98 )
x = x + 0.01;
if( ( y + 0.01 ) < 0.98 )
y = y + 0.01;
break;
case '-':
if( ( x - 0.1 ) > ( -0.15 ) )
x = x - 0.01;
if( ( y - 0.1 ) > ( -0.10 ) )
y = y - 0.01;
break;
case 'o':
if( ( x + 0.01 ) < 0.98 )
x = x + 0.01;
break;
case 'p':
if( ( x - 0.1 ) > ( -0.15 ) )
x = x - 0.01;
break;
case '[':
if( ( y + 0.01 ) < 0.98 )
y = y + 0.01;
break;
case ']':
if( ( y - 0.1 ) > ( -0.10 ) )
y = y - 0.01;
break;
}
glutPostRedisplay();
}
int main(
int argc,
char *argv[] )
{
glutInit( &argc, argv );
glutInitWindowSize( 640, 640 );
glutInitWindowPosition( 50, 50 );
/* glutInitDisplayMode must be called before calling glutCreateWindow
* GLUT, like OpenGL is stateful */
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH );
glutCreateWindow( "Assignment number 3" );
glutDisplayFunc( display );
glutKeyboardFunc( key );
glutIdleFunc( idle );
init();
glutMainLoop( );
return EXIT_SUCCESS;
}