- Home /
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
andgetTexelDensity
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?
Answer by Max-Pixel · Jun 21, 2019 at 06:18 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220612202032im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Local position in vertex shader? 1 Answer
Why doesn't this vertex+fragment shader work? 0 Answers
Fragment shader alpha 0 Answers
Can you specify both Surface and Vertex/Fragment shaders? 3 Answers
'discard' keyword cg error 1 Answer