BitField in Shaders (SM 3 and before)


Sometimes we need to encode lots of boolean flags in a texture channel and recover it in a shader. I found that shader model 3 and before dont have bitwise operations (they only support floats … that dont have this …) !!!
Fortunately i found some help on the old good float math and i managed to solve this even on SM 2.

Here is how it is done:

1. Encoding some flags in a binary format:

Helper Class

public class ShaderUtils
    {
        public static int CreateSpecificBitField(bool DoNotIlluminate = false, bool isBackGround = false,bool NotEffectedByMotionBlur = false , bool useCubeMapAmbientLightining = false)
        {
            return CreateBitField(DoNotIlluminate, isBackGround, NotEffectedByMotionBlur, useCubeMapAmbientLightining);
        }

        public static int CreateBitField(bool op1 = false, bool op2 = false, bool op3 = false, bool op4 = false, bool op5 = false,bool op6 = false,bool op7 = false,bool op8 = false,bool op9 = false)
        {
            int flags = 
            (op1 ? 1 : 0) |
            (op2 ? 2 : 0) |
            (op3 ? 4 : 0) |
            (op4 ? 8 : 0) |
            (op5 ? 16 : 0) |
            (op6 ? 32 : 0) |
            (op7 ? 64 : 0) |
            (op8 ? 128 : 0) |
            (op9 ? 256 : 0) 

            ;
            return flags;
        }
    }

Creating the bitfield

var bitfield = ShaderUtils.CreateSpecificBitField(false, true,false , false)

2. Saving it to a texture channel (in some Pixel Shader, using render to texture)

float id;   /// recieve the bitfield value
....
PixelShaderOutput PShader( PS_INPUT pin ) : COLOR0   
{   
    PixelShaderOutput output;   
    ///bla bla bla   
    output.color.a = id / 255;   
    return output;   
}

3. Recovering it in another shader and testing the flags !!!:

      sampler extraSampler :register(s1);
....
        float4 extra =  tex2D(extraSampler,input.TexCoord).rgba;
        int procces = round(extra.a * 255 );
        bool DoNotIlluminate = fmod(procces, 2) == 1; 
	bool isBackGround = fmod(procces, 4) >= 2; 
	bool isAmbienteCubeMap = fmod(procces, 16) >= 8; 
 ....

         if(DoNotIlluminate  || isBackGround)
	{
		return float4(diffuseColor,1);
	}
....

There is no rounding problem with the float parameters (the explanation is a bit harder, you will need to know how the worst case scenario is encoded as a mantissa and a expoent).
Shader Model > 3 introduced real integers and Bitwise operations =P

