SFML绘制像素数组

3
我在互联网上发现了这个教程(http://lodev.org/cgtutor/raycasting.html),很感兴趣想要自己尝试。虽然我想使用SFML来实现,并且想要扩展它,制作一个三维版本,这样玩家就可以在不同的层面上行走。因此,每个像素都需要1条光线,因此每个像素都必须独立绘制。我找到了这个教程(http://www.sfml-dev.org/tutorials/2.1/graphics-vertex-array.php),看起来很容易将数组设置为单独的顶点。首先,我觉得最好的方法是创建一个类,它可以读取由光线返回的像素,并将它们绘制到屏幕上。我使用了VertexArray,但奇怪的是事情并没有按预期工作。我试图分离出问题,但一直没有成功。我编写了一个简单的顶点数组,只有绿色像素可以填满部分屏幕,但仍然存在问题。像素只显示了我的代码和我想表达的图片。
#include "SFML/Graphics.hpp"  
int main() {
sf::RenderWindow window(sf::VideoMode(400, 240), "Test Window");
window.setFramerateLimit(30);
sf::VertexArray pointmap(sf::Points, 400 * 10);
for(register int a = 0;a < 400 * 10;a++) {
    pointmap[a].position = sf::Vector2f(a % 400,a / 400);
    pointmap[a].color = sf::Color::Green;
}
while (window.isOpen()) {
    sf::Event event;
    while (window.pollEvent(event)) {
        if (event.type == sf::Event::Closed)
        window.close();
    }
    window.clear();
    window.draw(pointmap);
    //</debug>
    window.display();
}
return 0;

}

http://oi43.tinypic.com/s5d9aw.jpg

我的意思是只用绿色填充前10行,但显然我没有做到...如果我能弄清楚是什么原因导致这个问题,我可能就能解决主要问题。如果你认为有更好的方法,请告诉我 :)

谢谢!


看起来是因为你使用了模数运算符“%”。 - ninMonkey
2个回答

7
我认为你误用了顶点数组。请看一下教程中表格中的sf::Quads原始图形:绘制四边形需要定义4个点(坐标),而一个像素只是一个边长为1的四边形。
所以你需要创建大小为400*10*4的顶点数组,并将相同的位置设置为每个后面的四个顶点。
你也可以使用SFML提供的另一种方法:直接逐像素绘制纹理并显示它。这可能不是最有效的方法(你需要与顶点比较),但它的优点是相当简单。
const unsigned int W = 400;
const unsigned int H = 10; // you can change this to full window size later

sf::UInt8* pixels = new sf::UInt8[W*H*4];

sf::Texture texture;
texture.create(W, H); 

sf::Sprite sprite(texture); // needed to draw the texture on screen

// ...

for(register int i = 0; i < W*H*4; i += 4) {
    pixels[i] = r; // obviously, assign the values you need here to form your color
    pixels[i+1] = g;
    pixels[i+2] = b;
    pixels[i+3] = a;
}

texture.update(pixels);

// ...

window.draw(sprite);

sf::Texture::update函数接受一个 sf::UInt8 数组,这些数字表示纹理每个像素的颜色。但是由于像素需要是 32位RGBA,所以在每个 sf::UInt8 后面会有 4 个 RGBA 分量。


0

替换这一行:

pointmap[a].position = sf::Vector2f(a % 400,a / 400);

使用:

pointmap[a].position = sf::Vector2f(a % 400,(a/400) % 400);

你能否添加一些解释说明为什么这个方法可以解决问题吗? - CertainPerformance

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接