In my 2D game I have TileSet class that loads the texture and creates Rectangle[] array which stores each tile coordinates. Pretty basic stuff. Now I'd like to also calculate and store the average color of each tile. How do I do that in XNA/C#?

My goal is to tint the tile with the color based on its value when highlighted. Or maybe there is some other way to achieve similar effect?

  • 1
    \$\begingroup\$ Average over Texture2D.getData(...)? \$\endgroup\$ – Anko Apr 4 '13 at 17:45
  • \$\begingroup\$ Not sure I understand what you are asking. Do you want to average the texture colors? or tile colors? or are your tiles subsections of your texture? Do you want to average of the tiles for the area of the texture they cover or the average color over several tiles? More descriptive questions can yield better results. \$\endgroup\$ – UnderscoreZero Apr 4 '13 at 18:13
  • \$\begingroup\$ Lets say I have 128x128 tileset. Each tile being 32x32 gives a total of 16 diffrent tiles. I'd like to get the average color of each of those 16 tiles (so 16 colors). So for example if the tile is a tree the color would be somewhat green. \$\endgroup\$ – kasztelan Apr 5 '13 at 18:30

Mipmap the texture, generate the miplevels, then read from the smallest (1x1) level. What's particularly cool about this is that you can keep the entire process GPU-side (even do it as a vertex texture if you wish) and not have to worry about reading back the colour, then sending it as a shader constant every time you do a texture change.

How do you know which level is the smallest? You don't need to - just use a stupidly high value for the LOD in your tex2Dlod call and it will auto-clamp to the correct level for you.

  • \$\begingroup\$ I'm sorry but I don't think I understand what you're saying. I just recently started learning XNA and I don't know it very well. Could you please give some example how could I implement your idea in XNA? \$\endgroup\$ – kasztelan Apr 5 '13 at 18:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.