8-light 3D development in Windows Phone

Source: Internet
Author: User

In real life, in addition to color, the most important thing is light. With light, we can see light and shade, coloring, and highlights. After the texture of the previous section, this section adds the illumination effect to the scenario.

In xNa, light can be divided into two types: ambient light and directed light.

The ambient light does not come from any special direction. It has a light source, but it is reflected multiple times by the surrounding environment without a definite direction, and the surfaces of objects are equally affected by the light. In use, we mainly use ambient light to change the color of the basic light in the scenario.

Directed light is the light reflected by the surface of an object in a certain direction, such as the light of a spotlight. When describing this light, in addition to describing the direction, it also describes the color of the scattered light, the color of the object's surface highlight area, and other attributes.

When using light, an additional parameter needs to be specified, that is, the normal direction. How does the rendering engine calculate the angle between the incident light and the reflected light on any plane? How to determine which direction of the plane is positive? In fact, the answer to these questions is to rely on the normal.

Let's review the definition of the normal. Simply put, it is the vertical line perpendicular to the plane. For a surface, it is the line perpendicular to the tangent of a certain point on the surface. The important role of normal in 3D space is to determine the positive direction of the plane, which is usually defined as the positive direction from the internal direction to the external direction, the rendering engine can correctly process the direction when performing Ray operations and texture textures to achieve the expected effect.

If you need illumination in the scenario, you cannot simply use the vertexpositiontexture class. xNa provides the vertexpositionnormaltexture class, which provides a representation of the normal. Next, we will use this new Class Based on the triangle definition above. The Code is as follows:

Triangle = new vertexpositionnormaltexture [] {

New vertexpositionnormaltexture (New vector3 (0, 1, 0), new vector3 (0, 0, 1), new vector2 (0.5f, 0 )),

New vertexpositionnormaltexture (New vector3 (1,-1, 0), newvector3 (0, 0, 1), new vector2 (1, 1 )),

New vertexpositionnormaltexture (New vector3 (-1,-1, 0), newvector3 (0, 0, 1), new vector2 (0, 1 ))

};

Note that the normal direction of each vertex is (0, 0, 1), that is, all points to the positive direction of the Z axis, so that the positive direction of the entire triangle is determined to direct to the user from the mobile phone screen.

With this data definition, you can add illumination effects through the basiceffect object. The Code is as follows:

Basiceffect. lightingenabled = true;

Basiceffect. ambientlightcolor = new vector3 (0.1f, 0.1f, 0.1f );

Basiceffect. directionallight0.diffusecolor = color. Red. tovector3 ();

Basiceffect. directionallight0.direction = vector3.normalize (newvector3 (-0.5f, 0.5f,-1 ));

Basiceffect. directionallight0.specularcolor = color. White. tovector3 ();

Basiceffect. directionallight0.enabled = true;

Lightingenabled = true can be used to start the illumination effect. Only when the value of this variable is true will the illumination set in subsequent statements be rendered.

Ambientlightcolor specifies the ambient light color.

You can use basiceffect to set environment light, diffuse reflection light, highlight light, and three directed light effects. In the above Code, the directionallight0 setting determines a property with the direction of light. In these attributes, diffusecolor is the color of the diffuse light, and direction is a normalized three-dimensional Vector used to specify the direction of the light. specularcolor is the color that defines the highlight, enabled is used to enable the effect rendering of the light.

The final running result. The light source is directed from the bottom right corner to the top left corner and points to the inside of the screen. Therefore, the highlight effect in the bottom right corner is obvious. In addition, the entire object is reflected in red by the diffuse reflection, as if it were shining in the sunset.


The remaining illumination effects need to be accumulated continuously in practice. I believe that with the above learning, we can achieve the desired effect in application.

Complete source code for the game1 class is provided in this section:

    public class Game1 : Microsoft.Xna.Framework.Game    {        GraphicsDeviceManager graphics;        Camera camera;        Matrix world = Matrix.Identity;        BasicEffect basicEffect;        VertexPositionNormalTexture[] triangle;        Matrix translateMatrix=Matrix.Identity;        Matrix scaleMatrix = Matrix.Identity;        Matrix rotateMatrix = Matrix.Identity;        Texture2D texture;        public Game1()        {            graphics = new GraphicsDeviceManager(this);            Content.RootDirectory = "Content";            // Frame rate is 30 fps by default for Windows Phone.            TargetElapsedTime = TimeSpan.FromTicks(333333);            // Extend battery life under lock.            InactiveSleepTime = TimeSpan.FromSeconds(1);            graphics.IsFullScreen = true;        }        /// <summary>        /// Allows the game to perform any initialization it needs to before starting to run.        /// This is where it can query for any required services and load any non-graphic        /// related content.  Calling base.Initialize will enumerate through any components        /// and initialize them as well.        /// </summary>        protected override void Initialize()        {            // TODO: Add your initialization logic here            base.Initialize();        }        /// <summary>        /// LoadContent will be called once per game and is the place to load        /// all of your content.        /// </summary>        protected override void LoadContent()        {            camera = new Camera(this, new Vector3(0, 0, 5), Vector3.Zero, Vector3.Up, MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 1.0f, 50.0f);            Components.Add(camera);            basicEffect = new BasicEffect(GraphicsDevice);            triangle = new VertexPositionNormalTexture[]{                new VertexPositionNormalTexture(new Vector3(0, 1, 0),new Vector3(0,0,1), new Vector2(0.5f,0)),                new VertexPositionNormalTexture(new Vector3(1, -1, 0),new Vector3(0,0,1), new Vector2(1,1)),                new VertexPositionNormalTexture(new Vector3(-1,-1, 0),new Vector3(0,0,1), new Vector2(0,1))            };            texture = Content.Load<Texture2D>(@"Tulips");        }        /// <summary>        /// UnloadContent will be called once per game and is the place to unload        /// all content.        /// </summary>        protected override void UnloadContent()        {            // TODO: Unload any non ContentManager content here        }        /// <summary>        /// Allows the game to run logic such as updating the world,        /// checking for collisions, gathering input, and playing audio.        /// </summary>        /// <param name="gameTime">Provides a snapshot of timing values.</param>        protected override void Update(GameTime gameTime)        {            // Allows the game to exit            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)                this.Exit();            TouchPanel.EnabledGestures = GestureType.Tap;            if (TouchPanel.IsGestureAvailable)            {                GestureSample gestureSample = TouchPanel.ReadGesture();                if (gestureSample.GestureType == GestureType.Tap)                {                    translateMatrix *= Matrix.CreateTranslation(0.3f, 0, 0);                     //scaleMatrix = Matrix.CreateScale(0.9f);                    rotateMatrix *= Matrix.CreateRotationY(MathHelper.ToRadians(10));                }            }            base.Update(gameTime);        }        /// <summary>        /// This is called when the game should draw itself.        /// </summary>        /// <param name="gameTime">Provides a snapshot of timing values.</param>        protected override void Draw(GameTime gameTime)        {            GraphicsDevice.Clear(Color.CornflowerBlue);            RasterizerState rasterizerState = new RasterizerState();            rasterizerState.CullMode = CullMode.None;            GraphicsDevice.RasterizerState = rasterizerState;            basicEffect.World = scaleMatrix * translateMatrix * rotateMatrix;            basicEffect.View = camera.view;            basicEffect.Projection = camera.projection;            basicEffect.TextureEnabled = true;            basicEffect.Texture = texture;            GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;            basicEffect.LightingEnabled = true;            basicEffect.AmbientLightColor = new Vector3(0.1f, 0.1f, 0.1f);            basicEffect.DirectionalLight0.DiffuseColor = Color.Red.ToVector3();            basicEffect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(-0.5f, 0.5f, -1));            basicEffect.DirectionalLight0.SpecularColor = Color.White.ToVector3();            basicEffect.DirectionalLight0.Enabled = true;                        foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)            {                pass.Apply();                GraphicsDevice.DrawUserPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleStrip, triangle, 0, 1);            }            base.Draw(gameTime);        }    }

-- Welcome to reprint, please indicate the source of http://blog.csdn.net/caowenbin --


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.