在我的游戏中,当“时间”处于活动状态时,它会在5个小时后崩溃。当它运行时,它正常工作,直到它开始显示不正确的时间(原因未知),并且由于分段故障它会在5“小时后崩溃。这很奇怪,因为以前没有这样的东西,它应该一遍又一遍地做同样的事情。这是我的代码。试着告诉我是否存在随着时间的推移可能发生内存泄漏的地方。顺便说一下,“time_tick()”出现在每个“while”循环中。
struct global_struct
{
int seconds;
int minutes;
int hours;
TTF_Font * font;
SDL_Color font_color;
SDL_Color bk_color;
};
global_struct global;
void GL_RENDER_TTF(const char * Text, TTF_Font * Font, SDL_Color Textcolor, SDL_Color bk_color, int x, int y, float depth)
{
SDL_Surface * surface;
int w;
int h;
if(!(Font == NULL))
{
surface = TTF_RenderUTF8_Shaded(Font,Text,Textcolor,bk_color);
if(!(surface == NULL))
{
w = surface->w;
h = surface->h;
GLuint texture;
GLenum texture_format;
GLint nOfColors;
surface = SDL_DisplayFormatAlpha(surface);
nOfColors = surface->format->BytesPerPixel;
if (nOfColors == 4)
{
if (surface->format->Rmask == 0x000000ff)
texture_format = GL_RGBA;
else
texture_format = GL_BGRA;
}
else if (nOfColors == 3)
{
if (surface->format->Rmask == 0x000000ff)
texture_format = GL_RGB;
else
texture_format = GL_BGR;
}
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D( GL_TEXTURE_2D, 0, nOfColors, surface->w, surface->h, 0, texture_format, GL_UNSIGNED_BYTE, surface->pixels );
glBindTexture(GL_TEXTURE_2D, texture);
glBegin(GL_QUADS);
glTexCoord2f(0.0f,0.0f); glVertex3f(x,y,depth);
glTexCoord2f(1.0f,0.0f); glVertex3f(x+w,y,depth);
glTexCoord2f(1.0f,1.0f); glVertex3f(x+w,y+h,depth);
glTexCoord2f(0.0f,1.0f); glVertex3f(x,y+h,depth);
glEnd();
};
};
};
void time_tick(float depth1)
{
global.seconds = global.seconds + 1;
if(global.seconds > 59)
{
global.seconds = 0;
global.minutes = global.minutes + 1;
};
if(global.minutes > 59)
{
global.minutes = 0;
global.hours = global.hours + 1;
};
if(global.hours > 23)
{
global.hours = 0;
};
string time;
string shours;
string sminutes;
string sseconds;
stringstream ssseconds;
stringstream ssminutes;
stringstream sshours;
ssseconds << global.seconds;
ssminutes << global.minutes;
sshours << global.hours;
if(global.hours < 10)
{
shours = "0"+sshours.str();
}
else
{
shours = sshours.str();
};
if(global.minutes < 10)
{
sminutes = "0"+ssminutes.str();
}
else
{
sminutes = ssminutes.str();
};
if(global.seconds < 10)
{
sseconds = "0"+ssseconds.str();
}
else
{
sseconds = ssseconds.str();
};
time = "time: "+shours+"h "+sminutes+"m "+sseconds+"s";
GL_RENDER_TTF(time.c_str(),global.font,global.font_color,global.bk_color,0,0,depth1);
SDL_Delay(10);
};
答案 0 :(得分:2)
每当你调用RENDER_TTF
时,你都会创建一个新的纹理,而前一个纹理的纹理仍然存在。如果可以使用恒定的纹理大小,请使用glTexSubImage2D
替换纹理内容。否则,在创建新纹理之前,使用glDeleteTextures
释放唯一的纹理。
您也可以重新使用纹理ID,只需在绑定旧纹理对象的情况下重新调用glTexImage2D
(即没有glGenTextures
,但最近版本的OpenGL和glTexStorage
不鼓励这样做。完全不允许它。)