我正在使用SFML来使用着色器渲染效果。我使用sf::RenderTexture对象来呈现我的效果,然后使用RenderWindow来显示它。
当我使用第一个的输出作为第二个的输入来渲染2个效果时,显示的图像将翻转。
例如,下面的代码将输入图像向上向下显示,我不明白为什么。我使用了SFML文档here中给出的着色器文件(我也在问题末尾复制了该文件)。
如果将l.33替换为l.34(已注释)或将l.42替换为l.43,则结果是正常的。复制输出纹理似乎可以解决问题。
为什么复制renderTexture的输出纹理可以解决此问题?另外,我想避免复制纹理,还有其他解决方案吗?
main.cpp
#include <iostream>
#include "SFML/Graphics.hpp"
using namespace std;
int main()
{
//Loading image
sf::Texture tex;
tex.loadFromFile("lena.png");
int s_x = tex.getSize().x;
int s_y = tex.getSize().y;
//loading shader;
sf::Shader shader;
shader.loadFromFile("shader.frag",sf::Shader::Fragment);
//Creating drawable object (rectangle) to be drawn by renderTextures
sf::VertexArray rect(sf::Quads,4);
rect[0].position = sf::Vector2f(0,0);
rect[1].position = sf::Vector2f(0,s_y);
rect[2].position = sf::Vector2f(s_x,s_y);
rect[3].position = sf::Vector2f(s_x,0);
rect[0].texCoords = sf::Vector2f(0.0,0.0);
rect[1].texCoords = sf::Vector2f(0.0,1.0);
rect[2].texCoords = sf::Vector2f(1.0,1.0);
rect[3].texCoords = sf::Vector2f(1.0,0.0);
//Render with the loaded image
shader.setParameter("texture", tex);
sf::RenderTexture renderTexture;
renderTexture.create(s_x,s_y);
renderTexture.clear();
renderTexture.draw(rect, &shader);
renderTexture.display();
//Rendering with the output from the first render
const sf::Texture& tex2 = renderTexture.getTexture();
//switching those lines displays a correct image
//sf::Texture tex2 = renderTexture.getTexture();
shader.setParameter("texture", tex2);
sf::RenderTexture renderTexture2;
renderTexture2.create(s_x,s_y);
renderTexture2.clear();
renderTexture2.draw(rect, &shader);
renderTexture2.display();
//displaying
const sf::Texture& tex3 = renderTexture2.getTexture();
//switching those lines displays a correct image
//sf::Texture tex3 = renderTexture2.getTexture();
sf::Sprite sprite(tex3);
sf::RenderWindow window(sf::VideoMode(s_x,s_y), "");
window.clear();
window.draw(sprite);
window.display();
char c;
std::cin>>c;
return 0;
}
shader.frag
uniform sampler2D texture;
void main()
{
// lookup the pixel in the texture
vec4 pixel = texture2D(texture, gl_TexCoord[0].xy);
// multiply it by the color
gl_FragColor = gl_Color * pixel;
}
最佳答案
前一阵子使用着色器时,我遇到了同样的问题:
http://en.sfml-dev.org/forums/index.php?topic=11178.msg77236
因为sf::RenderTexture产生的纹理被反转(由于FBO),所以纹理坐标被反转。
该行为是一致的,因此您可以解决该问题,并在使用RenderTextures时考虑将坐标反转。