Hi, I want to create something like lights with using the shaders, but I do not know how to use one shader with different properties on the same render texture. I want to use it like "cycle for". Please can you tell me how to do this or another way? And I have another problem, now when I am drawing background image to the render texture, it is flipped vertically.
My code
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
#include <cstring>
#include <vector>
class CLight
{
public:
sf::Vector2f position;
sf::Color color;
float radius;
CLight(sf::Vector2f pos, sf::Color col, float rad)
{
position = pos;
color = col;
radius = rad;
}
};
int main()
{
sf::RenderWindow App(sf::VideoMode(800,600,32),"SFML");
App.setFramerateLimit(60);
std::vector<CLight> lights;
lights.push_back(CLight(sf::Vector2f(400,300), sf::Color(128,128,128), 200.f));
sf::RenderTexture renderTexture;
renderTexture.create(800,600);
sf::Texture backTex;
backTex.loadFromFile("image.png");
backTex.setSmooth(false);
sf::Sprite background(backTex);
sf::Shader fragShader;
if(!fragShader.loadFromFile("light.frag",sf::Shader::Fragment))
App.close();
fragShader.setParameter("texture", backTex);
while(App.isOpen())
{
sf::Event event;
while(App.pollEvent(event))
{
if((event.type == sf::Event::Closed) || (event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
App.close();
}
float mouseX = float(sf::Mouse::getPosition(App).x);
float mouseY = float(sf::Mouse::getPosition(App).y);
std::cout<<mouseX<<" "<<mouseY<<std::endl;
App.clear();
renderTexture.clear();
fragShader.setParameter("lightRad", lights[0].radius);
fragShader.setParameter("lightPos", lights[0].position.x, 600.f-lights[0].position.y);
fragShader.setParameter("lightCol", lights[0].color.r/255.f, lights[0].color.g/255.f, lights[0].color.b/255.f);
sf::RenderStates shader(&fragShader);
renderTexture.draw(background, shader);
sf::Sprite drawTexture(renderTexture.getTexture());
App.draw(drawTexture);
App.display();
}
return 0;
}
Shader
uniform sampler2D texture;
uniform float lightRad; //radius
uniform vec2 lightPos; //position
uniform vec3 lightCol; //color
void main(void)
{
vec4 pixel = texture2D(texture, gl_TexCoord[0].xy);
float dis = 1.0f - distance(vec2(gl_FragCoord), lightPos) / lightRad;
vec4 light = vec4(lightCol.r,lightCol.g,lightCol.b,dis);
vec4 col = pixel + light;
gl_FragColor = vec4(col.xyz, dis);
}