Skip to content

Instantly share code, notes, and snippets.

@zackthehuman
Created November 11, 2012 10:02
Show Gist options
  • Save zackthehuman/4054347 to your computer and use it in GitHub Desktop.
Save zackthehuman/4054347 to your computer and use it in GitHub Desktop.
Color/palette cycling using GLSL (example in SFML)
uniform sampler2D texture;
uniform sampler2D colorTable;
uniform float paletteIndex;
void main()
{
vec2 pos = gl_TexCoord[0].xy;
vec4 color = texture2D(texture, pos);
vec2 index = vec2(color.r + paletteIndex, 0);
vec4 indexedColor = texture2D(colorTable, index);
gl_FragColor = indexedColor;
}
#include <cstdlib>
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
int main(int argc, char *argv[]) {
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML/OpenGL color cycling effects");
sf::Texture texture;
if(!texture.loadFromFile("rock-abpp.png")) {
return EXIT_FAILURE;
}
sf::Texture colorTableTexture;
if(!colorTableTexture.loadFromFile("color-mappings.png")) {
return EXIT_FAILURE;
}
sf::Sprite sprite(texture);
sprite.setScale(10.0f, 10.0f);
sprite.setPosition(
(window.getSize().x / 2) - (sprite.getGlobalBounds().width / 2),
(window.getSize().y / 2) - (sprite.getGlobalBounds().height / 2)
);
sf::Shader shader;
shader.loadFromFile("blur.frag", sf::Shader::Fragment);
int paletteIndex = 0;
int numPalettes = 9;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
if( event.type == sf::Event::KeyPressed ) {
if(event.key.code == sf::Keyboard::R) {
std::cout << "Reloading shader..." << std::endl;
shader.loadFromFile("cycle.frag", sf::Shader::Fragment);
}
// Move "left" through the palettes
if(event.key.code == sf::Keyboard::Comma) {
paletteIndex--;
}
// Move "right" through the palettes
if(event.key.code == sf::Keyboard::Period) {
paletteIndex++;
}
}
}
// Wrap around the palettes!
if(paletteIndex >= numPalettes) {
paletteIndex = 0;
} else if(paletteIndex < 0) {
paletteIndex = numPalettes - 1;
}
shader.setParameter("colorTable", colorTableTexture);
shader.setParameter("paletteIndex", static_cast<float>(paletteIndex) * 6.0f/256.0f);
window.clear(sf::Color::Magenta);
sf::RenderStates states;
states.shader = &shader;
window.draw(sprite, states);
window.display();
}
return EXIT_SUCCESS;
}
@gamepopper
Copy link

Do you have an example color table texture?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment