Skip to content

Instantly share code, notes, and snippets.

@bgolus
Created April 6, 2019 18:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bgolus/c417fbbca71cdecd7dc3f747a6ff66d9 to your computer and use it in GitHub Desktop.
Save bgolus/c417fbbca71cdecd7dc3f747a6ff66d9 to your computer and use it in GitHub Desktop.
Visually stable constant screen space sized texture shader for Unity
Shader "Unlit/Stable Constant Texture Size"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float3 cameraPos : TEXCOORD2;
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
v2f vert (appdata v)
{
v2f o;
o.cameraPos = mul(UNITY_MATRIX_MV, v.vertex).xyz / unity_CameraProjection[0][0];
o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
// o.uv = v.uv;
o.uv = mul(unity_ObjectToWorld, v.vertex).xz;
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
float dist = length(i.cameraPos.xyz);
float x = log(dist)/log(2);
float2 _x = floor((x + float2(0.0, 1.0)) * 0.5) * 2.0 - float2(0.0, 1.0);
float2 scale = pow(2.0, _x);
float blend = abs(frac(x * 0.5) * 2.0 - 1.0);
float2 uv0 = i.uv / scale.x * _MainTex_ST.xy + frac(scale.x * float2(0.1251, 0.6157));
float2 uv1 = i.uv / scale.y * _MainTex_ST.xy + frac(scale.y * float2(0.7127, 0.1281));
fixed4 col0 = tex2D(_MainTex, uv0);
fixed4 col1 = tex2D(_MainTex, uv1);
fixed4 col = lerp(col0, col1, blend);
// apply fog
UNITY_APPLY_FOG(i.fogCoord, col);
return col;
}
ENDCG
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment