忍者ブログ

Memeplexes

プログラミング、3DCGとその他いろいろについて

XNA爆発チュートリアル その11 ポイントサイズの調節

XNA爆発チュートリアルその10のつづきです。

だいたい機能がまとまってきたので
あら捜しをしていこうとおもいます。

まず最初に気になるのは、カメラからの距離によって
爆発の表示がおかしくなるということです。
近づけば近づくほど、バラバラになってしまいます。


explosionTutorialDistance4.jpgカメラからの距離:4

explosionTutorialDistance3.jpgカメラからの距離:3

explosionTutorialDistance2.jpgカメラからの距離:2

explosionTutorialDistance1.jpgカメラからの距離:1

カメラからの距離が1になるともうバラバラすぎで爆発には見えません。

これはXNA爆発で取り扱った問題と似ています(あちらのほうが症状は軽いですが)。

ここでのこの現象の原因は、それぞれの炎の大きさが固定だということです。
ExplosionRenderer.Drawメソッド内で、

RenderState.PointSize = 50;

としているのがまずいのです。
ここでセットしたポイントのサイズはスクリーン座標上の大きさで、固定なのです。

問題を解決するには、XNA Creators ClubのParticle 3Dサンプルのように、
HLSLで書いたエフェクトファイルで、ポイントサイズが
カメラからの距離を考慮するように調節しなければなりません。

こうですね:

ExplosionShader.fx
float4x4 View;
float4x4 Projection;
float ViewportHeight;

float3 Center;
float Age;
float StartLife;

float PointSize;

texture ExplosionTexture;

sampler explosionSampler = sampler_state
{
	Texture = <ExplosionTexture>;
};

struct ExplosionVertexShaderOutput
{
	float4 Position : POSITION;
	float4 Color : COLOR;
	float PointSize : PSIZE;
};

float4 ComputeColor(float normalizedAge)
{
	float4 color = 1;
	color.a *= normalizedAge * (1 - normalizedAge) * (1 - normalizedAge) * 6.7;
	return color;
}

ExplosionVertexShaderOutput ExplosionVertexShader(float3 velocity:COLOR)
{
	ExplosionVertexShaderOutput output;
	float4 worldPosition = float4(velocity * Age + Center, 1);
	output.Position = mul(worldPosition, mul(View, Projection));
	output.Color = ComputeColor(Age / StartLife);
	output.PointSize = PointSize * Projection._m11 / output.Position.w * ViewportHeight / 2;
	return output;
}

float4 ExplosionPixelShader(
	float2 textureCoordinate:TEXCOORD,
	float4 color:COLOR
	):COLOR
{
	return tex2D(explosionSampler, textureCoordinate) * color;
}

technique ExplosionShaderTechnique
{
	pass P0
	{
		VertexShader = compile vs_2_0 ExplosionVertexShader();
		PixelShader = compile ps_2_0 ExplosionPixelShader();
	}
}

頂点シェーダの戻り値の構造体ExplosionVertexShaderOutputのメンバ、
PointSizeはC#側のRenderState.PointSizeにとってかわります。

このメンバに、それなりの計算をすることでポイントのスクリーン上でのサイズを入れます。
気をつけるべきなのは、スクリーン上でのサイズが必要なので、スクリーンの大きさが必要になることです。
(頂点の座標はスクリーンの横縦をそれぞれ2とした-1~1の座標なんですけどね)
そこで描画するビューポートの高さを表すViewportHeightというグローバル変数を使います。
(というか、Particle 3Dサンプルがそうしています。)

こうして出来たエフェクトに、C#側からPointSizeとViewportHeightをセットしてやります。
そうすると、カメラから遠くなればそれぞれの爆炎は小さくなりますし、近づけば大きくなるわけです。

ExplosionRenderer.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System.Collections.Generic;


public class ExplosionRenderer : Microsoft.Xna.Framework.DrawableGameComponent
{
    private Effect effect;
    private VertexDeclaration vertexDeclaration;
    private VertexVelocity[] vertices;

    private ContentManager content;
    private static System.Random random = new System.Random();

    private Matrix view;
    private Matrix projection;

    private List<Explosion> explosions = new List<Explosion>();


    public ExplosionRenderer(Game game)
        : base(game)
    {
        content = new ContentManager(game.Services);
    }


    public override void Initialize()
    {
        vertices = new VertexVelocity[30];

        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i].Velocity = randomVector3()/10;
        }

        base.Initialize();
    }

    Vector3 randomVector3()
    {
        return new Vector3(
            (float)(random.NextDouble() * 2 - 1),
            (float)(random.NextDouble() * 2 - 1),
            (float)(random.NextDouble() * 2 - 1)
            );
    }

    protected override void LoadGraphicsContent(bool loadAllContent)
    {
        if (loadAllContent)
        {
            effect = content.Load<Effect>("Content/ExplosionShader");
            effect.Parameters["ExplosionTexture"].SetValue(
                content.Load<Texture2D>("Content/explosion")
                );

            vertexDeclaration = new VertexDeclaration(
                GraphicsDevice,
                VertexVelocity.VertexElements
                );
        }
    }


    protected override void UnloadGraphicsContent(bool unloadAllContent)
    {
        if (unloadAllContent) { content.Unload(); }
    }

    public override void Update(GameTime gameTime)
    {
        foreach (Explosion explosion in explosions)
        { explosion.Update(gameTime); }

        explosions.RemoveAll(
            delegate(Explosion explosion) { return explosion.Life < 0; }
            );
    }

    public override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        GraphicsDevice.RenderState.PointSize = 50;
        GraphicsDevice.RenderState.PointSpriteEnable = true;

        GraphicsDevice.RenderState.AlphaBlendEnable = true;
        GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
        GraphicsDevice.RenderState.DestinationBlend = Blend.One;
        GraphicsDevice.RenderState.DepthBufferWriteEnable = false;

        GraphicsDevice.VertexDeclaration = vertexDeclaration;

        effect.Parameters["View"].SetValue(view);
        effect.Parameters["Projection"].SetValue(projection);
        effect.Parameters["ViewportHeight"].SetValue(
            GraphicsDevice.Viewport.Height
            );
        effect.Parameters["PointSize"].SetValue(0.3f);

        foreach (Explosion explosion in explosions)
        { drawExplosion(explosion); }

        GraphicsDevice.RenderState.AlphaBlendEnable = false;
        GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
    }

    private void drawExplosion(Explosion explosion)
    {
        effect.Parameters["Center"].SetValue(explosion.Center);
        effect.Parameters["Age"].SetValue(explosion.Age);
        effect.Parameters["StartLife"].SetValue(explosion.StartLife);

        effect.Begin();

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Begin();

            GraphicsDevice.DrawUserPrimitives<VertexVelocity>(
                PrimitiveType.PointList,
                vertices,
                0,
                vertices.Length
                );

            pass.End();
        }

        effect.End();
    }

    public void SetCamera(Matrix view, Matrix projection)
    {
        this.view = view;
        this.projection = projection;
    }

    public void AddExplosion(Explosion explosion)
    {
        this.explosions.Add(explosion);
    }
}


explosionTutorialSizeDistanceIsConsidererd4.jpgカメラからの距離:4

explosionTutorialSizeDistanceIsConsidererd2.jpgカメラからの距離:2

explosionTutorialSizeDistanceIsConsidererd1.jpgカメラからの距離:1


変更前の画像と比べてみてください。
結果は一目りょう然です。

ポイントスプライトの大きさそのものが大きくなっているので、
カメラとの距離が変わってもきちんと爆発に見えます。











拍手[0回]

PR