Tuesday, 28 February 2012


I tried writing a shader today (Monday). Shaders have been part of Flash for a while, but as far as I know hardly any games use them. This is a shame as they can do things that are impossible in ActionScript, often with very little programming.

To get started download Pixel Bender Toolkit, from here, and install it. Then launch it and open up one of the many examples. They consist of a shader code in *.pbk files, initially unfamiliar but like many other intermediate level languages of the vector units of modern CPUs. A language reference PDF is provided but you may find you can learn enough simply from looking at the examples.

You use this to make your shader, editing it and testing it within the environment on static images (it can also be edited in a text editor). Once it's ready use 'Export Filter for Flash Player...' in the 'File' menu to save it as a *.pbj file.

This can't be added to a .fla based project, it has to be embedded as with other assets in Flex. A Shader is made from this, which is then used to make a Filter. I do this all at once at startup:

[Embed("../Art/filter.pbj", mimeType="application/octet-stream")]
private var filterClass:Class;
gShader = new Shader(new filterClass() as ByteArray);
gFilter = new ShaderFilter(gShader);

At runtime when it's needed it's added to a DisplayObject (actually a main Sprite containing most of the game) gMain:

datFilter = gFilter.shader.data;
datFilter.param2.value = [fVal1]
datFilter.param1.value = [fVal2];
datFilter.center.value = [fX, fY];
gMain.filters = [gFilter];

Then every frame until it's finished I update it as follows:

datFilter.param2.value = [fVal1]
datFilter.param1.value = [fVal2];
datFilter.center.value = [fX, fY];
gMain.filters = [gFilter];

I would like to avoid repeatedly adding it (the last line) but right now it only updates if I do that. It still runs in a frame though, doing something that would take many frames to do at all in ActionScript.

No comments:

Post a Comment