-
-
Save belzecue/0f5d20652376efd93ee8ab21cae3f85d to your computer and use it in GitHub Desktop.
Dithering Image Effect For Unity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Shader "Hidden/Dither" | |
{ | |
Properties | |
{ | |
_MainTex ("Texture", 2D) = "white" {} | |
} | |
SubShader | |
{ | |
Cull Off ZWrite Off ZTest Always | |
Pass | |
{ | |
CGPROGRAM | |
#pragma vertex vert | |
#pragma fragment frag | |
#include "UnityCG.cginc" | |
struct appdata | |
{ | |
float4 vertex : POSITION; | |
float2 uv : TEXCOORD0; | |
}; | |
struct v2f | |
{ | |
float2 uv : TEXCOORD0; | |
float4 vertex : SV_POSITION; | |
}; | |
v2f vert (appdata v) | |
{ | |
v2f o; | |
o.vertex = UnityObjectToClipPos(v.vertex); | |
o.uv = v.uv; | |
return o; | |
} | |
sampler2D _MainTex; | |
int _ColourDepth; | |
float _DitherStrength; | |
static const float4x4 ditherTable = float4x4 | |
( | |
-4.0, 0.0, -3.0, 1.0, | |
2.0, -2.0, 3.0, -1.0, | |
-3.0, 1.0, -4.0, 0.0, | |
3.0, -1.0, 2.0, -2.0 | |
); | |
fixed4 frag (v2f i) : SV_TARGET | |
{ | |
fixed4 col = tex2D(_MainTex,i.uv); | |
uint2 pixelCoord = i.uv*_ScreenParams.xy; //warning that modulus is slow on integers, so use uint | |
col += ditherTable[pixelCoord.x % 4][pixelCoord.y % 4] * _DitherStrength; | |
return round(col * _ColourDepth) / _ColourDepth; | |
} | |
ENDCG | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
[ExecuteInEditMode, ImageEffectAllowedInSceneView, RequireComponent(typeof(Camera))] | |
public class DitherEffect : MonoBehaviour | |
{ | |
public Material ditherMat; | |
[Range(0.0f, 1.0f)] | |
public float ditherStrength = 0.1f; | |
[Range(1, 32)] | |
public int colourDepth = 4; | |
private void OnRenderImage(RenderTexture src, RenderTexture dest) | |
{ | |
ditherMat.SetFloat("_DitherStrength", ditherStrength); | |
ditherMat.SetInt("_ColourDepth", colourDepth); | |
Graphics.Blit(src, dest, ditherMat); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment