Created
August 11, 2020 13:56
-
-
Save FreyaHolmer/e0a2fffe4c94440dfaaff07ea50f2d67 to your computer and use it in GitHub Desktop.
Alpha blending comparisons
This file contains 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
// alpha blending test | |
// more info: https://twitter.com/FreyaHolmer/status/1293163103035817985 | |
// add this script to an object in the scene, | |
// then edit src and dst to see - will it blend? | |
using UnityEngine; | |
[ExecuteAlways] | |
public class BlendTest : MonoBehaviour { | |
public Color src, dst; // modify these and see what happens to the ones below | |
public Color outSimpleAlphaBlend; | |
public Color outHackAlphaBlend; | |
public Color outReference; | |
public void Update() { | |
outSimpleAlphaBlend = SimpleAlphaBlending( src, dst ); | |
outHackAlphaBlend = HackyAlphaBlending( src, dst ); | |
outReference = CorrectAlphaBlending( src, dst ); | |
} | |
// rgba: SrcAlpha OneMinusSrcAlpha | |
static Color SimpleAlphaBlending( Color src, Color dst ) => src * src.a + dst * ( 1 - src.a ); | |
// rgb: SrcAlpha OneMinusSrcAlpha | |
// a: One OneMinusSrcAlpha | |
static Color HackyAlphaBlending( Color src, Color dst ) { | |
Color o = SimpleAlphaBlending( src, dst ); // same as simple for rgb | |
o.a = src.a + dst.a * ( 1 - src.a ); | |
return o; | |
} | |
// reference/correct alpha blending | |
// (there is no simple blend mode equivalent) | |
static Color CorrectAlphaBlending( Color src, Color dst ) { | |
Color o = default; | |
o.a = src.a + dst.a * ( 1 - src.a ); | |
if( o.a <= 0 ) | |
return new Color( 0, 0, 0, 0 ); | |
for( int i = 0; i < 3; i++ ) // thanks Unity for no swizzling >:I | |
o[i] = ( src[i] * src.a + dst[i] * dst.a * ( 1 - src.a ) ) / o.a; | |
return o; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment