Blend Modes: Hue, Saturation, Color, and Luminosity with WPF 4.0

I’ve been toying with and working on this blend mode library of mine for some time now (see posts 1, 2, 3, 4, 5). However, it is now only with WPF 4.0 (currently Beta 2) … that I can actually implement all the blend modes.

Hue, Saturation, Color, and Luminosity: Where Are You?

If you were watching closely, you will have noticed that I have not (to date) implemented the Hue, Saturation, Color, and Luminosity blend mode effects.

Why is that? Whenever fxc.exe would compile the .fx file (through the Shader Effects BuildTask and Templates), it would give me the following two errors:

  • error X5608: Compiled shader code uses too many arithmetic instruction slots (100). Max. allowed by target (ps_2_0) is 64.
  • error X5609: Compiled shader code uses too many instruction slots (102). Max. allowed by the target (ps_2_0) is 96.

Those errors mean that you’ve exceeded the limitations of Pixel Shader 2.0 … which is what WPF 3.5 SP1 targets for pixel shader effects.

So, what can you do about this? You could optimize the HLSL so that your effect code goes under the limits … but if you notice in the errors above (these particular errors are for the Saturation effect) … you will see that I am significantly above the number of allowed arithmetic instruction slots (100 versus 64). I would have to optimize significantly.

WPF 4.0 to the Rescue

Another option is to utilize WPF 4.0!

WPF 4.0 increases what you can do with effects because it now allows you to target Pixel Shader 3.0. This wikipedia article has a great chart on the differences between the different shader models. With PS 3.0, we shouldn’t hit any limits.

Realizing this, as soon as Visual Studio 2010 and .NET 4 Beta 2 came out (PS 3.0 is only available in Beta 2), I installed it and gave it a whirl. There was really only one gotcha in getting this to work. The Shader Effects BuildTask only compiles to PS 2.0 … and there is no option to toggle between PS 2.0 and PS 3.0.

This means that, for now, probably until release, you will have to manually run fxc.exe (targeting ps_3_0) and add the compiled shader output file (the .ps file) to the project as a Resource.


There are some caveats to using PS 3.0 in WPF 4.0. Most notably, there is no software fallback if your hardware or situation (remote desktop, forced software rendering) don’t support it. This means that your effect code will simply not run and not appear.

Some good news is that Microsoft has extended the RenderCapability API so that you can determine what level of pixel shader support is currently available. They’ve updated the RenderCapability.IsPixelShaderVersionSupported method and have added two additional methods: RenderCapability.IsPixelShaderVersionSupportedInSoftware and RenderCapability.MaxPixelShaderInstructionSlots.

(The above information and more is available in David Teitlebaum’s PDC09 session titled Mastering WPF Graphics and Beyond. Jamie Rodriguez also has some great posts covering what’s new in WPF 4.0 (Beta 1, Beta 2).)

Another caveat that bears mentioning is that Silverlight (both 3.0 and 4.0) only support PS 2.0. So, if you are creating and using effects across both technologies, you will not be able to use PS 3.0. This also means that the Hue, Saturation, Color, and Luminosity blend modes (and the attached code) are WPF only blend modes. Sorry Silverlight! I love you, but that’s how the chips fall.

Hue, Saturation, Color, and Luminosity: Here They Are!

Alright … enough with the caveats! Let’s see the effects!

First, let me refer you back to Angie Bowen’s post where she covers what each blend mode does … including the Hue, Saturation, Color and Luminosity effects.

To show off what each effect does, I’m going to go ahead and use her reference images … first showing how they blend out of Photoshop … and then showing how they blend with my library … for comparison purposes. Why? Well, it seems as if my blend mode library does not always match what is coming out of Photoshop … sometimes it’s pretty darn close and at other times it’s more than just a little bit off.

I have been through and through the math (and HLSL) for these effects and I honestly can’t find anything wrong there. If I could speculate what is going on, I would say that I’m bumping up against some float versus double precision issues (where Photoshop is using doubles for greater precision) during the conversion from RGB to HSL and back. If you can figure out what I’ve done wrong (if anything) please let me know.

However, for the most part, they work great!

Hue Blend Mode

The result is the hue of the blend layer and the saturation and luminance of the base layer.



My Blend Mode Library




My Blend Mode Library


Saturation Blend Mode

The result is the saturation of the blend layer and the hue and luminance of the base layer.



My Blend Mode Library




My Blend Mode Library


Color Blend Mode

The result is luminance of the base layer and the hue and the saturation of the blend layer.



My Blend Mode Library




My Blend Mode Library


Luminosity Blend Mode

The result is hue and the saturation of the base layer and the luminosity of the blend layer.



My Blend Mode Library




My Blend Mode Library


The Binaries and the Source Code

Here is the source code for the library and here is the assembly.

Again, remember that this is a WPF-only release as Silverlight does not yet have support for Pixel Shader 3.0.

Also, all of these new blend modes are opacity aware … meaning that you can pull the opacity out of the upper layer to lessen the effect of the blend mode (see my last post on the matter).



At one point, I thought that the Shader Effects BuildTask and Templates was built into Visual Studio 2010. It appears I was mistaken about that. I have updated this post to indicate that.

Blend Modes: Now Opacity Aware

After I wrote my trio of blog posts (1, 2, 3) about blend modes using pixel shader effects, I was toying around with it …


The Problem

… and noticed that it didn’t handle an opacity changes on the upper layer (B).

In fact, this was brought to my attention by a great blog post by Angie Bowen. In it she explains how the blend modes work and, she says:

Remember that to get better results you can also adjust the opacity of the upper layer.

Trying it out, revealed that some of the blend modes were okay, but most were not. Most of the blend modes would simply result in a black square if you pulled all the opacity out of the upper layer (B). This was obviously wrong, for if you pull all the opacity out of the upper layer (B), you should get the lower layer (A).



The Solution

So, I dove back in on the blend mode math, trying to figure out what I needed to do to make these blend modes … opacity aware. That’s got a nice ring to it, doesn’t it!?

I started at the top of the list and got the NormalEffect working:

float4 main(float2 uv : TEXCOORD) : COLOR
    float4 inputColor;
    inputColor = tex2D(input, uv);

    float4 blendColor;
    blendColor = tex2D(blend, uv);

    inputColor.rgb = (1 - blendColor.a) * inputColor.rgb + blendColor.rgb;

    return inputColor;

Ok, the above math made sense. When the opacity of the upper layer (blendColor.a) was 1 (opaque), the result was just blendColor. Otherwise when the opacity of the upper layer was 0 (transparent), the result was inputColor.

So, I then started to tackle the darken blend modes (Darken, Multiply, …) and quickly ran into problems. It was at that point, that I ran into this post in the WPF Forum. My blend modes were rendering full black (not white), but it provided a crucial piece of knowledge.

Namely, WPF uses pre-multiplied alpha everywhere for performance reasons.

What does that mean? Well, it means that the RGB values for inputColor are already multiplied by the alpha value for inputColor and that the RGB values for blendColor are already multiplied by the alpha value for blendColor.

Ah! Do you see it? This explains why the blend modes were going to a black square when pulling the opacity out. Take the Multiply blend mode. In the above HLSL, it would be:

// R = Base * Blend
resultColor.rgb = inputColor.rgb * blendColor.rgb

So, if the alphas were pre-multiplied in and you were pulling opacity out of the blend (upper) layer … then blendColor.rgb would go to zero … which would cause resultColor to go to zero … which would cause the gradient square to go to black!

Thinking about this … brought about the general solution for making these blend modes opacity aware. I needed to simply:

  1. Un-pre-multiply the blend layer alpha value out.
  2. Apply the blend mode math.
  3. Then re-multiply the blend layer alpha value in again.
    Here is the HLSL for the opacity aware Multiply blend mode:
    float4 main(float2 uv : TEXCOORD) : COLOR
        float4 inputColor;
        inputColor = tex2D(input, uv);
        float4 blendColor;
        blendColor = tex2D(blend, uv);
        float4 resultColor;
        resultColor.a = inputColor.a;
        // un-premultiply the blendColor alpha out from blendColor
        blendColor.rgb = clamp(blendColor.rgb / blendColor.a, 0, 1);
        // apply the blend mode math
        // R = Base * Blend
        resultColor.rgb = inputColor.rgb * blendColor.rgb;
        // re-multiply the blendColor alpha in to blendColor
        // weight inputColor according to blendColor.a
        resultColor.rgb =
            (1 - blendColor.a) * inputColor.rgb +
            resultColor.rgb * blendColor.a;
        return resultColor;

    A few comments about the above code. Notice that I am clamp(ing) when I un-premultiply (i.e. divide) the alpha out. This assures that the RGB values will be between 0 and 1 (where 0 is black and 1 is white … HLSL operates in ScRGB color space). This is necessary since dividing by values close to 0 (blendColor.a) can yield large numbers or even positive infinity … which throws off the math.

Secondly, when I re-multiply the blend layer alpha value back in … I need to also properly weight the inputColor … just like I did in the NormalEffect above.

Finally, notice that I really don’t have worry about the opacity on the lower layer (A). I just pass its value off to the result by setting resultColor.a equal to inputColor.a.

Applying this general formula worked in all cases!


The Gradient Contour Test Harness

In order to verify that I was doing math correctly, and to see the effect of pulling the opacity out of the blend modes … I have built a new gradient test harness. I have called it the gradient contour test harness since it not only shows the A + B = R gradient squares but it also shows the R gradient square with contours … just like Paul Dunn’s post does when you mouse over the R squares.

It is extremely interesting (to me at least) watching the contours as you pull out the opacities.

For example, Here are three gradient contour squares for the Pin Light blend mode at opacity values of 1.0, 0.5, and 0.0:

Gradient Squares

Gradient Contour Squares


PinLight1.00nc PinLight1.00


PinLight0.50nc PinLight0.50


PinLight0.00nc PinLight0.00


I have also included a button labeled ‘Swap’ which swaps the A and B layers … since not all blend mode effects are commutative.

The gradient contours were made possible via Dwayne Need’s library. Check out the code (the class Grayscale4Bitmap) and see this post for more info.

The Image Test Harness

I’ve also put opacity sliders in the image test harnesses. Let’s take a look at the Pin Light effect at opacity values of 1.0, 0.5, and 0.3.


PinLightImage1.0 1.0
PinLightImage0.75 0.50
image 0.3

As you can see … pulling out the opacity … lessens the effect that the upper layer/texture has on the lower layer … and proves the truth of what Angie Bowen was saying earlier about using the opacity of the upper layer to achieve better results.


The Binaries and the Source Code (aka The Goods)

So, as I’m fond of saying … without further adieu … here is source code for the Blend Mode library and here are the library binaries … now opacity aware!

I also have updated the Silverlight test harness (as always you will need the Silverlight 3.0 runtime).


The gradient contour test harness is WPF only … you won’t find that on the Silverlight side. Maybe someday I’ll get my Silverlight test harnesses up to parity with what’s in the WPF test harnesses … but I can’t see when. Any one want to do it for me? Bueller? Bueller?

Blend Modes, Part III

After I gave you the blend mode library for both WPF and Silverlight, you thought, “Finally! I can do some really cool stuff … and what’s even better … it will run on the GPU!” Then, you started playing with it a little and you ran into some limitations.

In this third blog post in the series (Part 1 and Part 2), I will explore these limitations and show you how you can use Jeremiah Morrill’s GlassBehavior (which with his permission I have renamed to BackgroundEffectBehavior) to get around some of them.

Let’s jump in.

Sometimes you’ll have two images of the exact same size that you want to blend together using one of the blend modes in my library. That is:

<!-- Blending Two Images Together -->
                <ImageBrush ImageSource="Resources/fall_325x244.jpg"/>