, , ,

  1. #1 by hauskredit gekündigt on 16 de janeiro de 2017 - 6:08 pm

    That’s a skillful answer to a difficult question

  2. #2 by butt plug on 16 de janeiro de 2017 - 7:52 pm

    usually posts some very fascinating stuff like this. If youre new to this site

  3. #3 by best insurance company ratings on 16 de janeiro de 2017 - 8:51 pm

    I have been exploring for a little bit for any high-quality articles or blog posts on this sort of area . Exploring in Yahoo I at last stumbled upon this website. Reading this info So i am happy to convey that I have a very good uncanny feeling I discovered exactly what I needed. I most certainly will make certain to don’t forget this web site and give it a look on a constant basis.

  4. #4 by beamtenkredit dr klein öffnungszeiten on 16 de janeiro de 2017 - 9:27 pm

    sono d’accordo, secondo me è più simile a una videocamera. Però cos’è una videocamera, se non una fotocamera che sa imprimere 23, 24, 25 o 50 fotogrammi al secondo? Ad ogni modo resta vero che il tutto è davvero affascinante… e come questo avvenga in maniera trasparente e del tutto non notata nella vita di un essere umano!P.S. HDR continuo.. terrific!

  5. #5 by sofortkredit trotz eintrag reise ägypten on 16 de janeiro de 2017 - 9:45 pm

    My daughter is also “chubby”. Have told her to exercise more to reduce or get rid of those excess fats. But because of her age, she finds it hard to do my wanting as she is so fond of eating any thing that fancy her. I recommend rigid exercise rather than the chemical way of reducing weight (fats).

  6. #6 by Car Insurance Quotes Online on 16 de janeiro de 2017 - 10:24 pm

    Are you able to type long blog posts for the PS3 internet browser?

  7. #7 by forward darlehen on 16 de janeiro de 2017 - 10:34 pm

    Hello, i believe that i saw you visited my web site thus i came to “return the choose”.I’m attempting to in finding things to improve my website!I guess its ok to use some of your concepts!!

  8. #8 by http://kostenloskreditevergleichen.net/kredit-15000-lange-laufzeit.html on 16 de janeiro de 2017 - 10:36 pm

    we had 3 Sibes in our family in years before me, Savannah…you can see them on my blog…anyways, Mom and Dad lived for a bit in Ohio with the Sibes before coming back to Calif. And, the games they played with their Sibe anifamily back then were totally hilarious…in rain, snow, tornadoes, and on and on…maybe Mom will tell that story some day…very cool

  9. #9 by http://privaterkreditvergleich.top/kredit-aufnehmen-auf-was-achten.html on 16 de janeiro de 2017 - 10:57 pm

    Emilio,Questa è stata la prima volta che ho copiato e incollato uno di questi messaggi su Facebook. L'ho fatto perchè ho verificato, come faccio sempre, la veridicità della notizia.Verificato dove?su Google News almeno una decina di testate titolavano sulla cosaQuali?E che cavolo per una volta devo sentirmi trattato così?Sì. Invece di inoltrarla pari pari, avresti potuto corredarla di link alle fonti che avevi trovato, per esempio. Così se le fonti pubblicavano una rettifica, l'appello portava con sè anche la rettifica.

  10. #10 by kredit ohne schufaeintrag gelöscht on 16 de janeiro de 2017 - 11:36 pm

    I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work.

  11. #11 by http://kostenloskreditevergleichen.net/easy-kredit-marl-recklinghausen-adresse.html on 16 de janeiro de 2017 - 11:38 pm

    A wonderful job. Super helpful information.

  12. #12 by kredit finanzierung kredit zins berechnen on 17 de janeiro de 2017 - 12:02 am

    A bit surprised it seems to simple and yet useful.

  13. #13 by http://guenstigerkreditonline.net/notebook-kredit-murah.html on 17 de janeiro de 2017 - 12:25 am

    hei….também tenho fotos assim educativas mas do Congo…. também posso enviar??????Aliás todas as semanas encontro uma coisa nova aqui…. muito, mas muito mais interessantes do que essas lolollol

  14. #14 by kredit mobil syar& 39;i on 17 de janeiro de 2017 - 12:31 am

    Monika, o tak Alcia jest poza wszelka konkurencja :-) A lapki z cynamonem czy kakao? Usciski!Pinos, wielkie dzieki!Ecocreme, dziekuje za odwiedziny i mile slowa, pozdrawiam Cie cieplo!! :-)Karola, nie powiem ze trzymam Cie za slowo, ale mam nadzieje ze rogaliki Ci posmakuja :-)Magda, oby byly dobre i by Cie nie rozczarowaly :-) Wiesz, ja to czasem przesadnie przejmuje sie forma, ale sobie tlumacze ze czasem mozna przesadzac jesli innym nie daje sie w kosc :-) Pozdrowienia sle!

  15. #15 by http://kostenloskreditevergleichen.net/schufafreier-kredit-sonderaktion-krakau.html on 17 de janeiro de 2017 - 12:32 am

    Hi Jon! I’m Greg Di Gregorio’s sister, Cynthia. Love your wbstiee!! Amazing photos!!! I remember seeing you jam in the Boston Best Guitar Contest at The Channel where?? Lol!! And those late night shows you did in Sommerville! You’ve come A LONG way since then!!Best of Luck with ALL!!Hope all is very well with you and your family!

  16. #16 by android apps for pc download on 17 de janeiro de 2017 - 12:35 am

    As soon as I noticed this web site I went on reddit to share some of the love with them.

  17. #17 by aktuell dispokredit rechner on 17 de janeiro de 2017 - 12:57 am

    I’m impressed! You’ve managed the almost impossible.

  18. #18 by apps for pc on 17 de janeiro de 2017 - 12:58 am

    I truly enjoy looking through on this site, it contains fantastic blog posts.

  19. #19 by http://privaterkreditvergleich.top/offenburg-kredit.html on 17 de janeiro de 2017 - 1:42 am

    Takaoka, Seko….Who is the third? If they are fit I think Fukushi and Akaba will make the team. Obviously the big mystery is Noguchi, I hate to say it, but I do not like the chances of her running a marathon again at peak fitness. After that it is a chook raffle, though (and I am sure you know more about this) I hope Niiya runs a marathon next year, because I think she has a very fast marathon in her.The men are always a mystery. I think it could be a while before we see a Japanese man challenge the elites.

  20. #20 by free download for windows pc on 17 de janeiro de 2017 - 2:01 am

    magnificent post, very informative. I ponder why the opposite specialists of this sector don’t realize this. You must proceed your writing. I am sure, you’ve a huge readers’ base already!

  21. #21 by schufafrei kredit geld zurück on 17 de janeiro de 2017 - 2:31 am

    Dire qu’en décembre dernier, SFR m’a remboursé 560€ pour que je puisse acheter un iphone chez Orange et rester chez eux quand même.Ca m’a fait 24€ l’iPhone !Ils m’ont même fait un abonnement -26 ans (vache; encore une réduc de 30% … de mon âge lol).Le plus dingue, c’est que j’ai accepté.Je suis vraiment un patate !Ouf, je suis tombé au bon endroit ;-D

  22. #22 by Kitchen Rugs on 17 de janeiro de 2017 - 2:36 am

    You actually make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complex and extremely broad for me. I’m looking forward for your next post, I will try to get the hang of it!

  23. #23 by kredit ändern on 17 de janeiro de 2017 - 2:41 am

    dit :Cet article est importé de mon précédent blog. Hélas, je n’ai pas pu importer vos commentaires. Alors, si vous avez des remarques, des questions, ou juste envie de dire bonjour, vos petits mots sont les bienvenus !

  24. #24 by http://besteronlinekredit.pw/online-kredit-hannover-yoga.html on 17 de janeiro de 2017 - 3:03 am

    Smart thinking – a clever way of looking at it.

  25. #25 by pengertian kredit fix and cap on 17 de janeiro de 2017 - 3:11 am

    I’m kind of stressin’ too. I just picked up an adorable little dress yesterday (on sale!) and at first was kind of wondering if it wasn’t sparkly enough (it has no sequins, just an amazing color and shape!), but now I’m thinking that you’re right — I’ll stand out from the crowd!Hope you figure out your dress sitch. Have a wonderful new year!

  26. #26 by バーバリー ニット on 17 de janeiro de 2017 - 3:21 am

    コピー時計通販専門店
    人気コピー時計通販専門店

    ◆在庫情報随時更新!
    ◆お客さんたちも大好評です:
    ◆新品種類がそろっています。
    ◆品質がよい、価格が低い、実物写真!
    ◆経営方針: 品質を重視、納期も厳守、信用第一!
    ◆超格安価格で、安心、迅速、確実、にお客様の手元にお届け致します。

    豊富な品揃えで最新作も随時入荷致しておりますのでごゆっくりとご覧ください。
    広大な客を歓迎してご光臨!
    バーバリー ニット http://kopii.net/products/p1/7/1/index.htm

  27. #27 by オメガ スピードマスター オートマチック 青 on 17 de janeiro de 2017 - 3:21 am

    カードで使える日本語完全対応の安心なブランドコピーショップ

    ルイヴィトン、シャネル、グッチ、エルメス、プラダ等のコピー商品を販売致しております
    ロレックス、ガガミラノ、パネライ、フランクミューラーなどのハイブランド腕時計のコピー品も取り扱っております。
    2017年新作も随時入荷致しております。

    当店の製品は、業界でスーパーコピーと呼ばれるレベルの商品を最低ラインに、自社工場にて手作業の製造を行っております。
    日本人ブランド鑑定士をアドバイザーに品質管理を行っておりますので、一般消費者はもちろんのこと、
    質店や鑑定士にも真贋鑑定が困難である、最高峰の製品をご提供致しております。商品の発送は日本郵便EMSにて格安の料金で承っており、
    EMS日本郵便のサイトにて随時発送状況を確認頂けます。他業者では行っていないクレジットカード決済、コンビニ決済もご利用可能です。
    安心、安全にお買い物をお楽しみ頂けます。

    ご希望の商品が掲載されていない場合にも、
    お問い合わせ頂けましたら商品を確保できる場合がございますので
    オメガ スピードマスター オートマチック 青 http://kopii.net/products/p1/8/1/index.htm

  28. #28 by カルティエ 結婚指輪 店舗 大阪 on 17 de janeiro de 2017 - 3:21 am

    2017年の新素材-新作
    ブランド腕時計、バッグ、財布、小物などでございます専売店
    ★弊社は「信用第一」をモットーにお客様にご満足頂けるよう
    ★全物品運賃無料(日本全国)
    ★不良品物情況、無償で交換します.
    ★税関没収する商品は再度無料で発送します!
    カルティエ 結婚指輪 店舗 大阪 http://kopi356.com/category-65-b0.html

  29. #29 by http://besteronlinekredit.pw/hauskredit-rate.html on 17 de janeiro de 2017 - 3:37 am

    Last one to utilize this is a rotten egg!

  30. #30 by Mass Health Connector on 17 de janeiro de 2017 - 3:48 am

    Thank you for sharing excellent informations. Your site is so cool. I’m impressed by the details that you¡¦ve on this site. It reveals how nicely you understand this subject. Bookmarked this website page, will come back for more articles. You, my friend, ROCK! I found just the information I already searched all over the place and simply could not come across. What a perfect site.

  31. #31 by http://guenstigerkreditonline.net/kreditvertrag-einfacher-ölteig.html on 17 de janeiro de 2017 - 4:22 am

    Deadly accurate answer. You’ve hit the bullseye!

  32. #32 by http://besterkreditvergleich.net/gulp-profil-kredit-plus.html on 17 de janeiro de 2017 - 4:41 am

    Great common sense here. Wish I’d thought of that.

1 715 716 717
(não será publicado)