Skip to content

Commit

Permalink
Use texelFetch instead of texture for indexed mode shaders
Browse files Browse the repository at this point in the history
Fixes various weird issues when palettes have empty slots, and removes unnecessary calculations.
  • Loading branch information
OverloadedOrama committed Nov 22, 2024
1 parent d580523 commit 1dcb696
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 9 deletions.
2 changes: 1 addition & 1 deletion src/Shaders/Effects/Palettize.gdshader
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ vec4 swap_color(vec4 color) {

int n_of_colors = textureSize(palette_texture, 0).x;
int color_index = find_index(color, n_of_colors, palette_texture);
return texture(palette_texture, vec2(float(color_index) / float(n_of_colors), 0.0));
return texelFetch(palette_texture, ivec2(color_index, 0), 0);
}

void fragment() {
Expand Down
3 changes: 1 addition & 2 deletions src/Shaders/FindPaletteColorIndex.gdshaderinc
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ int find_index(vec4 color, int n_of_colors, sampler2D palette_texture) {
int color_index = 0;
float smaller_distance = distance(color, texture(palette_texture, vec2(0.0)));
for (int i = 0; i <= n_of_colors; i++) {
vec2 uv = vec2(float(i) / float(n_of_colors), 0.0);
vec4 palette_color = texture(palette_texture, uv);
vec4 palette_color = texelFetch(palette_texture, ivec2(i, 0), 0);
float dist = distance(color, palette_color);
if (dist < smaller_distance) {
smaller_distance = dist;
Expand Down
10 changes: 5 additions & 5 deletions src/Shaders/IndexedToRGB.gdshader
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@ uniform sampler2D palette_texture : filter_nearest;
uniform sampler2D indices_texture : filter_nearest;

void fragment() {
float index = texture(indices_texture, UV).r;
float index = texture(indices_texture, UV).r * 255.0;
if (index <= EPSILON) { // If index is zero, make it transparent
COLOR = vec4(0.0);
}
else {
float n_of_colors = float(textureSize(palette_texture, 0).x);
index -= 1.0 / 255.0;
float index_normalized = ((index * 255.0)) / n_of_colors;
if (index_normalized + EPSILON < 1.0) {
COLOR = texture(palette_texture, vec2(index_normalized + EPSILON, 0.0));
index -= 1.0;
float index_normalized = index / n_of_colors;
if (index < n_of_colors) {
COLOR = texelFetch(palette_texture, ivec2(int(index), 0), 0);
}
else {
// If index is bigger than the size of the palette, make it transparent.
Expand Down
2 changes: 1 addition & 1 deletion src/Shaders/SetIndices.gdshader
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ uniform sampler2D palette_texture : filter_nearest;

void fragment() {
vec4 color = texture(rgb_texture, UV);
if (color.a <= 0.01) {
if (color.a <= 0.0001) {
COLOR.r = 0.0;
}
else {
Expand Down

0 comments on commit 1dcb696

Please sign in to comment.