I am writing a fragment shader for a TileSet. In the shader I have the UV coordinates of the whole texture, however, I am interested in the UV coordinates of the current tile that is being rendered. In other words: in my shader I am interested to know where the current pixel is within the current tile, not within the whole texture.

So given the overall texture size and the rectangle that defines the tile to render within that texture, and given the UV coordinates of the current pixel corresponding to the whole texture, how can I convert these UV coordinates to the "inner" UV coordinates of the current tile, but also in the range of [0.0,1.0]?

Godot version 3.2.3 stable
in Engine

So I solved this now by first - in GDscript - calculate the ratio and offset values of the sprite to draw vs. the whole tile set texture. Then I instance create the shader material

var ratio = sprite.texture.get_size() / sprite.region_rect.size
var offset = sprite.region_rect.position / sprite.texture.get_size() * ratio
sprite.material = material

Then in the fragment shader itself I do the following to calculate the UV coordinates mapped to the current tile:

uniform vec2 ratio = vec2(0.0);
uniform vec2 offset = vec2(0.0);

void fragment() {
vec2 uv = UV * ratio - offset;
// do whatever you want with the mapped UVs ...
}

Hope that helps!

by (30 points)
+1 vote

I was beginning to think this was impossible in Godot 3.2, as I've been looking for a way to do this too, but I think I've found how to do it.

uniform vec2 node_size = vec2(400.0, 400.0);

varying vec2 vert;

void vertex(){
vert = VERTEX;
}

void fragment() {
vec2 full_uv = vert/node_size;
COLOR.rgb = vec3(full_uv, 0.0);
}

It seems that VERTEX divided by the size of a node will give you the UV of the node. You can use this to apply some shader across all tiles of a tilemap. Setting node_size to cell_size * cellquadrantsize will result in full_uv looping after every quadrant, so if you want a UV that stretches across the full tilemap you will have to set the quadrant to the number of tiles in the tilemap and be limited to square tilemaps. However this should be fine if you don't mind the UV not perfectly lining up with the shape of the map.

Hope this helps!

by (22 points)

Thanks for your reply. In the meantime I came up with my own solution, will post it here as reference.