Skip to content

Instantly share code, notes, and snippets.

@Bradshaw
Last active August 29, 2015 13:59
Show Gist options
  • Save Bradshaw/10832930 to your computer and use it in GitHub Desktop.
Save Bradshaw/10832930 to your computer and use it in GitHub Desktop.
Palette shader
function love.load()
--[[Include this to initialise the shader]]
pltshader = love.graphics.newShader("palettise.fs")
-- Sending the colours from http://sharecart1000.com/img/SHARECART1000guide.png
pltshader:send("colors",
{148/256,146/256,76/256,1},
{73/256,84/256,65/256,1},
{4/256,174/256,204/256,1},
{148/256,74/256,28/256,1},
{60/256,136/256,38/256,1},
{252/256,254/256,252/256,1},
{95/256,57/256,31/256,1},
{108/256,250/256,220/256,1},
{144/256,144/256,158/256,1},
{50/256,45/256,35/256,1},
{28/256,62/256,68/256,1},
{220/256,198/256,124/256,1},
{28/256,70/256,36/256,1},
{164/256,218/256,196/256,1},
{4/256,92/256,156/256,1}
)
end
extern vec4 colors[15];
extern float ditherAmt;
// Magic number function
// Returns a value between 0 and 1
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
// Returns the square of the rgb distance
float dist32(vec4 a, vec4 b)
{
vec4 d = b-a;
return (d.r*d.r + d.g*d.g + d.b*d.b);
}
// Returns the rgb distance
//! sqrt is a hungry baby, do not over-use
float dist3(vec4 a, vec4 b)
{
return sqrt(dist32(a,b));
}
// Change this function for extra juicy
// Should return a value between -1 and 1
float jitterFunc(vec2 coord)
{
return sin((coord.x-coord.y)*1000);
}
// Gets the index of the closest colour to tested colour.
int getClosest(vec4 c, vec2 coord){
int res; // Result
float mindist = 10000; // rbg values have a maximum distance of sqrt(3) so this should be big enough
int i;
for (i = 0; i < 15; ++i)
{
float dist = dist3(c, colors[i]); // Use dist32() for better performance, but dodgy jittering
if (dist<mindist+ditherAmt*jitterFunc(coord)) // dither and jitter work together to break nasty lines
{
mindist = dist;
res = i;
}
}
return res;
}
vec4 effect( vec4 color, Image texture, vec2 texture_coords, vec2 screen_coords )
{
vec4 c = Texel(texture, texture_coords); // Get the ACTUAL colour
int i = getClosest(c, screen_coords); // Find the index of the closest colour
return colors[i]; // Return said closest colour
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment