• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
derrace

HLSL Pixel Shader that does palette swap

19 posts in this topic

Hi there,

I have implemented a simple pixel shader which can replace a particular colour in a sprite with another colour.

It looks something like this:

[CODE]

sampler input : register(s0);
float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
float4 colour = tex2D(input, coords);
if(colour.r == sourceColours[0].r &&
colour.g == sourceColours[0].g &&
colour.b == sourceColours[0].b) return targetColours[0];

return colour;
}
[/CODE]

What I would like to do is have the function take in 2 textures, a default table, and a lookup table (both same dimensions).
Grab the current pixel, and find the location XY (coords) of the matching RGB in the default table, and then substitute it with the colour found in the lookup table at XY.

I have figured how to pass the Textures from C# into the function, but I am not sure how to find the coords in the default table by matching the colour.

Could someone kindly assist?

Thanks in advance.
0

Share this post


Link to post
Share on other sites
Hmm, think I got it,

It involves using a for loop to cycle through the a variant of the above code but I am getting this silly error now =(

Shader uses texture addressing operations in a dependency chain that is too complex for the target shader model (ps_2_0) to handle.
0

Share this post


Link to post
Share on other sites
Use a 3D texture instead. That way instead of putting a for loop in your shader ( slow ), you take the color value, and use that value to look up a 3d texture that has the colours you want in it.
0

Share this post


Link to post
Share on other sites
If you're going to do this, it would be a whole lot simpler if the original sprite contained pallete-indices instead of colours.

You could pre-process your sprites once on the CPU to avoid having to execute that ridiculously huge loop in your pixel shader.

Then you'd just have to do "[font=courier new,courier,monospace]fetch sprite colour (which is an index), fetch colour from pallete at index[/font]", instead of "[font=courier new,courier,monospace]fetch sprite colour, search entire source pallets for colour to determine it's index, fetch colour from new pallete at index[/font]".
1

Share this post


Link to post
Share on other sites
Hey all, thanks for the replies.

[quote name='Kyall' timestamp='1353572011' post='5003164']
Use a 3D texture instead. That way instead of putting a for loop in your shader ( slow ), you take the color value, and use that value to look up a 3d texture that has the colours you want in it.
[/quote]

Hmm, that would require me to manually insert values into the 3rd dimension, if I have more more than 1 set of colours I want to change depending on the situation, I would need to store more than 1 look up value?


[quote name='Hodgman' timestamp='1353573681' post='5003168']
If you're going to do this, it would be a whole lot simpler if the original sprite contained pallete-indices instead of colours.

You could pre-process your sprites once on the CPU to avoid having to execute that ridiculously huge loop in your pixel shader.

Then you'd just have to do "[font=courier new,courier,monospace]fetch sprite colour (which is an index), fetch colour from pallete at index[/font]", instead of "[font=courier new,courier,monospace]fetch sprite colour, search entire source pallets for colour to determine it's index, fetch colour from new pallete at index[/font]".
[/quote]

Similar to what you suggested, I am thinking along the line of using one of the 3 RGB channels as my unique index, and storing my colour table values in an array of 255 elements.
0

Share this post


Link to post
Share on other sites
Ok, I have created a 4x1 png and inserted 4 different coloured pixels. I have changed index from 0 to 3 (or any value for that fact) but it always display the colour of the first pixel. If i change index with the var coords in the tex1D method, and move my sprite, it cycles through the colours when I move, but displays the colour of the first pixel when stationary. Do you have any idea why this is happening?

here's the snippet of my function:

[CODE]
float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{

float4 colour = tex2D(input, coords);

int index = 0; //doesn't matter what value i put, it always return the first pixel of my palette
float4 lookUp = tex1D(Palette2Sampler,index);
//float4 lookUp = tex1D(Palette2Sampler,coord);
// when I run the above and move the sprite, it cycles through the colours, but always
// displays the colour of the first pixel when stationary.

return lookup;
}
[/CODE] Edited by derrace
0

Share this post


Link to post
Share on other sites
Texture coordinates range between (0, 1), not (0, n). Divide your index by n, where n is the number of texels (4 in your case).

Also, if this is DX9, you need to apply the half texel offset so that you're sampling from the middle of the texel (sampling from the edge will be "unstable"). So add (0.5 / 4) to the index.

And make sure you're using point sampling.
1

Share this post


Link to post
Share on other sites
[quote name='phil_t' timestamp='1353613221' post='5003300']
Also, if this is DX9, you need to apply the half texel offset so that you're sampling from the middle of the texel (sampling from the edge will be "unstable"). So add (0.5 / 4) to the index.[/quote]That's not just DX9*, that's how texture coordinates work in all APIs.
[font=courier new,courier,monospace]centreOfTexel = (texelIndex+0.5)/widthInTexels[/font]

*[size=2]The "DX9 half pixel offset issue" is actually to do with how it addresses screen pixels during rasterization.[/size]
0

Share this post


Link to post
Share on other sites
[quote name='phil_t' timestamp='1353613221' post='5003300']
Texture coordinates range between (0, 1), not (0, n). Divide your index by n, where n is the number of texels (4 in your case).

Also, if this is DX9, you need to apply the half texel offset so that you're sampling from the middle of the texel (sampling from the edge will be "unstable"). So add (0.5 / 4) to the index.

And make sure you're using point sampling.
[/quote]


Ah, 0 to 1. Got it. In my script, I don't think I need to do any division as it would probably have done it for me. When setting up my colourtable, I would just multiply it by 255 since I am using the bands of the pixel as my index.

Got my algo for pixel shader for palette swap sorta working.. but I am having some issues with it.

[url="http://imgur.com/3pPnO"]http://imgur.com/3pPnO[/url]

Bands aren't unique, so I am taking the average of RGB as my index. I don't get a whole number, but I made each lookup area 3x1 (i need to increase it to 3). I am not sure if it's the decimals that is causing the issue. I will need to debug further. Also, I have two default colours with the same value, but expecting different palette swaps.. How can this be achieved?


for now just assume my colour table is 255 x 10. I will hardcode the dividers as well as the y index for now.

[source lang="java"]
float4 colour = tex2D(input, coords);
float2 index = float2((colour.r + colour.g+colour.b)/3.0 , 4/10.0 + 0.5 / 10.0);
float4 lookUp = tex2D(PaletteSampler,index);
if(colour.a != 0) {
colour.rgb = lookUp.rgb;
}

return colour;
[/source]

sorry, what do you mean by point sampling? Isn't the above point sampling? Edited by derrace
0

Share this post


Link to post
Share on other sites
hmm, so I have added a check and it does look like a lot of pixels aren't being replaced from the lookup table. It almost appears like I got my indices wrong =\

I think I need a better way of indexing. Does anyone have any suggestion?

To recap, currently I am taking the average of the RGB as the neither of the bands are unique =\. My palette (see screenshot attached) has potentially 15 pixels.

[url="http://imgur.com/ujO6E"]http://imgur.com/ujO6E[/url]

Replacing my default sprites with a greyscale one is kinda tedious, and I am hoping there's a better way. Edited by derrace
0

Share this post


Link to post
Share on other sites
Alright, I have tried using greyscale as my index.

http://imgur.com/CWZju

Hmm, it looks a bit better after using greyscale, but still far from perfect.. Running out of ideas =\
0

Share this post


Link to post
Share on other sites
Argh, turns out when my engine is running at 1x (default resolution) the shader works perfectly, any scale of that (including the default XNA's graphics.ToggleFullScreen();) stuffs it up =\.

I am passing a transformation matrix into my spriteBtach.Begin method to scale my playable window by X amount, as well as using it for my camera + parallax effect.

It appears that the translation or scale operations are messing up my pixel shader?


I need help, badly now =( Edited by derrace
0

Share this post


Link to post
Share on other sites
You might want to play around with the texture filtering for the sprite batch. Try adding this before the begin call:

this.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;

The default in XNA (according to the interlect) is LinearClamp
0

Share this post


Link to post
Share on other sites
[quote name='Kyall' timestamp='1353732212' post='5003666']
You might want to play around with the texture filtering for the sprite batch. Try adding this before the begin call:

this.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;

The default in XNA (according to the interlect) is LinearClamp
[/quote]


Hi there, I have tried that, but to no avail.

I have been reading up on this: http://msdn.microsoft.com/en-us/library/ff604998.aspx

But I have no experience with sampler state. Do you know of any tutorials which might help?

I am thinking of using the shader to do my scaling (magnification) just for the sprite. I am really at a lost atm =\
0

Share this post


Link to post
Share on other sites
If you're using SpriteBatch, you have to specify the sampler state in the Begin call. Otherwise it will override it with LinearClamp.

So use the overload of SpriteBatch.Begin that takes a SamplerState.
1

Share this post


Link to post
Share on other sites
[quote name='phil_t' timestamp='1353788243' post='5003807']
If you're using SpriteBatch, you have to specify the sampler state in the Begin call. Otherwise it will override it with LinearClamp.

So use the overload of SpriteBatch.Begin that takes a SamplerState.
[/quote]

Ah, that did the trick. Thanks a lot!

Are there any sites you could recommend to read up on this? The lack of documentation on MSDN is really slowing my progress and I am just stumbling along with random google searches.... =(
0

Share this post


Link to post
Share on other sites
Yeah, the MSDN documentation is pretty awful. The education samples are pretty good though: http://xbox.create.msdn.com/en-US/education/catalog/

I would also recommend Shawn Hargreaves blog, though I suspect your random google searches lead you there pretty frequently anyway :-).
0

Share this post


Link to post
Share on other sites
[quote name='derrace' timestamp='1353690938' post='5003531']
Replacing my default sprites with a greyscale one is kinda tedious, and I am hoping there's a better way.
[/quote]

I wonder if tinting the player would be good enough instead of a full palette swap ... don't use your existing palette swapping pixel shader, instead treat the image of your character as a greyscale by sampling the original texture and ignoring 2 out of the 3 color channels, then multiply the greyscale by a passed in tintcolor to make the player a different color.

float4 originalColor = tex2d( TexSampler, tex0.xy );
float4 greyColor = float4( originalColor.r, originalColor.r, originalColor.r, originalColor.a );
float4 newColor = greyColor * tintColor;

where you pass tintColor in as a uniform extern.

You might have to experiment with which channel you want to use as the grey scale (r,g or b). Edited by Steve_Segreto
0

Share this post


Link to post
Share on other sites
[quote name='Steve_Segreto' timestamp='1353918109' post='5004145']
[quote name='derrace' timestamp='1353690938' post='5003531']
Replacing my default sprites with a greyscale one is kinda tedious, and I am hoping there's a better way.
[/quote]

I wonder if tinting the player would be good enough instead of a full palette swap ... don't use your existing palette swapping pixel shader, instead treat the image of your character as a greyscale by sampling the original texture and ignoring 2 out of the 3 color channels, then multiply the greyscale by a passed in tintcolor to make the player a different color.

where you pass tintColor in as a uniform extern.

You might have to experiment with which channel you want to use as the grey scale (r,g or b).
[/quote]

Hi Steve, changing my spritesheet to greyscale was a lot easier than I thought, although it's more of a Black and White filter (with same values for RGB).

I had thought of that prior, but I have a problem that with my original palette, I don't have a unique RGB band, so sampling just one of the band is not possible. Selecting the average 2 of the 3 yields duplicate values, and it gets messy if i take the average of all 3. This was why I went with greyscale.

My motivation for getting the palette swap working was because it would be reused in many situations. My palette has 15+ samples, so it would be a nightmare trying to get the right set of colours for try and error with the tinting method. Doing it with a colour table makes it easy to swap the colours, as well as knowing exactly what colours it would be swapping.
0

Share this post


Link to post
Share on other sites
Anyway, I got it working. Thanks everyone for their help.

Here's it in action =)

http://www.youtube.com/watch?v=GHWiuaAiQVU
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0