How to tile part of texture in fragment shader

1k Views Asked by At

Using Defold game engine and it forces textures in the atlas to be a power of 2 (384x216 -> 512x256). Defold doesn't have support for parallax background and only options are:

  1. Managing multiple sprite positioning with code
  2. Manage it with shader on a single sprite.

The first option is not an elegant and optimized way to do, so I go with option Nr.2.

I have a pretty simple shader code that takes the scale and offset of the initial sprite. It works if the sprite is in size of power of 2. But I have practically no knowledge more than this, so I don't know how to tile part of the texture (original not a power of 2). I can calculate and give a uniform that has proportions vec2(384/512, 216/256).

varying mediump vec2 var_texcoord0;
uniform lowp sampler2D texture_sampler;
uniform lowp vec4 tint;
uniform lowp vec4 scale;
uniform lowp vec4 offset;
void main()
{
   // Pre-multiply alpha since all runtime textures already are
   lowp vec2 uv = vec2(var_texcoord0.x *scale.x +offset.x, var_texcoord0.y *scale.y +offset.y);
   gl_FragColor = tint * texture2D( texture_sampler, uv);
}

I expect to get tiled background but it has empty space because of forced power of 2.

1

There are 1 best solutions below

0
On

So I got help in Defold community and ended up with fragment shader like this:

varying mediump vec2 var_texcoord0;

uniform lowp sampler2D texture_sampler;
uniform lowp vec4 tint;
uniform lowp vec4 size; //actually vec2 of pecentage (x,y)
uniform lowp vec4 scale;
uniform lowp vec4 offset;

void main()
{
    lowp vec2 uv = vec2(var_texcoord0.x *scale.x +offset.x, var_texcoord0.y *scale.y +offset.y);
    uv = vec2(mod(uv.x, size.x), mod(uv.y, size.y));
    gl_FragColor = tint * texture2D( texture_sampler, uv);
}