我正在为游戏制作一种ascii画布。我认为在cp437样式中使用ascii字形的spritesheet来绘制ascii艺术会更有效率。我需要一种方法来为字形的背景和前景着色,以便我使用片段着色器。使用着色器将我降至7 fps。不使用着色器,我得到大约131.
我做错了什么吗?循环遍历字符串向量(以及字符串中的每个字符)是否过于昂贵,计算表单上字形的位置,设置纹理位置,然后使用着色器为每个字符绘制精灵?
int main() {
sf::RenderWindow rt(sf::VideoMode(1280, 720), "Demo Game");
sf::Texture texture;
texture.loadFromFile("Resources/courier_8x16.png");
texture.setSmooth(false);
sf::Sprite sprite(texture);
sf::Shader shader;
shader.loadFromFile("cycle.frag", sf::Shader::Fragment);
shader.setUniform("texture", sf::Shader::CurrentTexture);
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
std::vector<std::string> chars = std::vector<std::string>(50, std::string(100, 'X'));
while (rt.isOpen())
{
processEvents();
timeSinceLastUpdate += clock.restart();
while (timeSinceLastUpdate > TimePerFrame)
{
timeSinceLastUpdate -= TimePerFrame;
processEvents();
update(TimePerFrame);
}
//render();
rt.clear();
for (int y = 0; y < chars.size(); y++)
{
for (int x = 0; x < chars[y].size(); x++)
{
//bg and fg colors will be in a 2D vector and used here
shader.setUniform("foreground", sf::Glsl::Vec4(std::Color.White));
shader.setUniform("background", sf::Glsl::Vec4(std::Color.Black));
//uses decimal value of char and dimensions
//to find location of appropriate glyph in sprite sheet
sprite.setTextureRect(sf::IntRect((chars[y][x] % 16) * 8, (chars[y][x] / 16) * 16, 8, 16));
sprite.setPosition(x * 8, y * 16);
rt.draw(sprite, &shader);
}
}
rt.display();
}
}
这是着色器代码:
//////cycle.frag
uniform vec4 foreground;
uniform vec4 background;
uniform sampler2D texture;
void main()
{
vec4 pixel = texture2D(texture, gl_TexCoord[0].xy);
if (pixel.r < .1)
pixel = background;
else
pixel = foreground;
gl_FragColor = pixel;
}
这里是精灵表:(所有段落符号只是占位符)