Skybox on Windows Phone 7


When we have no custom shader, we need to make some sort of little magics to create usual effects like Skybox. This Small post will show a way to simulate this visual effect on Windows Phone 7.
The trick is actually very simple, we just “extract” all the textures from the cube map texture (normally we feed it to a shader that would sample it with the eye vector, but we dont have custom shaders …) and draw all of then each frame (transformed by the camera matrices).

Before showing the code, i need to make some things clear =P.
I used some render functions of PloobsEngine (to hold graphics state, create graphics resources …., tried to use it as little as possible), the functions names used says what is being done, so it is very easy to convert it to plain XNA.

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Features
{
    public class SkyBox
    {
        String textureCubeName;
        bool enable = false;        

        public void Initialize(String texCubeName)
        {
            Cube = GraphicFactory.GetTextureCube(texCubeName);
            CubeFaces = new Texture2D[6];
            PositionOffset = new Vector3(20, 20, 20);
            CreateGraphic(512);
            StripTexturesFromCube();
            InitializeData();
        }       

        #region Properties
        GraphicFactory GraphicFactory;
        public Vector3 PositionOffset { get; set; }
        public Vector3 Position { get; set; }
        public TextureCube Cube { get; set; }
        public Color[] PixelArray { get; set; }
        public Texture2D[] CubeFaces { get; set; }
        public VertexBuffer VertexBuffer { get; set; }
        public IndexBuffer IndexBuffer { get; set; }
        public BasicEffect Effect { get; set; }
        #endregion

        #region Fields

        private List _vertices = new List();
        private List _indices = new List();
        #endregion

        #region Private methods
        private void InitializeData()
        {
            VertexBuffer = GraphicFactory.CreateVertexBuffer(VertexPositionNormalTexture.VertexDeclaration, _vertices.Count, BufferUsage.None);
            VertexBuffer.SetData(_vertices.ToArray());
            IndexBuffer = GraphicFactory.CreateIndexBuffer(IndexElementSize.SixteenBits, _indices.Count, BufferUsage.None);
            IndexBuffer.SetData(_indices.ToArray());
            Effect = GraphicFactory.GetBasicEffect();
            Effect.TextureEnabled = true;
        }

        ///just a fancy quad
        private void CreateGraphic(float size)
        {
            Vector3[] normals = {
                                    Vector3.Right,
                                    Vector3.Left,
                                    Vector3.Up,
                                    Vector3.Down,
                                    Vector3.Backward,
                                    Vector3.Forward,
                                };
            Vector2[] textureCoordinates = {
                                               Vector2.One, Vector2.UnitY, Vector2.Zero, Vector2.UnitX,
                                               Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY,
                                               Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY,
                                               Vector2.Zero, Vector2.UnitX, Vector2.One, Vector2.UnitY,
                                               Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One,
                                               Vector2.UnitY, Vector2.Zero, Vector2.UnitX, Vector2.One,
                                           };
            var index = 0;
            foreach (var normal in normals)
            {
                var side1 = new Vector3(normal.Z, normal.X, normal.Y);
                var side2 = Vector3.Cross(normal, side1);
                AddIndex(CurrentVertex + 0);
                AddIndex(CurrentVertex + 1);
                AddIndex(CurrentVertex + 2);
                AddIndex(CurrentVertex + 0);
                AddIndex(CurrentVertex + 2);
                AddIndex(CurrentVertex + 3);
                AddVertex((normal - side1 - side2) * size / 2, normal, textureCoordinates[index++]);
                AddVertex((normal - side1 + side2) * size / 2, normal, textureCoordinates[index++]);
                AddVertex((normal + side1 + side2) * size / 2, normal, textureCoordinates[index++]);
                AddVertex((normal + side1 - side2) * size / 2, normal, textureCoordinates[index++]);
            }
        }
        protected void StripTexturesFromCube()
        {
            PixelArray = new Color[Cube.Size * Cube.Size];
            for (int s = 0; s < CubeFaces.Length; s++)
            {
                CubeFaces[s] = GraphicFactory.CreateTexture2D(Cube.Size, Cube.Size, false, SurfaceFormat.Color);
                switch (s)
                {
                    case 0:
                        Cube.GetData(CubeMapFace.PositiveX, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 1:
                        Cube.GetData(CubeMapFace.NegativeX, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 2:
                        Cube.GetData(CubeMapFace.PositiveY, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 3:
                        Cube.GetData(CubeMapFace.NegativeY, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 4:
                        Cube.GetData(CubeMapFace.PositiveZ, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                    case 5:
                        Cube.GetData(CubeMapFace.NegativeZ, PixelArray);
                        CubeFaces[s].SetData(PixelArray);
                        break;
                }
            }
        }
        protected void AddVertex(Vector3 position, Vector3 normal, Vector2 textureCoordinates)
        {
            _vertices.Add(new VertexPositionNormalTexture(position, normal, textureCoordinates));
        }
        protected void AddIndex(int index)
        {
            if (index > ushort.MaxValue)
                throw new ArgumentOutOfRangeException("index");
            _indices.Add((ushort)index);
        }

        protected int CurrentVertex
        {
            get { return _vertices.Count; }
        }
        #endregion

        public void PreDraw(RenderHelper render, GameTime gt, ref Matrix activeView, ref Matrix activeProjection, Vector3 CamPos)
        {
            if (!enable || Cube == null)
                return;

            Vector3 position = camPos

            this.Position = position + PositionOffset;
            Effect.View = activeView;
            Effect.Projection = activeProjection;
            Effect.World = Matrix.CreateTranslation(this.Position);

            render.PushDepthStencilState(new DepthStencilState() { DepthBufferEnable = false });
            render.PushRasterizerState(new RasterizerState() { CullMode = CullMode.None });

            var graphics = Effect.GraphicsDevice;
            graphics.SetVertexBuffer(VertexBuffer);
            graphics.Indices = IndexBuffer;

            Effect.Texture = CubeFaces[0];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 0, 2);
            Effect.Texture = CubeFaces[1];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 6, 2);
            Effect.Texture = CubeFaces[2];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 12, 2);
            Effect.Texture = CubeFaces[3];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 18, 2);
            Effect.Texture = CubeFaces[4];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 24, 2);
            Effect.Texture = CubeFaces[5];
            Effect.CurrentTechnique.Passes[0].Apply();
            graphics.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, _vertices.Count, 30, 2);

            render.PopDepthStencilState();
            render.PopRasterizerState();

        }
    }
}

You need to call the draw function before all 3D drawing !!!

As always code is not optimized and some stuffs are hardcoded.

  1. #1 by textbook discounts on 24 de março de 2017 - 6:21 am

    Well I guess I don’t have to spend the weekend figuring this one out!

  2. #2 by for more info on 24 de março de 2017 - 6:34 am

    Way cool! Some very valid points! I appreciate you penning this post and also the rest of the site is very good.

  3. #3 by Best food blogger on 24 de março de 2017 - 6:53 am

    Utterly indited written content , thankyou for information.

  4. #4 by 100% real estate on 24 de março de 2017 - 7:12 am

    Wow! Thank you! I constantly wanted to write on my site something like that. Can I include a fragment of your post to my blog?

  5. #5 by ERP Implementation in India on 24 de março de 2017 - 7:32 am

    Thanks so much for the blog.Really looking forward to read more. Cool.

  6. #6 by Vida en pareja on 24 de março de 2017 - 7:51 am

    This web site definitely has all the information I wanted concerning this subject and didn at know who to ask.

  7. #7 by http://www.sinnottsautosales.com/vintage-car-insurance-ontario.html on 24 de março de 2017 - 9:30 am

    WOW WOW WOW…LOVE IT!,what a gorgeous card again Bev,love this WOJ image and the colours you have used…yes i agree with you it takes awhile to pick the papers to use..lol,Take careSan x

  8. #8 by http://www.tier1graphicsusa.com/state-board-of-insurance.html on 24 de março de 2017 - 9:33 am

    This was so helpful and easy! Do you have any articles on rehab?

  9. #9 by http://www.sinnottsautosales.com/how-to-sell-an-insurance-policy.html on 24 de março de 2017 - 9:38 am

    I might be beating a dead horse, but thank you for posting this!

  10. #10 by affordable auto insurance on 24 de março de 2017 - 9:41 am

    I appreciate regarding nice review which plainly promote obtaining emergent provisitions. The best possibility to choose quotes goes free quotes comparison process which gives the cheapest deals on landlords insurance policy provided by high agents as american family from the USA.

  11. #11 by Cartier Love Bracelet Replica on 24 de março de 2017 - 9:52 am

    I got this one headphonesto our mother of mothers evening, as well as she definitely adored information technology! The truly adorable headphonesand suggesting in the card you already know comes within the container is very emotional!! As well as the excellence of the beads was ideal!

  12. #12 by hermes h belt replica on 24 de março de 2017 - 9:52 am

    I got your headphonestowards the mother of mothers day, to she absolutely liked it! It is truly sweet headphonesand the suggesting on the card that will come within the package is really sentimental!! And the premium of the beads is actually awesome!

  13. #13 by blick auf diese web-site on 24 de março de 2017 - 10:05 am

    Neben Busensex, Fusserotik und Fesselspielen geniesst sie ganz besonders orale Veröhnspiele, bei denen sie auch gerne bis zum sahnigen Schluss blässt.

  14. #14 by Montres Cartier Replica on 24 de março de 2017 - 10:11 am

    Great headphonesbuy, nicely listed and also exactly what are revealed. Awesome gift box furthermore poem and enclosed. Ideal to mother’s evening!

  15. #15 by everything you need to know about digital marketing on 24 de março de 2017 - 10:21 am

    Im obliged for the blog article.Much thanks again. Fantastic.

  16. #16 by http://www.warburtongallery.com/broad-form.html on 24 de março de 2017 - 10:34 am

    Toi aussi :OMoi ils sont dans le tiroir sous mon lit, je les ai TOUS gardés! Mais j’ai pas de posters de Buffy moi xDAh mais c’est toi les 150 visites « same user » Ahaha 😀

  17. #17 by i darueber nachgedacht on 24 de março de 2017 - 10:48 am

    cam amateur Ich konnte erkennen wie sich ihre Brustwarzen langsam aufrichteten.

  18. #18 by cheap flyer Printing 10000 on 24 de março de 2017 - 11:17 am

    Hello, the whole thing is going perfectly here and ofcourse every one is sharing data, that’s genuinely
    excellent, keep up writing.

  19. #19 by http://www.evolutionhairdressers.com/car-insurance-quotes-joplin-mo.html on 24 de março de 2017 - 11:18 am

    And I would gladly accept it, Stuccohouse! Here’s the problem with Midwestern snow though (and I say this from experience, having lived in Chicago for almost six years.) It’s charming in December, it’s to be expected in January, it’s tolerable in February, annoying in March and downright irritating in April. And in May? The words I would use to describe snow in May aren’t fit for a family-oriented blog. We’ll just go with “wrong.” Snow in May is WRONG! But December snow makes me happy!

  20. #20 by Compare of auto insurance on 24 de março de 2017 - 1:10 pm

    Thank you regarding natural review that truthfully determined in choosing unexplored provisitions. The best feature to make up rates goes cheaper process which gives the best deals for building insurance coverage from high companies as american family from the US.

  21. #21 by hobbyhuren dachau on 24 de março de 2017 - 1:25 pm

    Jenseits der zeigegeilen Dirndl Mädels kann auch beim Telefonsex Bayern jede Menge geile Weiber knallen und seinem Schwanz mal einen großen Gefallen tun.

  22. #22 by insurance add on 24 de março de 2017 - 1:30 pm

    acHola yo qiero saner q puedo aser para bolver con mi marido ya q llevamos 4 meses de separados el dic q ya no m qiere pero asta ase un mes m desia todo lo contrarioa24

  23. #23 by cheap Booklet printing melbourne on 24 de março de 2017 - 1:35 pm

    Oh my goodness! Impressive article dude! Many thanks, However I am having
    problems with your RSS. I don’t know the reason why I can’t subscribe to it.
    Is there anyone else getting the same RSS issues? Anyone who knows the answer
    will you kindly respond? Thanx!!

  24. #24 by http://www.sinnottsautosales.com/insurance-for-firearms.html on 24 de março de 2017 - 1:43 pm

    Det er fordelen med dårlig vær: mer tid til strikking. Flotte sokker ble det! :) Teppet ser ut til å bli kjempeflott, har lurt litt på det jeg også, men ikke kjøpt garn på salg.Nydelige bilder av natur og stavkirker! :)

  25. #25 by http://www.sinnottsautosales.com/need-insurance-to-register-a-car.html on 24 de março de 2017 - 1:45 pm

    I was so confused about what to buy, but this makes it understandable.

  26. #26 by http://www.evolutionhairdressers.com/how-much-does-full-coverage-insurance-cost-on-a-new-car.html on 24 de março de 2017 - 2:42 pm

    Sharp thinking! Thanks for the answer.

  27. #27 by using drugs to discriminateadverse selection in the insurance marketplace on 24 de março de 2017 - 2:48 pm

    Very well written! I have been teaching clients for years that it is absolutely necessary to love yourself – to be kind to yourself – to appreciate and respect yourself, as you are, completely, right now and for always – before consistent positive change can take place. Thank you for such a well written piece on self love! Yours truly in Peace & Love – Coach Tanya

  28. #28 by desentupidora on 24 de março de 2017 - 3:44 pm

    Thank you ever so for you post.Much thanks again. Really Cool.

  29. #29 by cheapest car insurance and tax on 24 de março de 2017 - 3:52 pm

    David, you never cease to amaze me with your intellect, life’s experiences. It is a joy to consider you a friend and a true patriot. Your analogy was point on! Awesome response!

  30. #30 by geico car insurance on 24 de março de 2017 - 4:11 pm

    I wish to thank you for good information which truthfully help in checking renewed definitions. The most preferable possibility to get quote is low cost process which gives the most wanted deals for house insurance coverage against well known providers as american family in US.

  31. #31 by http://www.whatsyouroldbrooklyn.com/swinton-car-insurance-retrieve-quote.html on 24 de março de 2017 - 4:16 pm

    I never thought I would find such an everyday topic so enthralling!

  32. #32 by auto insurance shakopee mn on 24 de março de 2017 - 4:32 pm

    Umm, are you really just giving this info out for nothing?

  33. #33 by reloj checador de huella digital precios on 24 de março de 2017 - 5:18 pm

    Reloj de biometría múltiple para control de asistencia acceso, cuenta con la última plataforma
    ZEM800 con algoritmo de semblantes 7.0 y una memoria de gran capacidad.

  34. #34 by cheap ad&d insurance on 24 de março de 2017 - 5:20 pm

    I will be putting this dazzling insight to good use in no time.

  35. #35 by http://www.warburtongallery.com/progressive-insurance-woman-stephanie-courtney.html on 24 de março de 2017 - 5:44 pm

    Posted on Dar dacă a fost o mutare deliberată, ca să “apară”, peste ani, “neimplicarea armată” a URSS în evenimente ? Chiar cu preÅ£ul demascării clicii FSN ? Altfel, s-au documentat cazurile cu turiÅŸti sovietici în autoturisme Lada.ÃŽn noiembrie (lună turistică, este ?) la hotelurile din centrul BucureÅŸtiului erau o gramadă de turiÅŸti sovietici, veniÅ£i cu autocarele alea portocalii Ikarus, cu inscripÅ£ia COBTPAHCABTO (Sovtransavto).

  36. #36 by http://www.whatsyouroldbrooklyn.com/how-to-get-insurance-before-buying-a-car.html on 24 de março de 2017 - 5:51 pm

    “Sam naslov nam govori da će naÅ¡ sadržaj biti arhiviran u Nacionalnoj sveučiliÅ¡noj knjižnici i pritom biti uvijek osvježavan, a to osvježavanje arhive ovisi o frekventnosti izlaženja odnosno, objavljivanja i procjeni stručnog povjerenstva.”Moj site je u DAMP uvrÅ¡ten 01.01.2005. i to je jedini arhivirani primjerak. Nikad nije uvrÅ¡tena novija kopija.Eto.

  37. #37 by http://www.warburtongallery.com/dvla-car-insurance-check.html on 24 de março de 2017 - 6:12 pm

    I read your post and wished I’d written it

  38. #38 by http://www.hexpilot.com/help_hermes.aspx on 24 de março de 2017 - 6:22 pm

    Therefore when i ordered things i thought things ended up being going to be the sweet and yet inexpensively established bracelet greatest for stocking stuffers. Then again it is made beautifully plus is actually thick hence the never plastic or quickly broken steel. My personal mom enjoyed information technology. This is a little regarding the slight side when you has a bigger wrist i wouldnt recommend it but it is therefore worthwhile the actual deal rates!!

  39. #39 by bucksking gulch tours on 24 de março de 2017 - 6:31 pm

    It as not that I want to copy your web site, but I really like the style. Could you tell me which theme are you using? Or was it tailor made?

  40. #40 by http://www.wrighthousecalls.com/tag-and-title-agency.html on 24 de março de 2017 - 7:29 pm

    Mmmmhhh … sieht alles sehr lecker aus – und wars auch bestimmt!Ich hoffe, Eline stellt bald ihre Rezepte in ihren Blog *vorfreude*.

  41. #41 by http://news.hermesreplica.pw/hermesreplicapw/179.asp on 24 de março de 2017 - 7:41 pm

    The item ended up being with such a great expense I never ever idea on premium is hence excellent. It’s awesome. This mother might prefer that in Holiday morning whenever she opens up gifts therefore appearances like I spent even more, although rates ended up being exclusively very good!!

  42. #42 by http://news.panchro.xyz/panchroxyz/68.asp on 24 de março de 2017 - 7:43 pm

    We have bought our brand out of bracelet a few occasions. Every single one is super sweet, made well, cannot tarnish and also meaningful based on what any you buy plus which a person promote that and.

  43. #43 by clash royale on 24 de março de 2017 - 8:03 pm

    Hi, I do believe this is a great website. I stumbledupon it 😉 I am going to revisit yet again since i have book-marked
    it. Money and freedom is the best way to change, may you be
    rich and continue to guide other people.

  44. #44 by remedies rose bud on 24 de março de 2017 - 8:23 pm

    here are some links to internet sites that we link to because we consider they are really worth visiting

  45. #45 by auto insurance anaheim ca on 24 de março de 2017 - 8:33 pm

    Bandal oyé | (13:41) Nzambe zongisela biso Madilu System zua na place Boketshu. Tala kaka ndenge aza kotia confusion na combat. Atutaki tolo que ba concerts eko beta te, lelo lingi ye moko abeta ! Ezalaka vraiment ? Moyibi moko boye. Mbala oyo Rex atimbeli yo na ba combattants ya mayele. Oko beta jamais concert sinon te ba musiciens tout bazongeli ba concerts

  46. #46 by Download ICDL-IT Certification Dumps on 24 de março de 2017 - 8:43 pm

    that may be the finish of this article. Here youll uncover some web sites that we think you will enjoy, just click the links over

  47. #47 by yeezy triple white on 24 de março de 2017 - 8:52 pm

1 691 692 693
(não será publicado)