Реализация точечного источника света в XNA 4.0. Часть 1

В этот раз мы сделаем простую реализацию точечных источников света.

Точечные источники могут очень красиво дополнить сцены, освещенные направленными источниками света, так что пришло время посмотреть на одну из возможных реализаций точечных источников света на XNA 4.0.

Но сначала как обычно я создам сцену, размещу в ней несколько разноцветных объектов. Для этого мне снова понадобится класс, который будет содержать в себе примитив, его позицию и цвет.

class GameObject
{
GeometricPrimitive primitive;
Vector3 position;
Color color;

public GameObject(GeometricPrimitive primitive, Vector3 position, Color color)
{
this.primitive = primitive;
this.position = position;
this.color = color;
}

public void Draw(Matrix world, Matrix view, Matrix projection)
{
world *= Matrix.CreateTranslation(position);
primitive.Draw(world, view, projection, color);
}

}

Теперь в Game создадим несколько примитивом. У нас должна получиться сцена, в которой на некоторой плоскости расположены чайники. В качестве плоскости нам пока подойдет большой куб.

 
List<GameObject> primitives = new List<GameObject>();

public Game1()
{
    graphics = new GraphicsDeviceManager(this);
    Content.RootDirectory = "Content";
 
 
    graphics.PreferredBackBufferWidth = 640;
    graphics.PreferredBackBufferHeight = 480;
 
}

/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);
 
    // TODO: use this.Content to load your game content here
 
 
    primitives.Add (new GameObject(new CubePrimitive(GraphicsDevice, 6), new Vector3(0,-4,0), Color.Green));
     primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(-0.5f, -0.65f, 1), Color.Yellow));
     primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 1f, 40), new Vector3(1, -0.5f, 1), Color.Red));
     primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(-0.5f, -0.65f, 2), Color.Tomato));
     primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(0.5f, -0.65f, 3f), Color.Gray));
     primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(0.5f, -0.65f, 1), Color.Brown));
 
}

/// <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.Black);
 
    // TODO: Add your drawing code here
    //Matrix world = Matrix.CreateRotationY((float)gameTime.TotalGameTime.TotalSeconds);
    Matrix world = Matrix.Identity;
 
    Vector3 cameraPosition = new Vector3(0, 0, 5);
 
    Matrix view = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
    Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), GraphicsDevice.Viewport.AspectRatio, 0.1f, 10f);
 
 
 
    foreach (var item in primitives)
    {
        item.Draw(world, view, projection);
    }
 
 
 
    base.Draw(gameTime);
}

Получится вот такая сцена:

Пока у нас еще нет никаких шейдеров, но уже сейчас можно расположить точечные источники света. Мы будем хранить во-первый координаты источников света в отдельном списке, а во-вторых создадим для каждого источника света примитив-сферу, чтобы визуально оценивать качество работы шейдера, который мы создадим.

 
List<Vector3> pointLights = new List<Vector3>();
 
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);
 
    // TODO: use this.Content to load your game content here
 
    lightEffect = Content.Load<Effect>("light");
 
    primitives.Add(new GameObject(new CubePrimitive(GraphicsDevice, 6), new Vector3(0, -4, 0), Color.Green));
    primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(-0.5f, -0.65f, 1), Color.Yellow));
    primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 1f, 40), new Vector3(1, -0.5f, 1), Color.Red));
    primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(-0.5f, -0.65f, 2), Color.Tomato));
    primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(0.5f, -0.65f, 3f), Color.Gray));
    primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(0.5f, -0.65f, 1), Color.Brown));
 
    Random r = new Random();
    for (int i = 0; i < 10; i++)
    {
        var pos = new Vector3((float)r.NextDouble() * 4f - 2f,  - 1.0f, (float)r.NextDouble() * 4f - 2f);
        pointLights.Add(pos);
 
        primitives.Add(new GameObject(new SpherePrimitive(GraphicsDevice, 0.1f, 10), pos, Color.White));
    }
}

Все готово для того, чтобы создать шейдер. Приступим:

 
#define MAXLIGHTS 30
bool xLightsEnabled;
int xLightCount;
float3 xLights[MAXLIGHTS];
 
 
 
float4x4 World;
float4x4 View;
float4x4 Projection;
float4 Color;
 
// TODO: add effect parameters here.
 
struct VertexShaderInput
{
    float4 Position : POSITION0;
    float3 Normal : NORMAL0;
    // TODO: add input channels such as texture
    // coordinates and vertex colors here.
};
 
struct VertexShaderOutput
{
    float4 Position : POSITION0;
          float3 WorldPosition : TEXCOORD1;
          // TODO: add vertex shader outputs such as colors and texture
    // coordinates here. These values will automatically be interpolated
    // over the triangle, and provided as input to your pixel shader.
};
 
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
 
    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);
 
    // TODO: add your vertex shader code here.
          output.WorldPosition = worldPosition;
 
 
    return output;
}
 
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 color = Color;
          float3 light = float3(0.1f,0.1f,0.1f);
 
    if (xLightsEnabled)
    for (int i = 0; i < xLightCount; i++)
                    light += (1 - saturate(distance(xLights[i], input.WorldPosition) * 1.5));
 
          color.rgb *= light;
          
    return color;
}
 
technique Technique1
{
    pass Pass1
    {
        // TODO: set renderstates here.
 
        VertexShader = compile vs_3_0 VertexShaderFunction();
        PixelShader = compile ps_3_0 PixelShaderFunction();
    }
}

Обратите внимание на то, что сейчас освещенность пикселя вычисляется неправильно с точки зрения физики. На самом деле нужно учитывать каждый источник света по модели Ламберта. Но для начала будем использовать такой просто алгоритм: Для каждого источника определяем расстояние до точки в пространстве мировых координат. Домножаем на некоторую константу, приводим к диапазону [0, 1]. Дальше к общей освещенности прибавляем единицу минус полученное только что значение.

Теперь вернемся к GameObject и допишем в него метод, который будет использовать произвольный эффект вместо BasicEffect. В нем же зададим нужные параметры эффекта.

 
public void Draw(Matrix world, Matrix view, Matrix projection, Effect effect)
{
    world *= Matrix.CreateTranslation(position);
 
    effect.Parameters["World"].SetValue(world);
    effect.Parameters["View"].SetValue(view);
    effect.Parameters["Projection"].SetValue(projection);
    effect.Parameters["Color"].SetValue(color.ToVector4());
    primitive.Draw(effect);
}

Теперь осталось в Draw вызвать правильный метод и передать все оставшиеся параметры в шейдер.

 
/// <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.Black);
 
    // TODO: Add your drawing code here
    //Matrix world = Matrix.CreateRotationY((float)gameTime.TotalGameTime.TotalSeconds);
    Matrix world = Matrix.Identity;
 
    Vector3 cameraPosition = new Vector3(0, 0, 5);
 
    Matrix view = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
    Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), GraphicsDevice.Viewport.AspectRatio, 0.1f, 10f);
 
 
     lightEffect.Parameters["xLights"].SetValue(pointLights.ToArray());
     lightEffect.Parameters["xLightCount"].SetValue(10);
     lightEffect.Parameters["xLightsEnabled"].SetValue(true);
  
     foreach (var item in primitives)
     {
         item.Draw(world, view, projection, lightEffect);
     }
 
 
 
    base.Draw(gameTime);
}

 


 

Исходный код:

 

Game1.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Primitives3D;
 
