我想加载纹理,然后让它们被多个对象使用。这样行得通吗?
class Sprite
{
GLuint* mTextures; // do I need this to also be a reference?
Sprite( GLuint* textures ) // do I need this to also be a reference?
{
mTextures = textures;
}
void Draw( textureNumber )
{
glBindTexture( GL_TEXTURE_2D, mTextures[ textureNumber ] );
// drawing code
}
};
// normally these variables would be inputed, but I did this for simplicity.
const int NUMBER_OF_TEXTURES = 40;
const int WHICH_TEXTURE = 10;
void main()
{
std::vector<GLuint> the_textures;
the_textures.resize( NUMBER_OF_TEXTURES );
glGenTextures( NUMBER_OF_TEXTURES, &the_textures[0] );
// texture loading code
Sprite the_sprite( &the_textures[0] );
the_sprite.Draw( WHICH_TEXTURE );
}有没有一种不同的方式,我应该这样做,即使它可以工作?
谢谢。
发布于 2011-01-02 18:56:46
例如,您可以使用纹理的全局实例:
textures.cpp:
static std::vector load_once_textures();
std::vector<GLuint> const& get_textures()
{
static std::vector<GLuint> const the_textures = load_once_textures();
return the_textures;
}
std::vector load_once_textures()
{
// loading
}textures.h
std::vector<GLuint> const& get_textures();这是一种简单的方法,而且足够安全,因为纹理将被加载一次,并且加载不存在静态初始化顺序不明确的问题
发布于 2011-01-02 13:39:23
这种特殊的情况应该是可行的。但是,一旦"the_textures“超出作用域,Sprite持有的指针就会失效。这将是相同的,即使它是一个参考。在这种情况下,我建议您将std::vector<>放在Sprite类中,并由该类实例拥有和管理它。
发布于 2011-01-02 18:45:16
我想知道为什么Draw不能只引用它正在绘制的对象。
class Sprite
{
public:
Sprite()
{
}
void Draw( GLuint & texture )
{
glBindTexture( GL_TEXTURE_2D, texture );
// drawing code
}
};中绘制的类型
这里可能存在多态:-你有不同的绘制算法-在绘制的不同类型的对象中有多态(虚拟)方法
因此Draw可能是一个虚方法,而GLuint可能是一个抽象基类,在这种情况下,实际的向量将不是对象的,而是指向不同类型对象的指针。
当然,您应该将绘制对象的方式与存储对象的方式解耦,因此在drawing类中存储一个向量,甚至传递一个假定它们在某种类型的数组中的指针都不太可能是一个好主意。
顺便说一下,main应该返回int而不是void。
https://stackoverflow.com/questions/4577291
复制相似问题