openGL紋理繪製
阿新 • • 發佈:2018-11-10
#include <stdlib.h> #include <GL/glut.h> #define imageWidth 64 #define imageHeight 64 GLubyte image[imageWidth][imageHeight][3]; /*繪製一個簡單的二維紋理圖*/ void makeImage(void) { int i, j, r, g, b; /*根據點的位置設定不同的顏色*/ for (i = 0; i < imageWidth; i++) { for (j = 0; j <imageHeight; j++) { r = (i*j) % 255; g = (i*i) % 255; b = (j*j) % 255; image[i][j][0] = (GLubyte)b; image[i][j][1] = (GLubyte)g; image[i][j][2] = (GLubyte)r; } } } void myInit(void) { glClearColor(0.0, 0.0, 0.0, 0.0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); makeImage(); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); /*指定二維紋理對映*/ glTexImage2D(GL_TEXTURE_2D, 0, 3, imageWidth, imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, &image[0][0][0]); /*設定紋理引數*/ glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); /*設定紋理環境引數*/ glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); glEnable(GL_TEXTURE_2D); glShadeModel(GL_FLAT); } void myDisplay(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /*將紋理對映到四邊形上*/ glBegin(GL_QUADS); /*紋理的座標和四邊形頂點的對應*/ glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, 1.0, 0.0); glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, -1.0, 0.0); glTexCoord2f(1.0, 1.0); glVertex3f(1.0, -1.0, 0.0); glTexCoord2f(1.0, 0.0); glVertex3f(1.0, 1.0, 0.0); glEnd(); glFlush(); } void myReshape(int w, int h) { glViewport(0, 0, (GLsizei)w, (GLsizei)h); glMatrixMode(GL_PROJECTION); //glMatrixMode(GL_TEXTURE); glLoadIdentity(); gluPerspective(80.0, 1.0 - (GLfloat)w / (GLfloat)h, 1.0, 30.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int main(int argc, char **argv) { /*初始化*/ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(300, 300); glutInitWindowPosition(200, 200); /*建立視窗*/ glutCreateWindow(" Texture "); /*繪製與顯示*/ myInit(); glutReshapeFunc(myReshape); glutDisplayFunc(myDisplay); glutMainLoop(); return 0; }
執行結果:
FR:海濤高軟(hunk Xu)
QQ技術交流群:386476712