namespace PointLightGame
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
 
        List<GameObject> primitives = new List<GameObject>();
 
        Effect lightEffect;
 
        List<Vector3> pointLights = new List<Vector3>();
 
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
 
 
            graphics.PreferredBackBufferWidth = 640;
            graphics.PreferredBackBufferHeight = 480;
 
        }
 
        /// <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()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
 
            // TODO: use this.Content to load your game content here
 
            lightEffect = Content.Load<Effect>("light");
 
            primitives.Add(new GameObject(new CubePrimitive(GraphicsDevice, 6), new Vector3(0, -4, 0), Color.Green));
            primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(-0.5f, -0.65f, 1), Color.Yellow));
            primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 1f, 40), new Vector3(1, -0.5f, 1), Color.Red));
            primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(-0.5f, -0.65f, 2), Color.Tomato));
            primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(0.5f, -0.65f, 3f), Color.Gray));
            primitives.Add(new GameObject(new TeapotPrimitive(GraphicsDevice, 0.3f, 40), new Vector3(0.5f, -0.65f, 1), Color.Brown));
 
            Random r = new Random();
            for (int i = 0; i < 10; i++)
            {
                var pos = new Vector3((float)r.NextDouble() * 4f - 2f, -0.8f, (float)r.NextDouble() * 4f - 2f);
                pointLights.Add(pos);
 
                primitives.Add(new GameObject(new SpherePrimitive(GraphicsDevice, 0.1f, 10), pos, Color.White));
            }
        }
 
        /// <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();
 
            // TODO: Add your update logic here
 
            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.Black);
 
    // TODO: Add your drawing code here
    //Matrix world = Matrix.CreateRotationY((float)gameTime.TotalGameTime.TotalSeconds);
    Matrix world = Matrix.Identity;
 
    Vector3 cameraPosition = new Vector3(0, 0, 5);
 
    Matrix view = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
    Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), GraphicsDevice.Viewport.AspectRatio, 0.1f, 10f);
 
 
    lightEffect.Parameters["xLights"].SetValue(pointLights.ToArray());
    lightEffect.Parameters["xLightCount"].SetValue(10);
    lightEffect.Parameters["xLightsEnabled"].SetValue(true);
 
    foreach (var item in primitives)
    {
        item.Draw(world, view, projection, lightEffect);
    }
 
 
 
    base.Draw(gameTime);
}
    }
}

 

 

 

GameObject.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Primitives3D;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
 
namespace PointLightGame
{
    class GameObject
    {
        GeometricPrimitive primitive;
        Vector3 position;
        Color color;
 
        public GameObject(GeometricPrimitive primitive, Vector3 position, Color color)
        {
            this.primitive = primitive;
            this.position = position;
            this.color = color;
        }
 
        public void Draw(Matrix world, Matrix view, Matrix projection)
        {
            world *= Matrix.CreateTranslation(position);
            primitive.Draw(world, view, projection, color);
        }
 
 
        public void Draw(Matrix world, Matrix view, Matrix projection, Effect effect)
        {
            world *= Matrix.CreateTranslation(position);
 
            effect.Parameters["World"].SetValue(world);
            effect.Parameters["View"].SetValue(view);
            effect.Parameters["Projection"].SetValue(projection);
            effect.Parameters["Color"].SetValue(color.ToVector4());
            primitive.Draw(effect);
        }
 
    }
 
}

 

 

 

Light.fx

 

#define MAXLIGHTS 30
bool xLightsEnabled;
int xLightCount;
float3 xLights[MAXLIGHTS];
 
 
 
float4x4 World;
float4x4 View;
float4x4 Projection;
float4 Color;
 
// TODO: add effect parameters here.
 
struct VertexShaderInput
{
    float4 Position : POSITION0;
    float3 Normal : NORMAL0;
    // TODO: add input channels such as texture
    // coordinates and vertex colors here.
};
 
struct VertexShaderOutput
{
    float4 Position : POSITION0;
          float3 WorldPosition : TEXCOORD1;
          // TODO: add vertex shader outputs such as colors and texture
    // coordinates here. These values will automatically be interpolated
    // over the triangle, and provided as input to your pixel shader.
};
 
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
 
    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);
 
    // TODO: add your vertex shader code here.
          output.WorldPosition = worldPosition;
 
 
    return output;
}
 
float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 color = Color;
          float3 light = float3(0.1f,0.1f,0.1f);
 
    if (xLightsEnabled)
    for (int i = 0; i < xLightCount; i++)
                    light += (1 - saturate(distance(xLights[i], input.WorldPosition) * 1.5));
 
          color.rgb *= light;
          
    return color;
}
 
technique Technique1
{
    pass Pass1
    {
        // TODO: set renderstates here.
 
        VertexShader = compile vs_3_0 VertexShaderFunction();
        PixelShader = compile ps_3_0 PixelShaderFunction();
    }
}

 

 

 

Запись опубликована в рубрике Компьютерная графика с метками , , , , , , , , . Добавьте в закладки постоянную ссылку.

Оставьте комментарий