Skip to content

Instantly share code, notes, and snippets.

@maluoi
Created February 2, 2021 20:30
Show Gist options
  • Save maluoi/528a6d1cf8a83cf353be9afc880f5390 to your computer and use it in GitHub Desktop.
Save maluoi/528a6d1cf8a83cf353be9afc880f5390 to your computer and use it in GitHub Desktop.
Dither based transparent Unity shader that preserves overlapping features.
Shader "Unlit/Dither Transparent" {
Properties {
_Color ("Color", Color) = (1,1,1,1)
_Offset ("Dither Depth Offset", Range(1,100)) = 40
}
SubShader {
Tags { "RenderType"="Opaque" }
LOD 100
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile_instancing
#include "UnityCG.cginc"
struct appdata {
float4 vertex : POSITION;
float3 normal : NORMAL0;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f {
float light : COLOR0;
float4 vertex : SV_POSITION;
UNITY_VERTEX_OUTPUT_STEREO
};
float4 _Color;
float _Offset;
// Dither code based on examples from:
// https://www.shadertoy.com/view/MslGR8
//note: returns [-intensity;intensity[, magnitude of 2x intensity
//note: from "NEXT GENERATION POST PROCESSING IN CALL OF DUTY: ADVANCED WARFARE"
// http://advances.realtimerendering.com/s2014/index.html
float InterleavedGradientNoise( float2 uv ) {
const float3 magic = float3( 0.06711056, 0.00583715, 52.9829189 );
return frac( magic.z * frac( dot( uv, magic.xy ) ) );
}
v2f vert (appdata v) {
v2f o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_OUTPUT(v2f, o);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.vertex = UnityObjectToClipPos(v.vertex);
// This is a fast/simple lighting trick, surfaces facing the
// camera are bright, and edges facing away from the camera get
// darker. "0.4" is minimum brightness, and "0.6" is "1-0.4"
float3 normal = mul((float3x3)unity_ObjectToWorld, v.normal);
o.light = dot(normalize(normal), normalize(WorldSpaceViewDir(v.vertex)))*0.6+0.4;
return o;
}
fixed4 frag(v2f i) : SV_Target {
if (InterleavedGradientNoise(i.vertex.xy + i.vertex.z*_Offset) > _Color.a)
discard;
return _Color * i.light;;
}
ENDCG
}
} }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment