Achieve multisampling within a fragment shader

Goal: Render a texture that is known to always have a texel density of greater than 1 and that cannot possibly have mips, without aliasing. Do this in a shader, as opposed to scaling on the CPU, to achieve maximum quality for any given camera angle, by making each fragment sample and blend every texel that it represents.

Goal in pseudocode:

Vec2 sizeOfFragmentInUvSpace = getFragmentUvSize();
Vec2 minUV = uv - sizeOfFragmentInUvSpace * 0.5f;
Vec2 maxUV = uv + sizeOfFragmentInUvSpace * 0.5f;
Vec2 texelsPerFragment = getTexelDensity();
Vec2 stride = sizeOfFragmentInUvSpace / texelsPerFragment;
Color result;
for (float x = minUV.x; x < maxUV.x; x += stride.x)
for (float y = minUV.y; y < maxUV.y; y += stride.y)
    result += texture2D(_MainTex, Vec2(x, y))
result /= texelsPerFragment;

Question:

  • getFragmentUvSize and getTexelDensity made-up - what are the real-world equivalents?
  • This functionality might already be implemented at a lower level, such that it would be unnecessary to implement the pseudocode above - is there a built-in function for multi-sampling?

getFragmentUvSize’s real-world equivalent is vec2(ddx(uv.x), ddy(uv.y)).

getTexelDensity can be approximated as texelsPerFragment = fragmentUvSize × textureResolution. Or stride can just be derived directly as texelUvSize = 1 / textureResolution.

This is a valid way of making a multi-sample shader, however I’m not certain if it’s the most efficient.