Friday, April 24, 2009

Bitmap Effects Generic PixelShader Helper Class

Personally I'm into simple code. Code should be as simple as possible todo the job and no more complex then needed. Case in point. Unless there is a strong reason to write my own command structure in Silverlight I'm going to go MVP or pMVP until I can see in Silverlight that MVVM is not just extra work (ie as when they get it to work like it does in WPF). Keeping this in mind I have been playing with pixel shaders. I tried this kind of thing by hand from scratch in Silverlight 2 and using Stegmens editiable bitmap class I could 'kind of' make this work however it was WAY to complicated to be reasonable. However with Silverlight 3 we have PixelShader support so we are gold. I reviewed a number of samples and wrote a few of my own in Shazzam (very cool tool I might add) but the one thing that bugged me was having a zillion pixel shader class's for each '.ps' so I made this simple yet generic class to clean up my source tree.

this is what I want to be able todo:

<Image Source="../Img/kasiadavid.jpg" Grid.Column="1" >
<Image.Effect>
<hsl:Shader x:Name="TargetShader" SetEffect="Ripples" />
</Image.Effect>
</Image>

Here I want to set a dependency property, in this case 'SetEffect' to some key value that will case the control called 'Shader' from my HackingSilverlight library and based on that select some ps file designated.

Here is my class to implement my 'Shader':

public class Shader : ShaderEffect
{
public Shader() { }

public string SetEffect
{
get { return (string)GetValue(SetEffectProperty); }
set { SetValue(SetEffectProperty, value); }
}

public readonly DependencyProperty SetEffectProperty = DependencyProperty.Register("SetEffect", typeof(string), typeof(Shader), new PropertyMetadata(new PropertyChangedCallback(OnSetEffectChanged)));

private static void OnSetEffectChanged(DependencyObject DpObj, DependencyPropertyChangedEventArgs e)
{
ShaderEffect ThisElement = DpObj as ShaderEffect;

if (ThisElement != null)
{
((Shader)(ThisElement)).PixelShader = new PixelShader()
{
UriSource = new Uri("HackingSilverlightLibrary;component/PixelShaders/" + ((Shader)(ThisElement)).SetEffect + ".ps", UriKind.RelativeOrAbsolute)
};
}
}
}

as you can see this could break if there is not ps file with the key name but add a little error handling and your good. :)