gpt4 book ai didi

c - 如何优化此功能? (使用几乎所有的处理能力)

转载 作者:太空宇宙 更新时间:2023-11-04 05:11:04 24 4
gpt4 key购买 nike

我正在编写一个小游戏来自学 OpenGL 渲染,因为这是我尚未解决的事情之一。我以前使用过 SDL,同样的功能虽然仍然表现不佳,但并没有像现在这样夸张。

基本上,我的游戏中还没有太多内容,只是一些基本的 Action 和背景绘制。当我切换到 OpenGL 时,它似乎方式太快了。我的每秒帧数超过 2000,此功能占用了大部分处理能力。

有趣的是,它的 SDL 版本中的程序使用了 100% 的 CPU,但运行流畅,而 OpenGL 版本仅使用了大约 40% - 60% 的 CPU,但似乎对我的显卡造成了负担,以至于我的整个桌面变得 react 迟钝。不好。

这不是一个太复杂的函数,它根据玩家的 X 和 Y 坐标渲染一个 1024x1024 的背景图 block ,以在玩家图形本身锁定在中心时给人以移动的印象。因为它是大屏幕的小图 block ,所以我必须多次渲染它才能将图 block 拼接在一起以获得完整的背景。下面代码中的两个 for 循环迭代 12 次,合并,所以我可以理解为什么每秒调用 2000 次时这无效。

言归正传,这就是作恶者:

void render_background(game_t *game)
{
int bgw;
int bgh;

int x, y;

glBindTexture(GL_TEXTURE_2D, game->art_background);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &bgw);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &bgh);

glBegin(GL_QUADS);

/*
* Start one background tile too early and end one too late
* so the player can not outrun the background
*/
for (x = -bgw; x < root->w + bgw; x += bgw)
{
for (y = -bgh; y < root->h + bgh; y += bgh)
{
/* Offsets */
int ox = x + (int)game->player->x % bgw;
int oy = y + (int)game->player->y % bgh;

/* Top Left */
glTexCoord2f(0, 0);
glVertex3f(ox, oy, 0);

/* Top Right */
glTexCoord2f(1, 0);
glVertex3f(ox + bgw, oy, 0);

/* Bottom Right */
glTexCoord2f(1, 1);
glVertex3f(ox + bgw, oy + bgh, 0);

/* Bottom Left */
glTexCoord2f(0, 1);
glVertex3f(ox, oy + bgh, 0);
}
}

glEnd();
}

如果我通过在游戏循环中调用 SDL_Delay(1) 人为地限制速度,我将 FPS 降低到 ~660 ± 20,我不会得到“性能矫枉过正”。但我怀疑这是继续进行此操作的正确方法。

为了完成,这些是我的一般渲染和游戏循环函数:

void game_main()
{
long current_ticks = 0;
long elapsed_ticks;
long last_ticks = SDL_GetTicks();

game_t game;
object_t player;

if (init_game(&game) != 0)
return;

init_player(&player);
game.player = &player;

/* game_init() */
while (!game.quit)
{
/* Update number of ticks since last loop */
current_ticks = SDL_GetTicks();
elapsed_ticks = current_ticks - last_ticks;

last_ticks = current_ticks;

game_handle_inputs(elapsed_ticks, &game);
game_update(elapsed_ticks, &game);

game_render(elapsed_ticks, &game);

/* Lagging stops if I enable this */
/* SDL_Delay(1); */
}

cleanup_game(&game);


return;
}

void game_render(long elapsed_ticks, game_t *game)
{
game->tick_counter += elapsed_ticks;

if (game->tick_counter >= 1000)
{
game->fps = game->frame_counter;
game->tick_counter = 0;
game->frame_counter = 0;

printf("FPS: %d\n", game->fps);
}

render_background(game);
render_objects(game);

SDL_GL_SwapBuffers();
game->frame_counter++;

return;
}

根据 gprof 分析,即使我使用 SDL_Delay() 限制执行,它仍然花费大约 50% 的时间渲染我的背景。

最佳答案

开启垂直同步。这样一来,您计算图形数据的速度将与显示器呈现给用户的速度一样快,并且您不会浪费 CPU 或 GPU 周期来计算中间的额外帧,这些帧将被丢弃,因为显示器仍在忙于显示前一帧.

关于c - 如何优化此功能? (使用几乎所有的处理能力),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7221752/

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