マテリアルによる半透明処理

Page creation date :

The page you are currently viewing does not support the selected display language.

マテリアルを使用した半透明処理を行います。今回は簡単な距離判定を行い、反対側から見ても問題なく透けて見えるようにしています。

マテリアルによる半透明処理

今回のメインコードファイルを載せます。

MainSample.cs

>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace MDXSample
{
    /// <summary>
    /// メインサンプルクラス
    /// </summary>
    public partial class MainSample : IDisposable
    {
        /// <summary>
        /// ティーポットメッシュ
        /// </summary>
        private Mesh _mesh = null;

        /// <summary>
        /// 青ティーポットの位置
        /// </summary>
        private Vector3 _blueTeapotPosition = new Vector3(1.0f, 0.0f, 2.0f);

        /// <summary>
        /// 赤ティーポットの位置
        /// </summary>
        private Vector3 _redTeapotPosition = new Vector3(0.0f, 0.0f, 0.0f);

        /// <summary>
        /// 青ティーポットのマテリアル
        /// </summary>
        private Material _blueTeapotMaterial;

        /// <summary>
        /// 青ティーポットのマテリアル
        /// </summary>
        private Material _redTeapotMaterial;


        /// <summary>
        /// アプリケーションの初期化
        /// </summary>
        /// <param name="topLevelForm">トップレベルウインドウ</param>
        /// <returns>全ての初期化がOKなら true, ひとつでも失敗したら false を返すようにする</returns>
        /// <remarks>
        /// false を返した場合は、自動的にアプリケーションが終了するようになっている
        /// </remarks>
        public bool InitializeApplication(MainForm topLevelForm)
        {
            // フォームの参照を保持
            this._form = topLevelForm;

            // 入力イベント作成
            this.CreateInputEvent(topLevelForm);


            try
            {
                // Direct3D デバイス作成
                this.CreateDevice(topLevelForm);

                // フォントの作成
                this.CreateFont();
            }
            catch (DirectXException ex)
            {
                // 例外発生
                MessageBox.Show(ex.ToString(), "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            // XYZライン作成
            this.CreateXYZLine();


            // ティーポットメッシュの作成
            this._mesh = Mesh.Teapot(this._device);

            // 青のマテリアル
            this._blueTeapotMaterial.Diffuse = Color.FromArgb(192, 64, 64, 255);
            this._blueTeapotMaterial.Ambient = Color.FromArgb(192, 64, 64, 64);

            // 赤のマテリアル
            this._redTeapotMaterial.Diffuse = Color.FromArgb(192, 255, 64, 64);
            this._redTeapotMaterial.Ambient = Color.FromArgb(192, 64, 64, 64);


            // ライトを設定
            this.SettingLight();

            // アルファブレンディング方法を設定
            this._device.RenderState.SourceBlend = Blend.SourceAlpha;
            this._device.RenderState.DestinationBlend = Blend.InvSourceAlpha;

            // アルファブレンディングを有効にする
            this._device.RenderState.AlphaBlendEnable = true;

            return true;
        }

        /// <summary>
        /// メインループ処理
        /// </summary>
        public void MainLoop()
        {
            // カメラの設定
            this.SettingCamera();


            // 描画内容を単色でクリアし、Zバッファもクリア
            this._device.Clear(ClearFlags.ZBuffer | ClearFlags.Target, Color.SkyBlue, 1.0f, 0);

            // 「BeginScene」と「EndScene」の間に描画内容を記述する
            this._device.BeginScene();


            // ライトを無効
            this._device.RenderState.Lighting = false;

            // 原点に配置
            this._device.SetTransform(TransformType.World, Matrix.Identity);

            // XYZラインを描画
            this.RenderXYZLine();


            // ライトを有効
            this._device.RenderState.Lighting = true;

            // レンズの位置を計算
            float radius = this._lensPosRadius;
            float theta = Geometry.DegreeToRadian(this._lensPosTheta);
            float fai = Geometry.DegreeToRadian(this._lensPosPhi);
            Vector3 lensPosition = new Vector3(
                (float)(radius * Math.Cos(theta) * Math.Cos(fai)),
                (float)(radius * Math.Sin(fai)),
                (float)(radius * Math.Sin(theta) * Math.Cos(fai)));

            // どちらが近いか比較
            if (Vector3.Length(lensPosition - this._redTeapotPosition) <
                Vector3.Length(lensPosition - this._blueTeapotPosition))
            {
                // 赤のティーポットの方が近い場合、青のティーポットから描画
                this.RenderTeapot(this._blueTeapotMaterial, this._blueTeapotPosition);
                this.RenderTeapot(this._redTeapotMaterial, this._redTeapotPosition);
            }
            else
            {
                // 青のティーポットの方が近い、赤のティーポットから描画
                this.RenderTeapot(this._redTeapotMaterial, this._redTeapotPosition);
                this.RenderTeapot(this._blueTeapotMaterial, this._blueTeapotPosition);
            }


            // 文字列の描画
            this._font.DrawText(null, "[Escape]終了", 0, 0, Color.White);
            this._font.DrawText(null, "θ:" + this._lensPosTheta, 0, 12, Color.White);
            this._font.DrawText(null, "φ:" + this._lensPosPhi, 0, 24, Color.White);

            // 描画はここまで
            this._device.EndScene();

            // 実際のディスプレイに描画
            this._device.Present();

            // アプリケーションの終了操作
            if (this._keys[(int)Keys.Escape])
            {
                this._form.Close();
            }
        }

        /// <summary>
        /// ティーポットの描画
        /// </summary>
        /// <param name="material">マテリアル</param>
        /// <param name="position">位置</param>
        private void RenderTeapot(Material material, Vector3 position)
        {
            // マテリアル
            this._device.Material = material;

            // 座標変換
            this._device.SetTransform(TransformType.World, Matrix.Translation(position));

            // ティーポットを描画
            this._mesh.DrawSubset(0);
        }

        /// <summary>
        /// リソースの破棄をするために呼ばれる
        /// </summary>
        public void Dispose()
        {
            // メッシュの解放
            if (this._mesh != null)
            {
                this._mesh.Dispose();
            }
            
            // リソースの破棄
            this.DisposeResource();
        }
    }
}
MainSamplePartial.cs ファイルのコードはこちらです。

MainSamplePartial.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace MDXSample
{
    public partial class MainSample
    {
        /// <summary>
        /// メインフォーム
        /// </summary>
        private MainForm _form = null;

        /// <summary>
        /// Direct3D デバイス
        /// </summary>
        private Device _device = null;

        /// <summary>
        /// Direct3D 用フォント
        /// </summary>
        private Microsoft.DirectX.Direct3D.Font _font = null;

        /// <summary>
        /// キーのプレス判定
        /// </summary>
        private bool[] _keys = new bool[256];

        /// <summary>
        /// 1つ前のマウスの位置
        /// </summary>
        private Point _oldMousePoint = Point.Empty;

        /// <summary>
        /// カメラレンズの位置(R)
        /// </summary>
        private float _lensPosRadius = 6.0f;

        /// <summary>
        /// カメラレンズの位置(θ)
        /// </summary>
        private float _lensPosTheta = 255.0f;

        /// <summary>
        /// カメラレンズの位置(φ)
        /// </summary>
        private float _lensPosPhi = 10.0f;

        /// <summary>
        /// XYZライン用頂点バッファ
        /// </summary>
        private VertexBuffer _xyzLineVertexBuffer = null;


        /// <summary>
        /// 入力イベント作成
        /// </summary>
        /// <param name="topLevelForm">トップレベルウインドウ</param>
        private void CreateInputEvent(MainForm topLevelForm)
        {
            // キーイベント作成
            topLevelForm.KeyDown += new KeyEventHandler(this.form_KeyDown);
            topLevelForm.KeyUp += new KeyEventHandler(this.form_KeyUp);

            // マウス移動イベント
            topLevelForm.MouseMove += new MouseEventHandler(this.form_MouseMove);
        }

        /// <summary>
        /// キーボードのキーを押した瞬間
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void form_KeyDown(object sender, KeyEventArgs e)
        {
            // 押されたキーコードのフラグを立てる
            if ((int)e.KeyCode < this._keys.Length)
            {
                this._keys[(int)e.KeyCode] = true;
            }
        }
        /// <summary>
        /// キーボードのキーを放した瞬間
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void form_KeyUp(object sender, KeyEventArgs e)
        {
            // 放したキーコードのフラグを下ろす
            if ((int)e.KeyCode < this._keys.Length)
            {
                this._keys[(int)e.KeyCode] = false;
            }
        }

        /// <summary>
        /// マウス移動イベント
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void form_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                // 回転
                this._lensPosTheta -= e.Location.X - this._oldMousePoint.X;
                this._lensPosPhi += e.Location.Y - this._oldMousePoint.Y;

                // φに関しては制限をつける
                if (this._lensPosPhi >= 90.0f)
                {
                    this._lensPosPhi = 89.9999f;
                }
                else if (this._lensPosPhi <= -90.0f)
                {
                    this._lensPosPhi = -89.9999f;
                }
            }
            // ??ウスの位置を記憶
            this._oldMousePoint = e.Location;
        }

        /// <summary>
        /// Direct3D デバイスの作成
        /// </summary>
        /// <param name="topLevelForm">トップレベルウインドウ</param>
        private void CreateDevice(MainForm topLevelForm)
        {
            // PresentParameters。デバイスを作成する際に必須
            // どのような環境でデバイスを使用するかを設定する
            PresentParameters pp = new PresentParameters();

            // ウインドウモードなら true、フルスクリーンモードなら false を指定
            pp.Windowed = true;

            // スワップ効果。とりあえず「Discard」を指定。
            pp.SwapEffect = SwapEffect.Discard;

            // 深度ステンシルバッファ。3Dでは前後関係があるので通常 true
            pp.EnableAutoDepthStencil = true;

            // 自動深度ステンシル サーフェイスのフォーマット。
            // 「D16」に対応しているビデオカードは多いが、前後関係の精度があまりよくない。
            // できれば「D24S8」を指定したいところ。
            pp.AutoDepthStencilFormat = DepthFormat.D16;

            try
            {
                // デバイスの作成
                this.CreateDevice(topLevelForm, pp);
            }
            catch (DirectXException ex)
            {
                // 例外発生
                throw ex;
            }
        }
        /// <summary>
        /// Direct3D デバイスの作成
        /// </summary>
        /// <param name="topLevelForm">トップレベルウインドウ</param>
        /// <param name="presentationParameters">PresentParameters 構造体</param>
        private void CreateDevice(MainForm topLevelForm, PresentParameters presentationParameters)
        {
            // 実際にデバイスを作成します。
            // 常に最高のパフォーマンスで作成を試み、
            // 失敗したら下位パフォーマンスで作成するようにしている。
            try
            {
                // ハードウェアによる頂点処理、ラスタライズを行う
                // 最高のパフォーマンスで処理を行えます。
                // ビデオカードによっては実装できない処理が存在します。
                this._device = new Device(0, DeviceType.Hardware, topLevelForm.Handle,
                    CreateFlags.HardwareVertexProcessing, presentationParameters);
            }
            catch (DirectXException ex1)
            {
                // 作成に失敗
                Debug.WriteLine(ex1.ToString());
                try
                {
                    // ソフトウェアによる頂点処理、ハードウェアによるラスタライズを行う
                    this._device = new Device(0, DeviceType.Hardware, topLevelForm.Handle,
                        CreateFlags.SoftwareVertexProcessing, presentationParameters);
                }
                catch (DirectXException ex2)
                {
                    // 作成に失敗
                    Debug.WriteLine(ex2.ToString());
                    try
                    {
                        // ソフトウェアによる頂点処理、ラスタライズを行う
                        // パフォーマンスはとても低いです。
                        // その代わり、ほとんどの処理を制限なく行えます。
                        this._device = new Device(0, DeviceType.Reference, topLevelForm.Handle,
                            CreateFlags.SoftwareVertexProcessing, presentationParameters);
                    }
                    catch (DirectXException ex3)
                    {
                        // 作成に失敗
                        // 事実上デバイスは作成で???ません。
                        throw ex3;
                    }
                }
            }
        }

        /// <summary>
        /// フォントの作成
        /// </summary>
        private void CreateFont()
        {
            try
            {
                // フォントデータの構造体を作成
                FontDescription fd = new FontDescription();

                // 構造体に必要なデータをセット
                fd.Height = 12;
                fd.FaceName = "MS ゴシック";

                // フォントを作成
                this._font = new Microsoft.DirectX.Direct3D.Font(this._device, fd);
            }
            catch (DirectXException ex)
            {
                // 例外発生
                throw ex;
            }
        }

        /// <summary>
        /// XYZライン作成
        /// </summary>
        private void CreateXYZLine()
        {
            // 6つ分の頂点を作成
            this._xyzLineVertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored),
                6, this._device, Usage.None, CustomVertex.PositionColored.Format, Pool.Managed);

            // 頂点バッファをロックして、位置、色情報を書き込む
            using (GraphicsStream data = this._xyzLineVertexBuffer.Lock(0, 0, LockFlags.None))
            {
                // 今回は各XYZのラインを原点(0.0f, 0.0f, 0.0f)からプラス方向に 10.0f 伸びた線を作成
                data.Write(new CustomVertex.PositionColored(0.0f, 0.0f, 0.0f, Color.Red.ToArgb()));
                data.Write(new CustomVertex.PositionColored(10.0f, 0.0f, 0.0f, Color.Red.ToArgb()));
                data.Write(new CustomVertex.PositionColored(0.0f, 0.0f, 0.0f, Color.Green.ToArgb()));
                data.Write(new CustomVertex.PositionColored(0.0f, 10.0f, 0.0f, Color.Green.ToArgb()));
                data.Write(new CustomVertex.PositionColored(0.0f, 0.0f, 0.0f, Color.Blue.ToArgb()));
                data.Write(new CustomVertex.PositionColored(0.0f, 0.0f, 10.0f, Color.Blue.ToArgb()));

                this._xyzLineVertexBuffer.Unlock();
            }
        }

        /// <summary>
        /// ライトの設定
        /// </summary>
        private void SettingLight()
        {
            // 平行光線を使用
            this._device.Lights[0].Type = LightType.Directional;

            // ライトの方向
            this._device.Lights[0].Direction = new Vector3(1.0f, -1.5f, 2.0f);

            // 光の色は白
            this._device.Lights[0].Diffuse = Color.White;

            // 環境光
            this._device.Lights[0].Ambient = Color.FromArgb(255, 128, 128, 128);

            // 0 番のライトを有効
            this._device.Lights[0].Enabled = true;

            // 0 番のライトを更新
            this._device.Lights[0].Update();
        }

        /// <summary>
        /// カメラの設定
        /// </summary>
        private void SettingCamera()
        {
            // レンズの位置を三次元極座標で変換
            float radius = this._lensPosRadius;
            float theta = Geometry.DegreeToRadian(this._lensPosTheta);
            float phi = Geometry.DegreeToRadian(this._lensPosPhi);
            Vector3 lensPosition = new Vector3(
                (float)(radius * Math.Cos(theta) * Math.Cos(phi)),
                (float)(radius * Math.Sin(phi)),
                (float)(radius * Math.Sin(theta) * Math.Cos(phi)));

            // ビュー変換行列を設定
            this._device.Transform.View = Matrix.LookAtLH(
                lensPosition, new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 1.0f, 0.0f));

            // 射影変換を設定
            this._device.Transform.Projection = Matrix.PerspectiveFovLH(
                Geometry.DegreeToRadian(60.0f),
                (float)this._device.Viewport.Width / (float)this._device.Viewport.Height,
                1.0f, 100.0f);
        }

        /// <summary>
        /// XYZライン描画
        /// </summary>
        private void RenderXYZLine()
        {
            this._device.SetStreamSource(0, this._xyzLineVertexBuffer, 0);
            this._device.VertexFormat = CustomVertex.PositionColored.Format;
            this._device.DrawPrimitives(PrimitiveType.LineList, 0, 3);
        }

        /// <summary>
        /// リソースの破棄
        /// </summary>
        private void DisposeResource()
        {
            // XYZラインの破棄
            if (this._xyzLineVertexBuffer != null)
            {
                this._xyzLineVertexBuffer.Dispose();
            }

            // フォントのリソース解放
            if (this._font != null)
            {
                this._font.Dispose();
            }

            // Direct3D デバイスのリソース解放
            if (this._device != null)
            {
                this._device.Dispose();
            }
        }
    }
}

/// <summary>
/// ティーポットメッシュ
/// </summary>
private Mesh _mesh = null;

/// <summary>
/// 青ティーポットの位置
/// </summary>
private Vector3 _blueTeapotPosition = new Vector3(1.0f, 0.0f, 2.0f);

/// <summary>
/// 赤ティーポットの位置
/// </summary>
private Vector3 _redTeapotPosition = new Vector3(0.0f, 0.0f, 0.0f);

/// <summary>
/// 青ティーポットのマテリアル
/// </summary>
private Material _blueTeapotMaterial;

/// <summary>
//// 青ティーポットのマテリアル
/// </summary>
private Material _redTeapotMaterial;

今回は2つの色違いティーポットを描画して半透明が行われているかをチェックします。ここではメッシュと、各ティーポットの位置とマテリアルの情報を持つようにします。

位置に関しては動かないのでここで設定しておきます。マテリアルはここでは設定できないので、初期化メソッド内で設定するようにしています。


// 青のマテリアル
this._blueTeapotMaterial.Diffuse = Color.FromArgb(192, 64, 64, 255);
this._blueTeapotMaterial.Ambient = Color.FromArgb(192, 64, 64, 64);

// 赤のマテリアル
this._redTeapotMaterial.Diffuse = Color.FromArgb(192, 255, 64, 64);
this._redTeapotMaterial.Ambient = Color.FromArgb(192, 64, 64, 64);

ここでマテリアルの設定を行っています。前回頂点データによる半透明処理では頂点データのディフューズ色にアルファ値を設定していましたが、マテリアルの場合も同じようにマテリアルにアルファ値を設定します。基本的に違いはこれだけです。


// ライトを設定
this.SettingLight();

// アルファブレンディング方法を設定
this._device.RenderState.SourceBlend = Blend.SourceAlpha;
this._device.RenderState.DestinationBlend = Blend.InvSourceAlpha;

// アルファブレンディングを有効にする
this._device.RenderState.AlphaBlendEnable = true;

マテリアルを使用するので同時にライトの設定も行います。前回同様アルファブレンディングも有効にしておきます。


// レンズの位置を計算
float radius = this._lensPosRadius;
float theta = Geometry.DegreeToRadian(this._lensPosTheta);
float fai = Geometry.DegreeToRadian(this._lensPosPhi);
Vector3 lensPosition = new Vector3(
    (float)(radius * Math.Cos(theta) * Math.Cos(fai)),
    (float)(radius * Math.Sin(fai)),
    (float)(radius * Math.Sin(theta) * Math.Cos(fai)));

後はメッシュを描画すれば前回同様、半透明に見えるのですが、それだとあまりにも簡単すぎるので今回はカメラの方向を変えても奥のポリゴン(ティーポット)から描画できるように簡単な距離判定を行います。

