Adding texture to elements with openGL - c++
I'm trying to build a giraffe with openGL. I already made the body and the walking, but I want to add texture I found. I'm adding my code for you to see.
#define _CRT_SECURE_NO_DEPRECATE
#include <stdlib.h>
#include <glut.h>
#include <stdio.h>
#include <math.h>
#include <windows.h>
#include <iostream>
#include <conio.h>
GLUquadricObj *p; /* pointer to quadric object */
GLuint GIRAFFE;
GLuint BODY;
GLuint LEGUP;
GLuint LEGDOWN;
GLuint HEAD;
GLuint CORN;
GLuint EYES;
GLuint TAIL;
GLuint LIST_NAME;
GLuint BODY_PAINT;
float MAX=10.0, MIN=-10.0;
int flagLeft = 0, flagRight = 0; //flags that indicates if the giraffe can move to the left or the right. if 0 - it can, if 1 - it can't
float XPlace=0.0,YPlace=0.0,ZPlace=0.0, rotation = 0.0; //indicators where the giraffe is at a current time
int position = 0; //index for setting the legs of the girrafe. 0 - all four legs standing. 1 - forward right and backwards left are in the air, forward left and backward right are on the ground. 2 - forward right and backwards left are on the ground, forward left and backward right are in the air
GLuint LoadTexture(char *filename) // load a textures //
{
GLuint texture;
BITMAPFILEHEADER fileheader;
BITMAPINFOHEADER infoheader;
RGBTRIPLE pixel;
FILE *pFile = fopen( filename, "rb"); // Open the file for reading to buffer
if( pFile == NULL) return (-1);
fread( &fileheader, sizeof(fileheader), 1, pFile); // Read the file_header
fread( &infoheader, sizeof(infoheader), 1, pFile); // and read the info_header
//----------------
int w,h, nSize;
w=(int)(infoheader.biWidth);
h=(int)(infoheader.biHeight);
nSize = w * h * 4; //in memory: 4 bytes for every readed pixel
// Allocation memory for our image (width * height * bytesPerPixel)
unsigned char *pImage = (unsigned char *)new char[nSize];
//------------
// Read w*h times data about every pixel from BMP file and locate them to memory
// if our file is 24-bit Bitmap type, so for every pixel we have 24/8=3 Bytes
// in this program size of memory for Image bigger of size of file
// (in memory: 4 bytes for every pixel)
int j = 0; //index for Image
for( int i=0; i < w * h; i ++ ) //index for BMP file
{
// We load an RGB value from the file
fread( &pixel, sizeof(pixel), 1, pFile);
// And store data in right places( additional here every rgb pixel = 4 bytes)
pImage[j+0] = pixel.rgbtRed; // Red component
pImage[j+1] = pixel.rgbtGreen; // Green component
pImage[j+2] = pixel.rgbtBlue; // Blue component
pImage[j+3] = 255; // Alpha value - is used in the process
//of combining texture with background
//to create a partial transparency
j += 4; // Go to the next 4 bytes in memory
}
fclose( pFile ); // Close the file stream
glEnable(GL_TEXTURE_2D);
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 );
// the texture wraps over at the edges (repeat)
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
// Make Texture(2D MIPmaps format image) from our Image in memory
//in this program for texture we define 4 bytes for 1 pixel
gluBuild2DMipmaps(GL_TEXTURE_2D, 4, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pImage);
free(pImage);
return texture;
}
#pragma region Body Parts
void HoofDown() //the hoof of the giraffe when it's down
{
glPushMatrix();
glTranslatef(-3,-7.5,1.8);
glColor3f(0.4, 0.75, 0.13);
glRotatef(245.0, 0.2, 0.2, 0.2);
gluDisk(p, 0.,1.,25,5);
glPopMatrix();
}
void HoofUp() //the hoof of the giraffe when it's up
{
glPushMatrix();
glTranslatef(-7,-6,1.8);
glColor3f(0.4, 0.75, 0.13);
glRotatef(220.0, 0.2, 0.2, 0.2);
gluDisk(p, 0.,1.,25,5);
glPopMatrix();
}
void Chest() //CHEST
{
glPushMatrix();
glTranslatef(-2,2.,0.);
glRotatef(90,1.,1.,0.);
gluCylinder(p,2.5,1.5,4.5,15,10);
glPopMatrix();
}
void Neck()
{
glPushMatrix();
glTranslatef(-5,14,0);
glRotatef(90,1,0.2,0);
gluCylinder(p,0.5,1.3,11,15,10);
glPopMatrix();
}
void ThighDown() //the thigh of the giraffe when it's down
{
glPushMatrix();
glTranslatef(-3,0.5,1.5);
glColor3f(0.4, 0.75, 0.13);
glRotatef(90,1.,0.,0.);
gluCylinder(p,0.5,0.5,4,15,10);
glPopMatrix();
}
void ThighUp() //the thigh of the giraffe when it's up
{
glPushMatrix();
glTranslatef(-3,0.5,1.5);
glColor3f(0.4, 0.75, 0.13);
glRotatef(90,3.,-3.,0.);
gluCylinder(p,0.5,0.5,4,15,10);
glPopMatrix();
}
void LegDown() //the leg of the giraffe when it's down
{
glPushMatrix();
glTranslatef(-3,-3.5,1.5);
glColor3f(0.4, 0.75, 0.13);
glRotatef(90,0.5,0.,0.);
gluCylinder(p,0.5,0.5,4,15,10);
glPopMatrix();
}
void LegUp() //the leg of the giraffe when it's up
{
glPushMatrix();
glTranslatef(-5.7,-2.2,1.5);
glColor3f(0.4, 0.75, 0.13);
glRotatef(90,1.5,-0.5,0.);
gluCylinder(p,0.5,0.5,4,15,10);
glPopMatrix();
}
void FootDown() //the lower leg of the giraffe when it's down
{
glPushMatrix();
glTranslatef(-3,-3.5,1.5);
glColor3f(0.4, 0.75, 0.13);
glRotatef(86,1.,0.,0.);
gluCylinder(p,0.3,0.7,4,15,10);
glPopMatrix();
}
void FootUp() //the lower leg of the giraffe when it's up
{
glPushMatrix();
glTranslatef(-5.7,-2.2,1.5);
glColor3f(0.4, 0.75, 0.13);
glRotatef(90,1.5,-0.5,0.);
gluCylinder(p,0.3,0.7,4,15,10);
glPopMatrix();
}
void Head1() //head part1
{
glPushMatrix();
glTranslatef(-5.3,14.3,0);
glRotatef(90,1.,-0.9,0.);
gluCylinder(p,0.7,0.3,3,15,10);
glPopMatrix();
}
void Cornp1() //corn part1
{
glPushMatrix();
glTranslatef(-8.8,14.3,0);
glColor3f(0.5, 0.35, 0.05);
glRotatef(90,1.,0.3,0.);
gluCylinder(p,0,0.2,1,15,10);
glPopMatrix();
}
void Cornp2() //corn part2
{
glPushMatrix();
glTranslatef(-8.6,13.3,0);
glRotatef(90,1.,0.9,0.);
gluCylinder(p,0.2,0.4,1,15,10);
glPopMatrix();
}
void Sphere()
{
glPushMatrix();
glTranslatef(-1.92,2,0.);
glRotatef(0.,0.,0.,1.);
gluSphere(p,2.5,15,21);
glPopMatrix();
}
void Sphere2()
{
glPushMatrix();
glTranslatef(1.5,-1.5,0.);
gluSphere(p,1.5,15,21);
glPopMatrix();
}
void Headp2() //head part2
{
glPushMatrix();
glTranslatef(-5.2,14.5,0.);
gluSphere(p,0.8,15,21);
glPopMatrix();
}
void Headp3() //head part3
{
glPushMatrix();
glTranslatef(-7.4,11.8,0.);
gluSphere(p,0.5,15,21);
glPopMatrix();
}
void HeadMiddle() //head middle part4
{
glPushMatrix();
glTranslatef(-6,12.8,0.);
gluSphere(p,0.5,15,21);
glPopMatrix();
}
void Eyes() //EYES
{
glPushMatrix();
glTranslatef(-11,12.9,0.2);
glColor3f(0.4, 0.75, 0.13);
gluSphere(p,0.2,15,21);
glPopMatrix();
}
void Tail()
{
glPushMatrix();
glTranslatef(-2.4,-0.3,-0.5);
glRotatef(90,1,0.5,0);
gluCylinder(p,0.2,0.1,4,15,10);
glPopMatrix();
}
#pragma endregion
#pragma region Leg Positions
void stand() //all four legs of the giraffe are on the ground
{
glCallList (LEGDOWN); //leg forward right
glPopMatrix();
glTranslatef (0, 0,-2.5);
glCallList (LEGDOWN); //leg forward left
glPopMatrix();
glScalef(1,1,1);
glTranslatef (5.4, -1.6, 0.3);
glScalef(1,0.8,1);
glCallList (LEGDOWN); //leg backward left
glPopMatrix();
glTranslatef (0, 0 ,1.5);
glCallList (LEGDOWN); //leg backward right
glPopMatrix();
}
void rightUp() //forward right and backwards left are in the air, forward left and backward right are on the ground
{
glCallList (LEGUP); //leg forward right
glPopMatrix();
glTranslatef (0, 0,-2.5);
glCallList (LEGDOWN); //leg forward left
glPopMatrix();
glScalef(1,1,1);
glTranslatef (5.4, -1.6, 0.3);
glScalef(1,0.8,1);
glCallList (LEGUP); //leg backward left
glPopMatrix();
glTranslatef (0, 0 ,1.5);
glCallList (LEGDOWN); //leg backward right
glPopMatrix();
}
void leftUp() //forward right and backwards left are on the ground, forward left and backward right are in the air
{
glCallList (LEGDOWN); //leg forward right
glPopMatrix();
glTranslatef (0, 0,-2.5);
glCallList (LEGUP); //leg forward left
glPopMatrix();
glScalef(1,1,1);
glTranslatef (5.4, -1.6, 0.3);
glScalef(1,0.8,1);
glCallList (LEGDOWN); //leg backward left
glPopMatrix();
glTranslatef (0, 0 ,1.5);
glCallList (LEGUP); //leg backward right
glPopMatrix();
}
#pragma endregion
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glRotatef(0+rotation,0.,2.,0.);
glTranslatef(XPlace,YPlace,ZPlace);
glCallList (BODY);
glCallList (HEAD);
glTranslatef (2, 2, 0.6);
glCallList (CORN);
glTranslatef (0, 0, -0.7);
glCallList (CORN);
glTranslatef (-2.3, -1.3, 0);
glScalef(1,1.5,1);
switch (position)
{
case 0:
stand();
break;
case 1:
rightUp();
break;
default:
leftUp();
break;
}
glCallList (EYES);
glTranslatef (0, 0 ,1.2);
glCallList (EYES);
glCallList (TAIL);
glFlush();
glutSwapBuffers();
}
void rotate(int direction)
{
if(direction == 1)
rotation += 0.5;
if(direction == 2)
rotation -= 0.5;
}
void myReshape(int w,int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-20.,20.,-20.,20.,-20.,20.);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void changePosition() //changing the position for setting the legs
{
position++;
if(position == 3)
position = 0;
}
void myinit()
{
LIST_NAME= glGenLists (9);
BodyPaint = LoadTexture("giraffeSkin.bmp");
p=gluNewQuadric(); /* allocate quadric object */
gluQuadricDrawStyle(p, GLU_LINE); /* render it as wireframe */
glClearColor(1.0, 1.0, 1.0, 1.0);
glColor3f(0.4, 0.75, 0.13);
BODY=LIST_NAME;
glNewList (BODY, GL_COMPILE);
Chest();
Neck();
Sphere();
Sphere2();
glEndList();
LEGUP=LIST_NAME+1;
glNewList(LEGUP ,GL_COMPILE);
ThighUp();
LegUp();
FootUp();
HoofUp();
glEndList();
LEGDOWN=LIST_NAME+2;
glNewList(LEGDOWN ,GL_COMPILE);
ThighDown();
LegDown();
FootDown();
HoofDown();
glEndList();
HEAD=LIST_NAME+3;
glNewList(HEAD,GL_COMPILE);
Head1();
Headp2();
Headp3();
glEndList();
CORN=LIST_NAME+4;
glNewList(CORN,GL_COMPILE);
Cornp1();
Cornp2();
glEndList();
EYES=LIST_NAME+5;
glNewList(EYES,GL_COMPILE);
Eyes();
glEndList();
TAIL=LIST_NAME+6;
glNewList(TAIL,GL_COMPILE);
Tail();
glEndList();
GIRAFFE=LIST_NAME+7;
}
void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case '2'://up
rotate(1);
glutPostRedisplay();
break;
case '4'://left
if(flagLeft==0)
{
flagRight = 0;
XPlace=XPlace-0.05;
if(XPlace<=MIN)
flagLeft=1;
changePosition();
}
glutPostRedisplay();
break;
case '6'://right
if(flagRight==0)
{
flagLeft = 0;
XPlace=XPlace+0.05;
if(XPlace>=MAX)
flagRight=1;
changePosition();
}
glutPostRedisplay();
break;
case '8'://down
rotate(2);
glutPostRedisplay();
break;
case 27: // ESC: exit the program
exit(0); break;
default:
break;
}
}
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(1000, 1000);
glutCreateWindow("Quadric Objects");
myinit();
glutKeyboardFunc(keyboard); // Register handler for key event
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutMainLoop();
}
The texture I found named giraffeSkin.bmp
I know I should use glBindTexture function but I don't know where. Could someone give me a hand here?
It looks like you're using the quadrics ( for example, "gluCylinder" ) libraries. They have their own way of doing texture mappings. Look at the function gluQuadricTexture. You'll see that mapping on quadrics is a bit involved.
http://www.opengl.org/sdk/docs/man2/xhtml/gluQuadricTexture.xml
Meanwhile, when texture mapping, remember to call glEnable( GL_TEXTURE_2D )
Related
OpenGL Project - objects not keeping filling color on movement
When I execute the code I get a hot air balloon formed of three elements. My issue is that when I move the objects from the keyboard, the objects loose color, and become more like wire than solid. From what I discovered until now, my trouble comes from this function call: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) But I need it to make the ropes... /* This program shows a hot air balloon rotating around its own axe to the left and to the right */ #include "glos.h" #include<math.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glaux.h> void myinit(void); void CALLBACK display(void); void CALLBACK myReshape(GLsizei w, GLsizei h); void CALLBACK rotateRight(void); void CALLBACK rotateLeft(void); static GLfloat x = 0; static GLfloat y = 0; static GLfloat z = 0; static GLfloat alfa = 0; double PI = 3.14159265; void myinit (void) { glClearColor(1.0, 1.0, 1.0, 1.0); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_COLOR_MATERIAL); glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE); } void CALLBACK rotateLeft(void) { y -= 5; } void CALLBACK rotateRight(void) { y += 5; } void CALLBACK display (void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); glRotatef(x, 1, 0, 0); glRotatef(y, 0, 1, 0); glTranslatef(0, -80, 0); //cube = basket glColor3f(1, 1, 0); auxSolidCube(50); //full sphere = baloon glPushMatrix(); glColor3f(1.0, 0.0, 0.0); glTranslatef(0,200,0); glRotatef(-90, 1, 0, 0); auxSolidSphere(130.0); glPopMatrix(); //polygon cylinder = ropes glPushMatrix(); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glBegin(GL_QUAD_STRIP); glColor3f(0.0, 1.0, 1.0); for (alfa = 0; alfa <= 360; alfa+=30) { glVertex3f(65 * sin((PI * alfa) / 180), 100, 65 * cos((PI * alfa) / 180));//top of the cylinder glVertex3f(15 * sin((PI * alfa) / 180),0, 15 * cos((PI * alfa) / 180));//base of the cylinder } glEnd(); glPopMatrix(); glPopMatrix(); glFlush(); } void CALLBACK myReshape(GLsizei w, GLsizei h) { if (!h) return; glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho (-400,400, -400 *(GLfloat)h / (GLfloat)w, +400.0*(GLfloat)h/(GLfloat)w, -1000.0, 1000.0); else glOrtho (-400*(GLfloat)w / (GLfloat)h, 400.0*(GLfloat)w/(GLfloat)h, -400, 400.0, -1000.0, 1000.0); glMatrixMode(GL_MODELVIEW); } int main(int argc, char** argv) { auxInitDisplayMode (AUX_SINGLE | AUX_RGB | AUX_DEPTH); auxInitPosition (100, 0, 600, 400); auxInitWindow ("Hot air balloon"); myinit (); auxKeyFunc(AUX_RIGHT, rotateRight); auxKeyFunc(AUX_LEFT, rotateLeft); auxReshapeFunc (myReshape); auxMainLoop(display); return(0); }
OpenGL is a state engine. Once a state has been set, it is retained until it is changed again, even beyond frames. Therefore, you need to set the polygon mode GL_FILL before rendering the solid geometry: void CALLBACK display (void) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // render solid geometry // [...] glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // render wireframe geometry // [...] }
Why in OpenGL my camera rotates 180 degrees every other time?
I want to do something like a 3d-shooter. The calculations seems to be correct, but it is works every other time with a spread with 180 degree rotation on every call glutPostRedisplay(). I understood that thanks to that red line. I do this with such IDE: Code Blocks / Qt Creator under Linux(Ubuntu x64). main.cpp #include "Functions.h" int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(wnd_width, wnd_height); glutInitWindowPosition(300, 100); glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glMatrixMode(GL_PROJECTION); glMatrixMode(GL_MODELVIEW); glutCreateWindow("OpenGL my"); glutDisplayFunc(display); glutIdleFunc(Idle); glutSpecialFunc(KeyPressed); GLdouble aspect = wnd_width/wnd_height; gluPerspective(90, aspect, 0.1, 10); glTranslatef(0, -0.3, 0); glutMainLoop(); return 0; } Functions.h #include <GL/glut.h> #include <math.h> #include <iostream> int wnd_width=1300; int wnd_height=900; float pos_x=0, pos_z=0.1; float angle = 0; float speed = 0.1; void DrawFloor(){ glVertex3d(1, 0, 2.5); glVertex3d(1, 0, 0); glVertex3d(-1, 0, 0); glVertex3d(-1, 0, 2.5); } void DrawWall(float x, float width, float height){ glVertex3f(x, height, 0); glVertex3f(x, height, width); glVertex3f(x, 0, width); glVertex3f(x, 0, 0); } void DrawLine(){ glVertex3f(0, 0.1, -1); glVertex3f(0, 0.1, 1); } void KeyPressed(int key, int x, int y){ switch (key) { case GLUT_KEY_UP: { //pos_x = speed * cos(3.14*angle/180); //pos_z = speed * sin(3.14*angle/180); pos_z+=0.1; break; } case GLUT_KEY_DOWN: { pos_x = speed*cos(angle); pos_z = speed*sin(angle); break; } case GLUT_KEY_LEFT: { angle += 1; pos_x = speed * cos(3.14 * angle/180); pos_z = speed * sin(3.14 * angle/180); break; } case GLUT_KEY_RIGHT: { angle -= 3; pos_x = speed * cos(3.14 * angle/180); pos_z = speed * sin(3.14 * angle/180); break; } } std::cout<<"x: "<<pos_x<<'\t'; std::cout<<"z: "<<pos_z<<'\n'; glutPostRedisplay(); } void display(){ glClearColor(0.6, 0.8, 1, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); gluLookAt(pos_x, 0, pos_z, pos_x, 0, pos_z+0.2, 0, 1, 0); glBegin(GL_QUADS); glColor3f(0, 0, 0.7); DrawFloor(); glColor3f(0, 0.8, 0.1); DrawWall(-0.5, 2, 0.7); DrawWall(0.5, 2, 0.7); glEnd(); glLineWidth(2); glColor3f(0.7, 0.2, 0.2); glBegin(GL_LINES); DrawLine(); glEnd(); glutSwapBuffers(); } void Idle(){ //pos_z+=0.01; //glutPostRedisplay(); }
You're using the fixed function stack, so you'll have to learn what glMatrixMode does and how transformation matrices are managed in those old ways. Anyway, consider this a possible implementation of glMatrixMode void glMatrixMode(GLenum m) { switch(m){ case GL_MODELVIEW: ctx->M = &ctx->matrix_modelview; break; case GL_PROJECTION: ctx->M = &ctx->matrix_projection; break; case GL_TEXTURE: ctx->M = &ctx->matrix_texture; break; case GL_COLOR: ctx->M = &ctx->matrix_color; break; } } On other words, there's a (context) global matrix selected with glMatrixMode, that's subsequently used for all folloing matrix manipulations. Hence, glMatrixMode is not some form of initialization, but something you use to switch (often several times) during rendering a frame! Your use of it in the main function is kind of pointless. You must use it in your drawing function. Furthermore, every matrix manipulation multiplies on top, of what's currently in ctx->M. gluLookAt is normally used with a identity matrix. If you don't reset you identity, that gluLookAt will work relative to the look-at done previously. So what you want is this: void display(){ glClearColor(0.6, 0.8, 1., 1.); /* <<<----* */ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTIOM); glLoadIdentity(); setup_projection_here(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(pos_x, 0, pos_z, pos_x, 0, pos_z+0.2, 0, 1, 0); glBegin(GL_QUADS); /* ... */ glutSwapBuffers(); } (*) Also you normally want to clear to alpha = 1 on the main framebuffer, unless you're planning on drawing window-translucent imagery. With alpha = 0 things might look correct in the window, but if a screenshot is taken, or some screen recording or sharing is used, it may cause undesired transparence.
using gluLookAt and mouse to channge viewing angle in opengl/glut
Hello so i am attempting to use a mouse function to move the perspective of gluLookAt to no luck so far i have attempted to adjust upX and upY based off of the mouse position however I want the program to be able to do an entire 360 rotation around the object based on the mouse movement and would like it to stop when the mouse movement in the window stops. Any help would be appreciated I am still learning #include <iostream> #include <math.h> #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> float posX=4, posY=6, posZ=5, targetX=0, targetY=0, targetZ=0, upX=0, upY=1, upZ=0; void display() { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, 4.0/3.0, 1, 40); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(posX, posY, posZ, targetX, targetY, targetZ, upX, upY, upZ); glColor3f(1.0, 1.0, 1.0); glutWireTeapot(1.5); glBegin(GL_LINES); glColor3f(1, 0, 0); glVertex3f(0, 0, 0); glVertex3f(10, 0, 0); glColor3f(0, 1, 0); glVertex3f(0, 0, 0); glVertex3f(0, 10, 0); glColor3f(0, 0, 1); glVertex3f(0, 0, 0); glVertex3f(0, 0, 10); glEnd(); glFlush(); } void usage(){ std::cout<< "\n\n\ q,Q: Quit\n\n" ; std::cout.flush(); } void onMouseMove(int x, int y) { posX = x*cos(posY) + PosY*sin(PosX)*sin(yRot) - dz*cos(xRot)*sin(yRot) glutPostRedisplay(); } void KeyboardFunc (unsigned char key, int eyeX, int eyeY) { switch (key) { case 'q': case 'Q': exit(0); break; } glutPostRedisplay(); } void init() { glClearColor(0.0, 0.0, 0.0, 1.0); glColor3f(1.0, 1.0, 1.0); usage(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowPosition(300,250); glutInitWindowSize(800, 600); glutCreateWindow("Final"); init(); glutDisplayFunc(display); glutPassiveMotionFunc(&onMouseMove); glutKeyboardFunc(&KeyboardFunc); glutMainLoop(); }
If you want to implement an arcball camera, and you want to do it with the fixed-function pipeline matrix stack, it'd actually be simpler to not use gluLookAt() but glRotate/glTranslate, like so: glTranslatef(0f, 0f, -radius); glRotatef(angX, 1f, 0f, 0f); glRotatef(angY, 0f, 1f, 0f); glTranslatef(-targetX, -targetY, -targetZ); where radius is the distance of the "camera" to the viewed point, angX is the angle around the X axis, angY the angle around the Y axis and (targetX, targetY, targetZ) is the position of the viewed point (your targetX/Y/Z). You don't have to compute sin/cos yourself (it is computed by glRotatef) and all you have to do is set/increase angX and angY in your motion function.
Opengl Cant set color to solid with glColor3f(1.0f, 0.0f, 0.0f) very opaque red
in image appearing red opaque but i set the glColor3f(1.0f, 0.0f, 0.0f); //command compiler g++ console tested with Visual Studio Code //g++ GL01Hello.cpp -o GL01Hello.exe -L"C:/MinGW/freeglut/lib" -lglu32 -lopengl32 -lfreeglut -I"C:\MinGW\freeglut\include\GL" /* * GL01Hello.cpp:With Load Background Image and Poligon Test OpenGL/GLUT C/C++ Setup * Tested Visual Studio Code with MinGW * To compile with -lfreeglut -lglu32 -lopengl32 and */ #include <windows.h> // for MS Windows #include <stdio.h> /* printf, scanf, puts, NULL */ #include <iostream> #include <stdlib.h> /* srand, rand */ #include <ctime> #include <freeglut.h> // GLUT, include glu.h and gl.h using namespace std; float spin = 0.0; GLuint texture = 0; int w1 = 0; int h1 = 0; // for random color primitive polygon //static GLubyte redc,greenc,bluec; bool prim_polygonmode = false; // glut_load_image GLuint LoadTexture( const char * filename ) { GLuint texture; int width, height; unsigned char * data; FILE * file; file = fopen( filename, "rb" ); if(!file) std::cout<<"File not Found"<<std::endl; if ( file == NULL ) return 0; width = 1360; height = 768; data = (unsigned char *)malloc( width * height * 3 ); //int size = fseek(file,); 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 ); glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );//Necessary for correct elements value 4 default 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; } /* Initialize OpenGL Graphics just n this case for colors */ void initGL() { // Set "clearing" or background color glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Black and opaque //randomnumber color by ctime library srand(time(NULL)); //redc = rand()%255; //greenc = rand()%255; //bluec = rand()%255; } /* Called back when there is no other event to be handled */ void idle() { spin = spin + 0.075; if (spin > 360.0) spin = 0; glutPostRedisplay(); // Post a re-paint request to activate display() } /* Handler for window re-size event. Called back when the window first appears and whenever the window is re-sized with its new width and height */ void reshape(GLsizei width, GLsizei height) { // GLsizei for non-negative integer // Compute aspect ratio of the new window w1 = width; h1 = height; if (height == 0) height = 1; // To prevent divide by 0 GLfloat aspect = (GLfloat)width / (GLfloat)height; // Set the viewport to cover the new window glViewport(0, 0, width, height); // Set the aspect ratio of the clipping area to match the viewport glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix glLoadIdentity(); if (width >= height) { // aspect >= 1, set the height from -1 to 1, with larger width gluOrtho2D(-1.0 * aspect, 1.0 * aspect, -1.0, 1.0); } else { // aspect < 1, set the width to -1 to 1, with larger height gluOrtho2D(-1.0, 1.0, -1.0 / aspect, 1.0 / aspect); } } void orthogonalStart() { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(-w1/2, w1/2, -h1/2, h1/2); glMatrixMode(GL_MODELVIEW); } void orthogonalEnd() { glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); } void background() { glBindTexture( GL_TEXTURE_2D, texture ); orthogonalStart(); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPolygonOffset(1,1); // texture width/height const int iw = 1360; const int ih = 768; glPushMatrix(); glTranslatef( -iw/2, -ih/2, 0 ); glBegin(GL_QUADS); glColor3f(1.0f, 1.0f, 1.0f); // always default color white stars, if no this line will random color same of polygon glTexCoord2i(0,0); glVertex2i(0, 0); glTexCoord2i(1,0); glVertex2i(iw, 0); glTexCoord2i(1,1); glVertex2i(iw, ih); glTexCoord2i(0,1); glVertex2i(0, ih); glEnd(); glPopMatrix(); orthogonalEnd(); } void display() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque glClear(GL_COLOR_BUFFER_BIT);// Clear the color buffer (background glEnable( GL_TEXTURE_2D ); background(); gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); // A SQUARE PARAMETERS if (prim_polygonmode) { // draw polygon mode lines glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } else { glEnable(GL_POLYGON_OFFSET_FILL); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPolygonOffset(1,1); } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glPushMatrix(); glRotatef(spin , 0., 0., 1.); glTranslatef(50.0, 50.0, 0); glTranslatef(-50.0, -50.0, 0); glBegin(GL_QUADS); // Each set of 4 vertices form a quad //glColor3ub(redc, greenc, bluec); // Random red green blue value glColor3f(1.0f, 0.0f, 0.0f); // Random red green blue value glVertex2f(-0.5f, -0.5f); // x, y default 0.5f values glVertex2f( 0.5f, -0.5f); glVertex2f( 0.5f, 0.5f); glVertex2f(-0.5f, 0.5f); glEnd(); //angle += 5.0f; glPopMatrix(); // glFlush(); // Render now glutSwapBuffers(); // Double buffered - swap the front and back buffers } /* Callback handler for special-key event */ void specialKeys(int key, int x, int y) { switch (key) { case GLUT_KEY_F1: // F1: Toggle wireframe and solid polygon prim_polygonmode = !prim_polygonmode; // Toggle state break; } } /* Main function: GLUT runs as a console application starting at main() */ int main(int argc, char** argv) { glutInit(&argc, argv); // Initialize GLUT glutInitDisplayMode(GLUT_DOUBLE); // Enable double buffered mode glutInitWindowSize(1360, 768); // Set the window's initial width & height glutInitWindowPosition(0, 0); // Position the window's initial top-left corner glutCreateWindow("OpenGL Setup Test"); // Create a window with the given title glutSpecialFunc(specialKeys); // Register callback handler for special-key event glutDisplayFunc(display); // Register display callback handler for window re-paint glutReshapeFunc(reshape); glutIdleFunc(idle); // GLuint texture; texture = LoadTexture( "stars.bmp" ); initGL(); glutMainLoop();// Enter the event-processing loop //Free our texture glDeleteTextures( 1, &texture ); return 0; } This code have a set background and small animation of square. Dont know wihy cant set more the solid colors. Then the wireframe square i got a very litle line red need got the bright color red.Maybe any filte, ou buffer causing that? if possible please help me.
OpenGL is a state engine. Once a state is set, it is persistent until it is change again. This means if 2 dimensional texturing is enabled, all the following geometry is "textured". Note, when glVertex2f is called then the current texture coordinate is associated with the vertex coordinate. If you don't explicitly set a texture coordinate, then the last texture coordinate which was set is still the current texture coordinate and will be associated to the vertex coordinate. This may cause a random like behavior. If texturing is enabled, then by default the color of the texel is multiplied by the current color, because by default the texture environment mode (GL_TEXTURE_ENV_MODE) is GL_MODULATE. See glTexEnv. That all means: If you want to draw a geometry with a texture then enable texturing and set a "white" color: glEnable(GL_TEXTURE_2D) glColor3f(1.0f, 1.0f, 1.0f); background(); If you want to draw a uniform colored geometry, then set the color and disable texturing: glDisable(GL_TEXTURE_2D); glColor3f(1.0f, 0.0f, 0.0f); glBegin(GL_QUADS); // [...] glEnd();
OpenGL displaying white textures
I have trouble displaying a texture using OpenGL and C++. I am loading the texture from a RGB Raw file, binding it to a texture, but when I am trying to display the texture on a quad, the texture is white. I am using glGetError and it catches no errors. Here is my code: #include <iostream> #include <windows.h> // Standard header for MS Windows applications #include <GL/gl.h> // Open Graphics Library (OpenGL) header #include <GL/glut.h> // The GL Utility Toolkit (GLUT) Header using namespace std; typedef struct { int width; int height; char* title; float field_of_view_angle; float z_near; float z_far; } glutWindow; glutWindow win; float rotation, distance1; bool light=TRUE; bool trans=FALSE; GLuint tex; void drawFlatFace(float size) { glBegin(GL_QUADS); glTexCoord2f (0, 0); glVertex3f(-size, -2*size, size); glTexCoord2f (1.0, 0); glVertex3f(size, -2*size, size); glTexCoord2f (1.0, 1.0); glVertex3f(size, 2*size, size); glTexCoord2f (0, 1.0); glVertex3f(-size, 2*size, size); glEnd(); } void drawBlock(float size){ glColor3f(1.0f,1.0f,1.0f); glPushMatrix(); drawFlatFace (size); glRotatef (90, 0, 1, 0); drawFlatFace (size); glRotatef (90, 0, 1, 0); drawFlatFace (size); glRotatef (90, 0, 1, 0); drawFlatFace (size); glPopMatrix(); } GLuint loadTexture(const char * filename) { GLuint text[1]; GLubyte* bits = new GLubyte[512*256*3]; FILE *file; fopen_s(&file,filename,"rb"); fread(&bits,(512*256*3),1,file); fclose(file); glGenTextures(1,&text[0]); glBindTexture(GL_TEXTURE_2D,text[0]); glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); glTexImage2D(GL_TEXTURE_2D, 0, 3,256,512,0,GL_RGB,GL_UNSIGNED_BYTE,bits); free(bits); return text[0]; } void display() { GLenum err; err = glGetError(); if (err != GL_NO_ERROR) { cerr << "OpenGL error: " << gluErrorString(err) << endl; } tex=loadTexture("tex.raw"); glBindTexture(GL_TEXTURE_2D,tex); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen and Depth Buffer glLoadIdentity(); gluLookAt( 10+distance1 ,1.4,0, 0,0,0, 0,1,0); // Define a viewing transformation glRotatef(rotation, 0.f, 1.f, 0.f); drawBlock(3); if (light) glEnable(GL_LIGHTING); // Enable Lighting else glDisable(GL_LIGHTING); // Disable Lighting if (trans) glEnable (GL_BLEND); // Enable Transparency else glDisable(GL_BLEND); // Disable Transparency glutSwapBuffers(); } void initialize () { glMatrixMode(GL_PROJECTION); // select projection matrix glViewport(0, 0, win.width, win.height); // set the viewport glLoadIdentity(); // reset projection matrix GLfloat aspect = (GLfloat) win.width / win.height; gluPerspective(win.field_of_view_angle, aspect, win.z_near, win.z_far); // set up a perspective projection matrix glMatrixMode(GL_MODELVIEW); // specify which matrix is the current matrix glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); // specify implementation-specific hints GLfloat amb_light[] = { 0.3, 0.3, 0.3, 1.0 }; GLfloat diffuse[] = { 0.4, 0.4, 0.4, 1.0 }; GLfloat specular[] = { 0.5, 0.5, 0.5, 1.0 }; glLightModelfv( GL_LIGHT_MODEL_AMBIENT, amb_light ); glLightfv( GL_LIGHT0, GL_SPECULAR, specular ); glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse ); GLfloat light_position[] = { 1.0, 1.0, 0, 0.0 }; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glEnable( GL_LIGHT0 ); glEnable( GL_COLOR_MATERIAL ); glEnable( GL_LIGHTING ); //glLightModeli( GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE ); glEnable(GL_TEXTURE_2D); // Enable Texture Mapping glShadeModel(GL_SMOOTH); // Enable Smooth Shading glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background glClearDepth(1.0f); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR); } void keyboard ( int key, int mousePositionX, int mousePositionY ) { switch ( key ) { case GLUT_KEY_DOWN: if (distance1<9){ distance1=distance1+.3; } break; case GLUT_KEY_UP: if (distance1>-9){ distance1=distance1-.3; } break; case GLUT_KEY_LEFT: rotation=rotation-2; break; case GLUT_KEY_RIGHT: rotation=rotation+2; break; case GLUT_KEY_PAGE_UP: light=TRUE; break; case GLUT_KEY_PAGE_DOWN: light=FALSE; break; case GLUT_KEY_HOME: trans=TRUE; break; case GLUT_KEY_END: trans=FALSE; break; default: break; } } int main(int argc, char **argv) { // set window values win.width = 800; win.height = 600; win.title = "Test Texture"; win.field_of_view_angle = 45; win.z_near = 1.0f; win.z_far = 500.0f; // initialize and run program glutInit(&argc, argv); // GLUT initialization glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH ); // Display Mode glutInitWindowSize(win.width,win.height); // set window size glutCreateWindow(win.title); // create Window // Callback functions glutDisplayFunc(display); // register Display Function glutIdleFunc( display ); // register Idle Function glutSpecialFunc( keyboard ); // register Keyboard Handler initialize(); glutMainLoop(); // run GLUT mainloop return 0; } I want to add that the Raw file is displayed correctly when loaded in IrfanView as 256x512, 24BPP, RGB (the size is 393,216 bytes or 3*512*256)
This line: glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR); Shouldn't be in your main intialisation, but instead needs to be done when setting up the texture itself (i.e. after binding). You may also want to set the MAG_FILTER, and the texture coordinate wrapping modes, as a general rule. Also, you appear to be loading the texture every time you render. Don't do that, performance will be terrible and you'll run out of memory as GL will keep allocating new textures.