Skip to content

Instantly share code, notes, and snippets.

@xphere
Created July 30, 2020 13:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xphere/75a9f56650f7163b26fdcda69a95fd30 to your computer and use it in GitHub Desktop.
Save xphere/75a9f56650f7163b26fdcda69a95fd30 to your computer and use it in GitHub Desktop.
Generates a gradient mapping to keep your game within a given palette colors.
shader_type canvas_item;
render_mode unshaded;
uniform bool enabled = true;
uniform sampler2D gradient: hint_black;
uniform vec3 greyscale = vec3(0.299, 0.587, 0.114);
void fragment() {
vec4 input_color = texture(TEXTURE, UV);
if (enabled) {
float greyscale_value = dot(input_color.rgb, greyscale);
vec3 sampled_color = texture(gradient, vec2(greyscale_value, 0.0)).rgb;
COLOR = vec4(sampled_color, input_color.a);
} else {
COLOR = input_color;
}
}
extends ViewportContainer
func _ready() -> void:
# Define your palette colors
var colors: = [
Color("#171219"),
Color("#251d35"),
Color("#2e2842"),
Color("#3e365d"),
Color("#5b5a84"),
Color("#7884ac"),
Color("#b3bcc3"),
Color("#ffffff"),
]
material.get("shader_param/gradient").gradient = posterized_gradient(colors)
func posterized_gradient(colors: Array, posterize: Vector3 = Vector3(0.299, 0.587, 0.114), gap: float = 0.5) -> Gradient:
var gradient: = Gradient.new()
gradient.set_color(0, colors[0])
gradient.set_color(1, colors[-1])
var last: = colors.size() - 1
for index in colors.size():
var color: = colors[index] as Color
var current: = posterize(color, posterize)
if index > 0:
var before: = posterize(colors[index - 1], posterize)
gradient.add_point(
before * gap - current * (gap - 1),
color
)
if index < last:
var after: = posterize(colors[index + 1], posterize)
gradient.add_point(
after * gap - current * (gap - 1),
color
)
return gradient
func posterize(color: Color, posterize: Vector3) -> float:
return posterize.dot(Vector3(color.r, color.g, color.b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment