0
votes

Hullo, I want to implement a simple 2D lighting technique in GLSL. My projection matrix is set up so that the top left corner of the window is (0, 0) and the bottom right is (window.width, window.height). I have one uniform variable in the fragment shader uniform vec2 lightPosition; which is currently set to the mouse position (again, in the same coordinate system). I have also calculated the distance from the light to the pixel.


I want to light up the pixel according to its distance from the light source. But here's the catch, I don't want to light it up more than its original color. For instance if the color of the pixel is (1, 0, 0 (red)), no matter how close the light gets to it, it will not change more that that, which adds annoying specularity. And the farther the light source moves away from the pixel, the darker I want it to get. I really feel that I'm close to getting what I want, but I just can't get it!


I would really appreciate some help. I feel that this is a rather simple code to implement (and I feel ashamed for not knowing it).

1
You have not really desrcibed what you are doing already, but the standard way to apply light to some material color is by per-channel multiplication, with the light values being in [0,1] or course.derhass
@derhass I think its clear enough. (s)he want to limit the lighting strength based form raw distance of fragment and light source... but example fragment code would not hurt to shareSpektre

1 Answers

0
votes

why not scale up the distance to <0..1> range by dividing it and max it by some max visibility distance vd so:

d = min( length(fragment_pos-light_pos) , vd ) / vd;

that should get you <0..1> range for the distance of fragment to light. Now you can optionaly perform simple nonlinearization if you want (using pow which does not change the range...)

d = pow(d,0.5);

or

d = pow(d,2.0);

depending on what you think looks better (you can play with the exponent ...) and finally compute the color:

col = face_color * ((1.0-d)*0.8 + 0.2);

where 0.8 is your lightsource strength and 0.2 is ambient lighting.