TableTower/ui/gradient_map.gd

44 lines
1.8 KiB
GDScript3
Raw Normal View History

class_name GradientMap
extends RefCounted
## Recolours greyscale art by how light each pixel is (a "gradient map"):
## black → the dark colour, middle grey → the trim colour, white → the trim
## made lighter. Alpha is kept. Card frames and thread strips use it, so one
## drawing works in every theme and every card or thread colour.
## `lo`: lightness at or below which a pixel is fully dark. `mid`: lightness
## that gives exactly the trim colour. `highlight`: how much lighter white is.
const SHADER_CODE := "shader_type canvas_item;
uniform vec4 dark : source_color;
uniform vec4 trim : source_color;
uniform vec4 light : source_color;
uniform float lo = 0.05;
uniform float mid = 0.5;
void fragment() {
vec4 art = texture(TEXTURE, UV);
float lightness = dot(art.rgb, vec3(0.299, 0.587, 0.114));
vec3 shade = mix(dark.rgb, trim.rgb, smoothstep(lo, mid, lightness));
vec3 shine = mix(trim.rgb, light.rgb, smoothstep(mid, 1.0, lightness));
COLOR = vec4(lightness <= mid ? shade : shine, art.a * COLOR.a);
}"
static var _shader: Shader
static var _materials: Dictionary = {}
## A shared material for these colours and stops.
static func material(dark: Color, trim: Color, lo: float = 0.05, mid: float = 0.5, highlight: float = 0.45) -> ShaderMaterial:
var key := "%s|%s|%s|%s|%s" % [dark.to_html(), trim.to_html(), lo, mid, highlight]
if not _materials.has(key):
if _shader == null:
_shader = Shader.new()
_shader.code = SHADER_CODE
var mat := ShaderMaterial.new()
mat.shader = _shader
mat.set_shader_parameter("dark", dark)
mat.set_shader_parameter("trim", trim)
mat.set_shader_parameter("light", trim.lightened(highlight))
mat.set_shader_parameter("lo", lo)
mat.set_shader_parameter("mid", maxf(mid, lo + 0.01))
_materials[key] = mat
return _materials[key]