I am trying to render a texture through a fragment shader to a SFML rectangle, but all I get is white color instead of the rendered texture.
here is the main file, which sets up a sfml window and prepare a sfml rectangle and shader:
#include <SFML/Graphics.hpp>
#include <iostream>
int main() {
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Shader Test");
window.setFramerateLimit(60);
// Load texture
sf::Texture texture;
if (!texture.loadFromFile("n10249.jpg")) {
std::cerr << "Failed to load texture" << std::endl;
return -1;
}
// Load shader
sf::Shader shader;
if (!shader.loadFromFile("fragment_shader.frag", sf::Shader::Fragment)) {
std::cerr << "Failed to load shader." << std::endl;
return -1;
}
shader.setUniform("texture0", texture); // Set the texture uniform
// Create rectangle and set texture
sf::RectangleShape rect(sf::Vector2f(window.getSize().x, window.getSize().y));
rect.setTexture(&texture); // Set texture to rectangle
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw(rect, &shader); // Draw rectangle with shader
window.display();
}
return 0;
}
and here is the fragment shader:
#version 330 core
in vec2 TexCoords;
out vec4 FragColor;
uniform sampler2D texture0;
void main() {
vec4 texColor = texture(texture0, TexCoords);
FragColor = texColor; // Directly output the texture color
}