The above is easy. As you can see, you just choose one of the images and set the blend mode effect on it. This actually causes that image to become the ‘A’ input (remember: A + B = R). Then, you simply set the ‘B’ input of the blend mode effect to the second image.

But it isn’t always that easy, is it?!

Many times when a designer is thinking of blend modes they aren’t thinking “Ok, I have two images and I want to blend those together.” They often are thinking, “I have this shape and I want to blend it into its background using a cool blend mode.”

Take a look at the following. Here I have a shape, a gray (#FF808080) ‘H’, on top of an image:


And, here I have the gray ‘H’, blended into its background image using the Color Burn blend mode:


Now, anywhere I move that ‘H’ … it is going to look different because it is being blended into its background, similar, of course, to making a shape transparent (although with different math).

So, how would I do this with the blend mode library that I’ve provided? Well, it would seem easy … and here is a valiant try:

<Grid Width="240" Height="150">
        <SolidColorBrush x:Key="solidColorBrush" Color="#FF808080"/>
            Data="(removed for clarity)"
            Fill="{DynamicResource solidColorBrush}"

        Source="Resources/MSwanson - Wide - Water 06.jpg"
                    <VisualBrush Visual="{StaticResource path}"/>

In the above, I am using the Image as the ‘A’ input and then passing the shape (Path) in as a VisualBrush for the ‘B’ input on the color burn blend mode effect. Here is what happens, though:


What is going on? Well, if you recall from Greg Schlecter’s series (1 and 2) on multi-input pixel shader effects (which is how the blend modes are implemented), the inputs have to be either a VisualBrush or an ImageBrush and the inputs have to be the same size. If they are not, the second input is resized to match the first input.

So, our ‘H’ path is getting sized bigger to match the image’s size and the parts outside of the path are taking part in the blending that is occurring (i.e. the dark areas outside the ‘H’) as well.

Greg Schlecter suggests (in the aforementioned articles) how you can solve the ‘resizing’ issue … by using the Viewbox property on the brush.

But, let’s take a step back here. Do we really want to apply the blend mode effect to the background? No, we don’t, as that would limit us to having only one effect per background. For that matter, it is also not very intuitive as you typically think of blending the shape into the background which suggests that it makes more sense to apply effect to the shape.

While thinking about how to solve this problem, I ran into this WPF forum post. I first thought, “Oh, no! I’m up a creek without a paddle.” But, then I dove in on Jeremiah Morrill’s GlassBehavior … and got it too work (at least for certain situations)!

(I’m not going to cover behaviors in this blog post, but they are basically something new with Expression Blend 3.x. They are an implementation of the attached property behavior pattern and allow the designer inside of Blend to drag and drop behaviors onto elements in the element tree. See here and here for more info.)

Jeremiah’s GlassBehavior is a behavior that let’s you apply an effect to the background underneath the element that you are attaching the behavior to. He uses it to apply a SmoothMagnifyEffect (to get a glass like appearance) … but you can really use it to apply any effect. And that is just what I did.

Take a look at this xaml:

    <Grid x:Name="grid">
            Source="Resources/MSwanson - Wide - Water 06.jpg"
    <Canvas Width="168.367" Height="152.44">
            Data="(removed for clarity)"
            Fill="{StaticResource solidColorBrush}"
                    Visual="{Binding ElementName=grid, Mode=OneWay}"

                                    Brush="{StaticResource solidColorBrush}"
                                        <RectangleGeometry Rect="0,0,1,1"/>


First of all, notice how the BackgroundEffectBehavior attaches to the Path through the attached property collection i:Interaction.Behaviors. This is how the behavior hooks its functionality into Path.

The BackgroundEffectBehavior’s Visual is set to the background (the grid which is holding the image) … and the BackgroundEffectBehavior’s Effect is set to the ColorBurnEffect which has a SolidColorBrush as its ‘B’ input. I also have the same SolidColorBrush set as the Fill of the Path … but this is just so that I can see it in the designer … as at runtime … this behavior kicks in and that Fill is not used.

This is what we get from the xaml above … but basically … success! 🙂


Now, a few caveats. 🙁 This whole thing seems to be very fragile.

For example, in order to get this to work, I had to put the image inside the grid … as a sibling to the Canvas that contains the ‘H’ path. Certain other ways of doing it didn’t work. For example, if I set the BackgroundEffectBehavior’s Visual to the grid which contains both the grid/image and the ‘H’ path … it doesn’t work.

Also, if you change the StaticResource(s) to DynamicResource(s) … it doesn’t work.

Another issue is that using this behavior inside of Blend … does not result in what-you-see-is-what-you-get (WYSIWYG) blending. That is why I also set the Fill of the Path above to the same SolidColorBrush that I used as my ‘B’ input to the color burn blend mode effect. In that way, at least, I can see the ‘H’ inside of Blend.

Finally, I have not done any performance analysis (yet) of this, but the BackgroundEffectBehavior uses two VisualBrush(es) to get its job done. So, if you use a lot of these, I wouldn’t be surprised if it starts slowing stuff down.

The best solution here, is really for Microsoft to bake blend modes into the platform. Unfortunately, blend modes will not be in next release of WPF (.NET 4.x) … but the good news is that Brendan Clark from Microsoft says he’s pushing for it.

Here is the code. Unfortunately, the BackgroundEffectBehavior is WPF-only right now (I hope to fix this), but I have updated the Silverlight test harness to have the gradient and image test harnesses. Enjoy!

Here is a live Silverlight 3 test harness (you will need the Silverlight 3.0 runtime, 3.0.40624).


p.s. I just want to give a shout-out to Mike Swanson and his wallpaper images. They rock. Period. The water droplet background I am using above is one of his.

Blend Modes for Silverlight

Given the great response to my series on Blend Modes … I decided to quickly convert the library so that it could be compiled for the Silverlight platform. I pretty much copied how the WPF Pixel Shader Effect Library did it. Oh, and I renamed a bunch of things too.

So, here it is … the new and improved blend mode effects library … now with a little Silverlight love!

p.s. And here are the WPF binaries and here are the Silverlight binaries.

p.s.s. I now have a live Silverlight test harness (you will need the Silverlight 3.0 runtime, 3.0.40624).

Blend Modes, Part II

In Part I of this series, I showed how I was able to eventually figure out how to create the Linear Burn blend mode effect and how to apply this effect to a Border element.

In Part II of this series, I am going to start off by showing how I was able to truly verify that I had written the Linear Burn blend mode effect correctly. And, then, I will share a few of the A + B = R gradient squares for a few of the blend modes that Paul Dunn’s post didn’t have. Finally, I will share the full blend mode effect library and the test harnesses that go with it.

So … here we go …

With the Linear Burn blend mode effect that I had created, it bothered me that the gradient that I had blended with the green … was white to gray … and not white to black as Robby’s post had shown. Was I doing things correctly? Was the HLSL that I written, right?

A little more searching and I ran into Paul Dunn’s post on Photoshop’s blend modes. Ah! Perfect! Exactly what I wanted, and sure enough, I had written Linear Burn correctly. Check out the screen shot below (from my test harness) and compare it to what you see on Paul Dunn’s post. A match. Whew!



At that point, I started creating and going through every blend mode in his blog post, verifying each along the way. This went along fine until I hit the Vivid Light blend mode. The math that he had just wasn’t working. I tried to figure out what was wrong with it, but eventually I ran into another post that had a different way of expressing the math … it was in HLSL! Plugging in this HLSL worked! And what’s better, he had some additional effects that could be added to the library I was creating. And, so, I finished it off.

Now, as mentioned above, mouaif’s post had some blend mode effects that Paul Dunn’s post didn’t show visually. And, so, I will share those here:

Glow Effect




Reflect Effect



Hard Mix Effect



Negation Effect



Phoenix Effect



Finally, Nathan’s post had a visual way of verifying things as well (near the bottom) and so I included in my test harness a window that let’s you apply the various blend mode effects to images from Nathan’s page. Here’s a screen shot of that window (with the Phoenix blend mode effect applied … which I think looks cool):

Test Harness Window (Images)


Without any further adieu, here’s the blend mode effects library and the test harness. All the same caveats apply to what you need on your machine to build the sample code (.NET 3.5 SP1, DirectX SDK, and the Shader Effects BuildTask and Templates from the WPF Futures stuff on CodePlex).

If you don’t want to build the library and test harness yourself … here are the binaries.

Also, I now have a live Silverlight test harness (you will need the Silverlight 3.0 runtime, 3.0.40624). 


p.s. Thanks to Kevin Moore for the Color Picker that I used in this sample code. I believe I created that Color Picker from an article he did at one point. In fact, I think that some variant of this Color Picker ended up in his Bag-o-Tricks.

Blend Modes, Part I

A while back (now some time ago), I was inspired by Robby Ingebretsen’s post on blend modes that were made possible with pixel shader effects, a new feature of .NET 3.5 SP1. In his post, he suggested that someone take a weekend and create a library of these effects for the community to use. Well, a little late, but I have eventually gotten around to this and done so … because I wanted to give a designer I work with some power tools that he is familiar with in applications like Photoshop.

In this trio (1, 2, 3) of blog posts, I will not be covering how to create a shader effect in WPF, Greg Schlecter has a great introductory series on that already. In particular, it is the multi-input shader effects that make blend modes possible, so be sure to read all the way through his series.

In order to write this library of blend mode effects, I first needed to find the math behind them. Then, I needed to convert this math into the proper HLSL. And finally, I needed some way to verify that the HLSL that I had written … was actually correct. I will cover these topics in the first two blog (first, second) posts.

In the third blog post, I will show how you can use Jeremiah Morrill’s GlassBehavior to blend two shapes with differing geometries.

So … let’s jump in.

I quickly started off with a simple Google search and it led me to Nathan Moinvaziri’s post which is all the blend mode math in C. So, I decided to buckle down and see if I could do Linear Burn … which is the subject of Robby’s post. Nathan had the math (for each channel) for Linear Burn as:

#define ChannelBlend_Subtract(B, L)
     ((uint8)((B + L < 255) ? 0 : (B + L – 255)))
#define ChannelBlend_LinearBurn(B, L)
     (ChannelBlend_Subtract(B, L))


Just plugging in the macro definitions into the .fx file didn’t work and through some trial and error, I discovered that the correct HLSL was:

inputColor.r = inputColor.r + blendColor.r - 1;
inputColor.g = inputColor.g + blendColor.g - 1;
inputColor.b = inputColor.b + blendColor.b - 1;


This finally gave me the blending Robby had talked about in his post:

Linear Burn

Following is the xaml for the above rectangle which is using the Linear Burn blend mode effect:

                                        <RectangleGeometry Rect="0,0,1,1"/>

As you can see above, it is rather easy to apply the blend mode effect. Each blend mode effect takes two shader effect inputs (where input is a shader effect sampler input).

The first input is the element it is set on which is in this case the Border element with the #FF6AB400 background.

The second input is the ImageBrush (it can also be a VisualBrush) that is set on the Texture property. Notice that the alpha channels for the GradientStop(s) are set 100% and not 50% like the Border with opacity overlay (see the attached code, .zip file below). That is, the two layers are being blended by the blend mode effect and not with opacity.

Another thing to mention is that the first input maps to A in the picture above and the second input maps to B in the picture above. R maps to the blend result which is what the user sees. In the next post, I will use this mapping (A + B = R) to illustrate what each blend mode effect does.

Here is the code for this post and here are the binaries. Also, I now have a live Silverlight test harness (you will need the Silverlight 3.0 runtime, 3.0.40624).


(To build the above sample code, you need .NET 3.5 SP1 and you need a version of the DirectX SDK installed on your machine. Besides all that, you must also install the Shader Effects BuildTask and Templates from the WPF Futures CodePlex site.)