まずカメラの位置を使わないといけないので、あらかじめ計算しておきます。実際にカメラのレンズ位置を計算する式とまったく同じです。


// どちらが近いか比較
if (Vector3.Length(lensPosition - this._redTeapotPosition) <
    Vector3.Length(lensPosition - this._blueTeapotPosition))
{
    // 赤のティーポットの方が近い場合、青のティーポットから描画
    this.RenderTeapot(this._blueTeapotMaterial, this._blueTeapotPosition);
    this.RenderTeapot(this._redTeapotMaterial, this._redTeapotPosition);
}
else
{
    // 青のティーポットの方が近い、赤のティーポットから描画
    this.RenderTeapot(this._redTeapotMaterial, this._redTeapotPosition);
    this.RenderTeapot(this._blueTeapotMaterial, this._blueTeapotPosition);
}

レンズの位置を求めたら、各ティーポットとの距離を計算します。

ベクトルから距離を求めるには「Vector3.Length」メソッドで求めることが出来ます。

距離を求めるには、青のティーポットの図のように「原点からカメラの位置へのベクトル」から「原点からティーポットの位置へのベクトル」分を引けば「ティーポットからカメラの位置へのベクトル」が求まるのでその長さを計算します。

赤のティーポットに関しては原点位置にあるので、カメラ位置へのベクトルをそのまま使用すればいいのですが、念のため計算しています。

赤のティーポットの距離青のティーポットの距離
赤のティーポットの位置は原点なので引いても値は変化しない

2つの距離が求まったら長さの判定を行い、「」のティーポットが近いなら遠くにある「」のティーポットから順番に描画します。「」のティーポットが近いなら遠くにある「」のティーポットから順番に描画します。

そうするとわざわざZバッファを無効にしなくてもうまく半透明処理が出来ていることがわかります。(ちなみに暗いのはライトの関係です

距離判定での描画

ただ、今回はソートしているわけではないので、実際のプログラミングでは描画順リストを作成してソートするのが普通だと思います。それは各自作ってみてください。

「RenderTeapot」メソッドは描画処理をまとめるために作成したものであり、マテリアルと位置を引数として渡せばティーポットを描画するようになっています。(次セクション参照)


/// <summary>
/// ティーポットの描画
/// </summary>
/// <param name="material">マテリアル</param>
/// <param name="position">位置</param>
private void RenderTeapot(Material material, Vector3 position)
{
    // マテリアル
    this._device.Material = material;

    // 座標変換
    this._device.SetTransform(TransformType.World, Matrix.Translation(position));

    // ティーポットを描画
    this._mesh.DrawSubset(0);
}

渡されたマテリアルと位置によってティーポットを描画するメソッドです。何か特別な処理をしているわけではありません。