Port Shadertoy JPEG compression GLSL shader to Unreal Engine

Barti1
Sun, 03 Mar 2024 18:40:01 +0000
Asset Creation

Hi everyone,

I recently found a JPEG compression shader on shadertoy:

shadertoy.com

Shadertoy

Build shaders, share them, and learn from the best community.

I was wondering, if it is possible to translate the shader code from GLSL to HLSL and use it in a custom node in a post-processing material.

My approach would be to translate the individual code snippets from the different buffers into HLSL and create custom nodes from them. The variable ‘fragColor’ would probably be a ‘SceneTexture:PostProcessInput0’. I don’t understand how the different buffers work.

That was one of my failed attempts. Unfortunately, I keep getting compilation errors that I can’t resolve.

#define PI    3.14159265359
#define SQRT2 0.70710678118
#define NB_LEVELS 64.0
#define NB_FREQ    8

// Buffer B
float2 k = frac(fragCoord.xy / 8.0) - float2(0.5, 0.5);
float2 K = fragCoord.xy - float2(0.5, 0.5) - k;
float3 val = float3(0.0, 0.0, 0.0);

for (int x = 0; x < 8; ++x)
{
    for (int y = 0; y < 8; ++y)
    {
        float2 uv = (K + float2(x, y) + float2(0.5, 0.5)) / iResolution.xy;
        float2 freq = float2(x, y) + float2(0.5, 0.5);

        val += tex2D(iChannel0, uv).rgb *
               cos(PI * k.x * freq.x / 8.0) * cos(PI * k.y * freq.y / 8.0) *
               ((k.x < 0.5) ? SQRT2 : 1.0) * ((k.y < 0.5) ? SQRT2 : 1.0);
    }
}

fragColor = float4(val / 4.0, 0.0);

// Buffer C
if (fragColor.x < 0.5)
{
    fragColor = round(fragColor / 8.0 * NB_LEVELS) / NB_LEVELS * 8.0;
}

// Buffer D
val = float3(0.0, 0.0, 0.0);
for (int u = 0; u < NB_FREQ; ++u)
{
    for (int v = 0; v < NB_FREQ; ++v)
    {
        float2 uv = (K + float2(u, v) + float2(0.5, 0.5)) / iResolution.xy;
        float2 freq = float2(u, v) + float2(0.5, 0.5);

        val += fragColor.rgb *
               cos(PI * (k.x + 0.5) * (freq.x / 8.0)) * cos(PI * (k.y + 0.5) * (freq.y / 8.0)) *
               ((u == 0) ? SQRT2 : 1.0) * ((v == 0) ? SQRT2 : 1.0);
    }
}

fragColor = float4(val / 4.0, 1.0);

// Result
return fragColor;

I have very little knowledge of shader programming. Therefore, I was hoping that someone could help me to steer in the right direction.

Thank you in advance!

3 posts - 2 participants