Skip to content

Instantly share code, notes, and snippets.

@nickludlam
Last active May 16, 2023 22:57
Show Gist options
  • Save nickludlam/48b538ff77d75a8895d5ac9f6b3c5011 to your computer and use it in GitHub Desktop.
Save nickludlam/48b538ff77d75a8895d5ac9f6b3c5011 to your computer and use it in GitHub Desktop.
The equivalent to GetPixelBilinear() but using a NativeArray
private float4 GetPixelBilinearFromNativeArray(float2 uv, float size, NativeArray<half4> data)
{
float2 pixelLocation = uv * size;
float2 floorPixelLocation = math.floor(pixelLocation);
float2 ceilPixelLocation = floorPixelLocation + new float2(1, 1);
float xDistance = pixelLocation.x - floorPixelLocation.x;
float yDistance = pixelLocation.y - floorPixelLocation.y;
// Note: This assumes the texture is set to wrap, not clamp. We need a euclidean modulo for negative uv values
float2 floorPixelLocationWrapped = (floorPixelLocation % size + size) % size;
float2 ceilPixelLocationWrapped = (ceilPixelLocation % size + size) % size;
// Origin is top left, layout is:
// A B
// C D
int pixelAIndex = (int)floorPixelLocationWrapped.y * size + (int)floorPixelLocationWrapped.x; // x:floor y:floor
half4 pixelA = data[pixelAIndex];
int pixelBIndex = (int)floorPixelLocationWrapped.y * size + (int)ceilPixelLocationWrapped.x; // x:ceil y:floor
half4 pixelB = data[pixelBIndex];
int pixelCIndex = (int)ceilPixelLocationWrapped.y * size + (int)floorPixelLocationWrapped.x; // x:floor y:ceil
half4 pixelC = data[pixelCIndex];
int pixelDIndex = (int)ceilPixelLocationWrapped.y * size + (int)ceilPixelLocationWrapped.x; // x:ceil y:ceil
half4 pixelD = data[pixelDIndex];
float4 pixelAB = math.lerp(pixelA, pixelB, xDistance);
float4 pixelCD = math.lerp(pixelC, pixelD, xDistance);
float4 pixel = math.lerp(pixelAB, pixelCD, yDistance);
return pixel;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment