Skip to content

Instantly share code, notes, and snippets.

@belzecue
Forked from josephbk117/Dither.shader
Created July 21, 2018 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save belzecue/0f5d20652376efd93ee8ab21cae3f85d to your computer and use it in GitHub Desktop.
Save belzecue/0f5d20652376efd93ee8ab21cae3f85d to your computer and use it in GitHub Desktop.
Dithering Image Effect For Unity
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
}
}
}
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