四角形ポリゴンの描画

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 VertexBuffer _vertexBuffer = null;


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

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

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

            // カメラの設定
            this.SettingCamera();

            // 四角形ポリゴンを表示するための頂点バッファを作成
            this._vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored),
                4, this._device, Usage.None, CustomVertex.PositionColored.Format, Pool.Managed);

            // 4点の情報を格納するためのメモリを確保
            CustomVertex.PositionColored[] vertices = new CustomVertex.PositionColored[4];

            // 各頂点を設定
            vertices[0] = new CustomVertex.PositionColored(-4.0f, 4.0f, 0.0f, Color.Red.ToArgb());
            vertices[1] = new CustomVertex.PositionColored(4.0f, 4.0f, 0.0f, Color.Blue.ToArgb());
            vertices[2] = new CustomVertex.PositionColored(-4.0f, -4.0f, 0.0f, Color.Green.ToArgb());
            vertices[3] = new CustomVertex.PositionColored(4.0f, -4.0f, 0.0f, Color.Yellow.ToArgb());

            // 頂点バッファをロックする
            using (GraphicsStream data = this._vertexBuffer.Lock(0, 0, LockFlags.None))
            {
                // 頂点データを頂点バッファにコピーします
                data.Write(vertices);

                // 頂点バッファのロックを解除します
                this._vertexBuffer.Unlock();
            }

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

            return true;
        }

        /// <summary>
        /// メインループ処理
        /// </summary>
        public void MainLoop()
        {
            // 描画内容を単色でクリアし、Zバッファもクリア
            this._device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.DarkBlue, 1.0f, 0);

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


            // 頂点バッファをデバイスのデータストリームにバインド
            this._device.SetStreamSource(0, this._vertexBuffer, 0);

            // 描画する頂点のフォーマットをセット
            this._device.VertexFormat = CustomVertex.PositionColored.Format;

            // レンダリング(描画)
            this._device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);


            // 文字列の描画
            this._font.DrawText(null, "四角形ポリゴン", 0, 0, Color.White);

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

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

        /// <summary>
        /// リソースの破棄をするために呼ばれる
        /// </summary>
        public void Dispose()
        {
            // 頂点バッファを解放
            if (this._vertexBuffer != null)
            {
                this._vertexBuffer.Dispose();
            }

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

            // Direct3D デバイスのリソース解放
            if (this._device != null)
            {
                this._device.Dispose();
            }
        }
    }
}
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>
        /// 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>
        /// カメラの設定
        /// </summary>
        private void SettingCamera()
        {
            // ビュー変換行列を設定
            this._device.Transform.View = Matrix.LookAtLH(new Vector3(0.0f, 0.0f, -10.0f),
                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);
        }
    }
}

四角形ポリゴンについてちょっとだけ考えます。 DirectX ではポリゴンは基本的に三角形ポリゴンとして扱い複雑な形状はこの三角形ポリゴンを組み合わせて構成されています。

ということは四角形ポリゴンも三角形ポリゴンで構成することになり、下の図のようになります。

四角形ポリゴン

三角形ポリゴンが二つ必要なので、本来は頂点数は6個必要なのですが、描画するときの PrimitiveType を「PrimitiveType.TriangleStrip」で指定すると4つの頂点で描画できるのでそれを使用します(参照:2Dポリゴンの表示 ページ最下部)。

その際頂点のインデックスは下のようにします。順番は決まっているので注意してください(これに関しては後の Tips で説明します)。

頂点インデックス


/// <summary>
/// 頂点バッファ
/// </summary>
private VertexBuffer _vertexBuffer = null;

頂点バッファはポリゴンの数に関係なくひとつ定義すればいいです。複数の形状がある場合はその分だけ定義します。


// カメラの設定
this.SettingCamera();

カメラの設定もメソッドにまとめました。


// 四角形ポリゴンを表示するための頂点バッファを作成
this._vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored),
    4, this._device, Usage.None, CustomVertex.PositionColored.Format, Pool.Managed);

ほとんど変わりありませんが、頂点を4つ作成するので第2引数に「4」を指定します。


// 4点の情報を格納するためのメモリを確保
CustomVertex.PositionColored[] vertices = new CustomVertex.PositionColored[4];

// 各頂点を設定
vertices[0] = new CustomVertex.PositionColored(-4.0f, 4.0f, 0.0f, Color.Red.ToArgb());
vertices[1] = new CustomVertex.PositionColored(4.0f, 4.0f, 0.0f, Color.Blue.ToArgb());
vertices[2] = new CustomVertex.PositionColored(-4.0f, -4.0f, 0.0f, Color.Green.ToArgb());
vertices[3] = new CustomVertex.PositionColored(4.0f, -4.0f, 0.0f, Color.Yellow.ToArgb());

頂点の数が4つになっただけで、基本的に変わりはありません。四角形になるように頂点の位置を指定します。

頂点位置


// 頂点バッファをロックする
using (GraphicsStream data = this._vertexBuffer.Lock(0, 0, LockFlags.None))
{
    // 頂点データを頂点バッファにコピーします
    data.Write(vertices);

    // 頂点バッファをロック解除します
    this._vertexBuffer.Unlock();
}

ここも変わりありません。


// 頂点バッファをデバイスのデータストリームにバインド
this._device.SetStreamSource(0, this._vertexBuffer, 0);

// 描画する頂点のフォーマットをセット
this._device.VertexFormat = CustomVertex.PositionColored.Format;

// レンダリング(描画)
this._device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2);

上の2つは変わりありません。「Device.DrawPrimitives」でプリミティブタイプを「PrimitiveType.TriangleStrip」で指定し、プリミティブの数が2つ(三角形ポリゴンが2つ)なので、「2」を指定します。


// 頂点バッファを解放
if (this._vertexBuffer != null)
{
    this._vertexBuffer.Dispose();
}

前回と同様です。