Skip to content

Instantly share code, notes, and snippets.

@meshula
Created February 20, 2020 03:42
Show Gist options
  • Save meshula/bc90929f0534094f8febebb71fad58b7 to your computer and use it in GitHub Desktop.
Save meshula/bc90929f0534094f8febebb71fad58b7 to your computer and use it in GitHub Desktop.
letterbox and nearest resampling in a shader
kernel void
nearestKernel(texture2d<float, access::read> inTexture [[texture(AAPLTextureIndexInput)]],
texture2d<float, access::write> outTexture [[texture(AAPLTextureIndexOutput)]],
constant ResizeParams &resizeParams [[buffer(0)]],
uint2 gid [[thread_position_in_grid]])
{
int input_width = inTexture.get_width();
int input_height = inTexture.get_height();
float origin_aspect = float(input_width) / float(input_height);
int output_width = outTexture.get_width();
int output_height = outTexture.get_height();
float new_aspect = float(output_width) / float(output_height);
float u_ratio, v_ratio;
float u_offset, v_offset;
if (origin_aspect < new_aspect)
{
u_ratio = float(output_width) * float(input_height) / (float(input_width) * float(output_height));
v_ratio = 1;
u_offset = (float(output_width) - float(input_width) * float(output_height) / float(input_height)) * 0.5;
v_offset = 0;
}
else
{
u_ratio = 1;
v_ratio = float(output_height) * float(input_width) / (float(input_height) * float(output_width));
u_offset = 0;
v_offset = (float(output_height) - float(input_height) * float(output_width) / float(input_width)) * 0.5;
}
float u = float(gid.x - u_offset) * u_ratio / float(output_width - 1);
float v = float(gid.y - v_offset) * v_ratio / float(output_height - 1);
int s = int(u * float(input_width));
int t = int(v * float(input_height));
if (s < 0 || t < 0 || s >= input_width || t >= input_height)
outTexture.write(float4(0,0,0,1), gid);
else
{
float4 sample = inTexture.read(uint2(s, t));
outTexture.write(sample, gid);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment