gpt4 book ai didi

c++ - OpenGL 中多个纹理的问题

转载 作者:行者123 更新时间:2023-11-28 07:44:14 24 4
gpt4 key购买 nike

我正在尝试编写一个类来将对象加载到我的程序中/问题是 OpenGL 只加载所有对象的最后一个纹理。

代码如下:

game.cpp 类:

object =  new Object("table.obj", "wood.bmp",0); // a new object - obj file, texture and 
object1 = new Object("aa.obj", "cloth.bmp",1); // texture number

object->draw();
object1->draw();

项目等级:

AUX_RGBImageRec *texture;

Object::Object(char* filename, char* texname, int num) {
tex_num = num;
is_loaded = false;
.... some vertex stuff here
texture = auxDIBImageLoadA(texname);
}

void Object::draw() {
if(!is_loaded) {
loadTexture();
is_loaded = true;
}
... vertex stuff again
void Object::loadTexture() {
GLuint *tex = new GLuint[10];
unsigned int names[10];
glGenTextures(1, tex);
glBindTexture(GL_TEXTURE_2D, tex[tex_num]);
cout << tex_num << endl;
// glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, 3,
texture->sizeX,
texture->sizeY,
0, GL_RGB, GL_UNSIGNED_BYTE,
texture->data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// free memory
delete tex;
cout << tex_num << endl;
}

最佳答案

为什么要动态分配纹理 ID 变量?为什么在需要时在 loadTexture 末尾删除它,以便在绘制时实际引用纹理? OpenGL 不会神奇地将纹理与几何本身相关联。

以下更改:

- Object::Object(char* filename, char* texname, int num) {
+ Object::Object(char* filename, char* texfilename) {

- tex_num = num;
is_loaded = false;
.... some vertex stuff here
- texture = auxDIBImageLoadA(texname);
+ loadTexture(texfilename);

}

class Object {
/*...*/
+ GLuint texID;
}

void Object::draw() {
-if(!is_loaded) {
- loadTexture();
- is_loaded = true;
- }

+ glBindTexure(GL_TEXTURE_2D, texID);
+ draw_geometry();
}

- void Object::loadTexture() {
+ void Object::loadTexture(char const * const texfilename) {

- GLuint *tex = new GLuint[10];
- unsigned int names[10];
- glGenTextures(1, tex);
- glBindTexture(GL_TEXTURE_2D, tex[tex_num]);
- cout << tex_num << endl;

+ glGenTexture(1, &texID);
+ glBindTexture(GL_TEXTURE_2D, texID);
+ cout << texID << endl;

+ // Image is a yet to implement class offering image loading
+ // in a RAII fashion.
+ Image img = Image::fromFile(texfilename);

- // glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
- glTexImage2D(GL_TEXTURE_2D, 0, 3,
- texture->sizeX,
- texture->sizeY,
- 0, GL_RGB, GL_UNSIGNED_BYTE,
- texture->data);

+ glPixelStorei(GL_UNPACK_ALIGNMENT, img.alignment());
+ glTexImage2D(GL_TEXTURE_2D, 0,
+ img.glinternalformat(), // don't use a channel count here!
+ img.width(),
+ img.height(),
+ 0,
+ img.glformat(),
+ img.gltype(),
+ img.data() );

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

- // free memory
- delete tex;
- cout << tex_num << endl;
+ cout << texID << endl;

}

关于c++ - OpenGL 中多个纹理的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15185121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com