Exemple 5: une sphère avec une texture
Ce programme génère lui-même une texture en forme de damier, et la plaque sur une sphère colorée. Les coordonnées des sommets de la sphère sont calculés selon une paramétrisation en coordonnées... sphériques.
Fichier : examples/prog5.cpp /*
Exemple de génération procédurale et d'utilisation d'une texture.
*/
#include <math.h>
#include "glut_import.h"
#include "application.h"
#include "texture.h"
#define N 30
#define M 15
#define pi 3.141592653589793
class DemoWindow:public Window{
Texture_2D tex;
void vertex(float i,float j){
float o1=pi*i*2/N,o2=pi*(j/M-0.5);
glTexCoord2f(i/N,j/M);
glColor3f(0.5+0.5*cos(o2)*cos(o1),0.5+0.5*sin(o2),0.5+0.5*cos(o2)*sin(o1));
glVertex3f(cos(o2)*cos(o1),sin(o2),cos(o2)*sin(o1));
}
void makeTexture(int w,int h){
unsigned char *p=(unsigned char *) malloc(w*h*3), *q;
int i,j;
unsigned char k;
for (i=0;i<w;i++)
for (j=0;j<h;j++){
q=p+3*(j*w+i);
if (((i/10)%2==0)^((j/10)%2==0))
k=255;
else
k=0;
q[0]=k;
q[1]=k;
q[2]=k;
}
tex.bind();
gluBuild2DMipmaps(GL_TEXTURE_2D,GL_RGB,w,h,GL_RGB,GL_UNSIGNED_BYTE,p);
free(p);
}
public:
DemoWindow():
Window("Fenêtre de démonstration",windowStyle(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE,WC_IDLE | WC_KEYBOARD)){};
void onIdle(){
redisplay();
};
void onDisplay(){
float t=0.03*glutGet(GLUT_ELAPSED_TIME);
int i,j;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
tex.bind();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(70,(float) getWidth()/getHeight(),0.1,100);
gluLookAt(0,0,2,0,0,0,0,1,0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(0.5*t,1,0,0);
glRotatef(0.7*t,0,1,0);
glRotatef(0.9*t,0,0,1);
for (i=0;i<N;i++){
glBegin(GL_QUAD_STRIP);
for (j=0;j<=M;j++){
vertex(i,j);
vertex(i+1,j);
}
glEnd();
}
glFlush();
glutSwapBuffers();
};
void onCreate(){
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
printf("Generation de la texture-damier... ");
makeTexture(256,256);
printf("termine\nAppuyer sur [ESCAPE] pour quitter\n");
};
};
int main(){
DemoWindow w;
Application::run();
} Ce document a été traduit de LaTeX par HeVeA |