C++ 将png加载为纹理并将其绑定到球体
我找不到任何关于如何加载PNG文件并将其用作纹理将其绑定到球体的像样教程。有任何库函数可以执行此操作吗? 我如何将它绑定到一个球体上? 我已经尝试过了,但它没有工作,没有错误,但是纹理没有加载到球体上。 在glutMainLoop()之前,我使用特定文件调用LoadTexture 以下是我加载文件的代码:C++ 将png加载为纹理并将其绑定到球体,c++,opengl,C++,Opengl,我找不到任何关于如何加载PNG文件并将其用作纹理将其绑定到球体的像样教程。有任何库函数可以执行此操作吗? 我如何将它绑定到一个球体上? 我已经尝试过了,但它没有工作,没有错误,但是纹理没有加载到球体上。 在glutMainLoop()之前,我使用特定文件调用LoadTexture 以下是我加载文件的代码: GLuint LoadTexture( const char * filename, int width, int height ) { GLuint texture; unsigne
GLuint LoadTexture( const char * filename, int width, int height )
{
GLuint texture;
unsigned char * data;
FILE * file;
//The following code will read in our PNG file
file = fopen( filename, "rb" );
if ( file == NULL ) return 0;
data = (unsigned char *)malloc( width * height * 3 );
fread( data, width * height * 3, 1, file );
fclose( file );
glGenTextures( 1, &texture ); //generate the texture with
glBindTexture( GL_TEXTURE_2D, texture ); //bind the texture
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
GL_MODULATE ); //set texture environment parameters
//even better quality, but this will do for now.
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_LINEAR );
//Here we are setting the parameter to repeat the texture
//to the edge of our shape.
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
GL_REPEAT );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
GL_REPEAT );
//Generate the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0,
GL_RGB, GL_UNSIGNED_BYTE, data);
free( data ); //free the texture
return texture; //return whether it was successfull
}
这里是我创建球体的地方
void renderScene(void) {
// Clear Color and Depth Buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable( GL_TEXTURE_2D );
// Reset transformations
glLoadIdentity();
glBindTexture( GL_TEXTURE_2D, texture );
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glPushMatrix();
glTranslatef(0.0,2.0,-6);
glRotatef(angle, 0.0f, 2.0, -6.0f);
glutSolidSphere(1,50,50);
glPopMatrix();
angle+=0.4f;
glDisable(GL_TEXTURE_2D);
glutSwapBuffers();
}
我做对了吗 您正在将压缩的PNG数据馈送到OpenGL。它必须先解压缩,因为OpenGL纹理函数无法理解PNG。你可以使用一些图像库来解压它,比如PNG是压缩文件,你不能仅仅读入它们并期望OpenGL知道如何解码它们。加载PNG的推荐方法是使用
下面是一个使用libpng的示例,演示如何将PNG文件同步读取到二维数组中。OpenGL需要一个扁平的1D数组,所以你需要自己将其扁平化,但这非常简单。我建议使用图像加载库,这样可以为你完成所有的脏活。我还建议使用OpenGL API,但这是你的最终决定:)我意识到有一百万个库被扔给你,但我强烈建议。加载png非常简单
GLuint tex_2d = SOIL_load_OGL_texture( "img.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y);