Shaders in Love2D

Showcase your libraries, tools and other projects that help your fellow love users.
Post Reply
User avatar
darkfrei
Party member
Posts: 1250
Joined: Sat Feb 08, 2020 11:09 pm

Shaders in Love2D

Post by darkfrei »

Hi all! Do you have nice simple examples of the shaders?

I want to show something that I've made.

The shader to make the image made with one color, from black to white with the chosen middle color. I think it looks like the pen ink drawing.
The black will be black, the white will be white, but all gray shades are tinted.

main.lua:

Code: Select all

local shaderCode = [[
extern vec3 colorA;
extern vec3 colorB;
extern vec3 colorC;

vec3 projectOnSegment(vec3 p, vec3 a, vec3 b) {
    vec3 ab = b - a;
    float t = dot(p - a, ab) / dot(ab, ab);
    return a + t * ab;
}

vec4 effect(vec4 color, Image texture, vec2 uv, vec2 screenCoords) {
    vec4 pixel = Texel(texture, uv);
    vec3 p = pixel.rgb;
    
    // projection of the point onto the segments AB and BC
    vec3 projAB = projectOnSegment(p, colorA, colorB);
    vec3 projBC = projectOnSegment(p, colorB, colorC);

    // calculate relative 't' along the whole A->B->C line
    float lenAB = length(colorB - colorA);
    float lenBC = length(colorC - colorB);
    float totalLen = lenAB + lenBC;
    
    float tAB = length(projAB - colorA) / totalLen;
    float tBC = (lenAB + length(projBC - colorB)) / totalLen;
    
    float t = (length(p - colorA) / length(colorC - colorA));
    
    // mix colors based on the adjusted 't' value
    vec3 finalColor = mix(projAB, projBC, t);
    
    return vec4(finalColor, pixel.a);
}
]]


function love.load()
	image = love.graphics.newImage ('image.jpg')
	width, height = image:getDimensions ()
	love.window.setMode (width*2, height)
	shader = love.graphics.newShader(shaderCode)

	-- send colors to the shader
	shader:send('colorA', {0, 0, 0})
	shader:send('colorB', {0.4, 0.0, 0.8})
	shader:send('colorC', {1, 1, 1})
end


function love.draw()
	love.graphics.draw(image)
	love.graphics.setShader(shader)
	love.graphics.draw(image, width, 0)
	love.graphics.setShader()
end
2025-03-03T18_31_04-Untitled.png
2025-03-03T18_31_04-Untitled.png (874.42 KiB) Viewed 488 times
Attachments
License CC0 (public domain)
License CC0 (public domain)
image.jpg (223.09 KiB) Viewed 488 times
:awesome: in Lua we Löve
:awesome: Platformer Guide
:awesome: freebies
User avatar
dusoft
Party member
Posts: 765
Joined: Fri Nov 08, 2013 12:07 am
Location: Europe usually
Contact:

Re: Shaders in Love2D

Post by dusoft »

Moonshine has good starter selection:
https://github.com/vrld/moonshine

and there was a forum thread that I am unable to find now where users would post their shader code.

Edit: this one: viewtopic.php?t=3733&start=320
Post Reply

Who is online

Users browsing this forum: No registered users and 3 guests