Displaying Boxes Using Index Buffers

Page update date :
Page creation date :

summary

I use a lot of polygons to create a box. In doing so, an index buffer is used to reduce the amount of data in the vertex data.

インデックスバッファを使用したボックスの表示

Operating environment

Prerequisites

Supported XNA Versions
  • 4.0
Supported Platforms
  • Windows (XP SP2 or later, Vista, 7)
  • Xbox 360
  • Windows Phone 7
Windows Required Vertex Shader Version 2.0
Windows Required Pixel Shader Version 2.0

Operating environment

platform
  • Windows 7
  • Xbox 360
  • Windows Phone 7 Emulator

substance

About the box

The box consists of six faces, one of which consists of two triangular polygons. This means that the total number of triangular polygons is "2×6 = 12". Furthermore, since the triangular polygon has three vertices, the total of vertices is "12×3 = 36". Therefore, when creating only with "VertexBuffer", it is possible to display it as a box if you decide the position information so that 36 pieces of data are in the shape of a box and write it. (24 are required for TriangleStrip)

But imagine a box. The corners of the box are 8 pieces. Eight should be enough for location information. As the number of vertex data increases, it puts pressure on memory. To reduce this somehow, we use "IndexBuffer".

You only need 8 position information, but you always need 36 vertices for a polygon. Therefore, the purpose of using "IndexBuffer" is to share 8 vertex data.

四角形ポリゴン

field

/// <summary>
/// インデックスバッファ
/// </summary>
private IndexBuffer indexBuffer = null;

/// <summary>
/// インデックスバッファの各頂点番号配列
/// </summary>
private static readonly Int16[] vertexIndices = new Int16[] {
    2, 0, 1, // 1枚目のポリゴン
    1, 3, 2, // 2枚目のポリゴン
    4, 0, 2, // 3枚目のポリゴン
    2, 6, 4, // 4枚目のポリゴン
    5, 1, 0, // 5枚目のポリゴン
    0, 4, 5, // 6枚目のポリゴン
    7, 3, 1, // 7枚目のポリゴン
    1, 5, 7, // 8枚目のポリゴン
    6, 2, 3, // 9枚目のポリゴン
    3, 7, 6, // 10枚目のポリゴン
    4, 6, 7, // 11枚目のポリゴン
    7, 5, 4  // 12枚目のポリゴン
};

The field is declared an "IndexBuffer", but a "vertex number array" is pre-created under it. This array reserves an array for 36 vertices, but the meaning of each number is how many vertex data of the eight vertex data each triangle polygon uses. If you look closely, you can see that the data inside is written with an index between "0 ~ 7". It's easy to see in the comments.

By the way, the type of the array is "Int16[]", but it can also be "short[]" (2 bytes). In some cases, an array is created with "int" (4 bytes), but this is used when the number of vertices exceeds "65535". If the number of vertices never exceeds this number, create an array of 2-byte data to reduce memory consumption.

creation

// 頂点の数
int vertexCount = 8;

// 頂点バッファ作成
this.vertexBuffer = new VertexBuffer(this.GraphicsDevice,
    typeof(VertexPositionColor), vertexCount, BufferUsage.None);

// 頂点データを作成する
VertexPositionColor[] vertives = new VertexPositionColor[vertexCount];

vertives[0] = new VertexPositionColor(new Vector3(-2.0f, 2.0f, -2.0f), Color.Yellow);
vertives[1] = new VertexPositionColor(new Vector3(2.0f, 2.0f, -2.0f), Color.Gray);
vertives[2] = new VertexPositionColor(new Vector3(-2.0f, 2.0f, 2.0f), Color.Purple);
vertives[3] = new VertexPositionColor(new Vector3(2.0f, 2.0f, 2.0f), Color.Red);
vertives[4] = new VertexPositionColor(new Vector3(-2.0f, -2.0f, -2.0f), Color.SkyBlue);
vertives[5] = new VertexPositionColor(new Vector3(2.0f, -2.0f, -2.0f), Color.Orange);
vertives[6] = new VertexPositionColor(new Vector3(-2.0f, -2.0f, 2.0f), Color.Green);
vertives[7] = new VertexPositionColor(new Vector3(2.0f, -2.0f, 2.0f), Color.Blue);

// 頂点データを頂点バッファに書き込む
this.vertexBuffer.SetData(vertives);

Creating vertex buffers. Originally, it is necessary to create 36 vertices, but by using an index buffer, you only need to create 8 vertices.

// インデックスバッファを作成
this.indexBuffer = new IndexBuffer(this.GraphicsDevice,
    IndexElementSize.SixteenBits, 3 * 12, BufferUsage.None);

// 頂点インデックスを書き込む
this.indexBuffer.SetData(vertexIndices);

Creating index buffers. The second argument specifies the number of bits of the vertex index to be written. Since one index is 2 bytes, specify "IndexElementSize.SixteenBits".

The third argument is the number of indexes. In this case, we will draw 12 polygons, so specify 36, which is the number of vertices × polygons of the triangular polygons. Of course, there is no problem if you specify the number of elements in the index array as it is, but this time the numbers are intentionally separated for clarity.

Since we have already created an array of vertex indices with fields, we will write them with the "IndexBuffer.SetData" method.

IndexBuffer constructor

Creates an instance of the IndexBuffer class that manages the index that references the vertex data.

graphicsDevice GraphicsDevice Specifies the GraphicsDevice to associate with the index buffer.
indexElementSize IndexElementSize The size of a single vertex index. Specify "SixteenBits" for 2 bytes, "ThirtyTwoBits" for 4 bytes, and specify BufferUsage.None.
indexCount int Specifies the number of indexes.
usage BufferUsage Index buffer usage. Specify BufferUsage.None unless otherwise.

IndexBuffer.SetData method

Copy the array of vertex indices to the index buffer.

T ValueType Vertex index array type
data T Vertex index array to copy

drawing

// インデックスバッファをセット
this.GraphicsDevice.Indices = this.indexBuffer;

If you want to use an index buffer, set the index buffer on the device before drawing the polygon.

// インデックスを使用してポリゴンを描画する
this.GraphicsDevice.DrawIndexedPrimitives(
    PrimitiveType.TriangleList,
    0,
    0,
    8,
    0,
    12
);

If you are using index and vertex buffers, use the "GraphicsDevice.DrawIndexedPrimitives" method to draw polygons.

The fourth argument is the number of vertices created. In the sample, "8" is specified because 8 vertex data is shared.

The sixth argument specifies the number of primitives. It is "12" because it draws 12 triangular polygons.

For other numeric parameters, 0 is fine.

GraphicsDevice.DrawIndexedPrimitives method

Draws a primitive based on the specified vertex index and vertex buffer.

primitiveType PrimitiveType Specifies the primitive to draw.
baseVertex int The offset to add to each vertex index in the index buffer. For example, when the first vertex index points to vertex data 2, if "1" is specified in this argument, the first vertex index will point to vertex data 3.
minVertexIndex int The minimum vertex index of the vertex used in the call. For example, a minVertexIndex of 1 increases the index of the vertex data by 1 (it does not increase the number of buffers, so the last element of the vertex data cannot be specified). If the vertex index points to the second vertex data, it will point to the first vertex data.
numVertices int The number of vertex data used.
startIndex int The starting offset of the vertex index. For example, if you specify TriangleList as the primitiveType, specify "3, 6, 9,..." to skip the polygons that start drawing. If you specify a value other than the number that is divided by 3, the model will collapse. (Because all indexes are off)
primitiveCount int The number of primitives to draw. The maximum value that can be specified is "Number of vertex indices÷ Number of vertices of primitives - startIndex"

All Codes

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;
#if WINDOWS_PHONE
using Microsoft.Xna.Framework.Input.Touch;
#endif

namespace IndexBufferBox
{
    /// <summary>
    /// ゲームメインクラス
    /// </summary>
    public class GameMain : Microsoft.Xna.Framework.Game
    {
        /// <summary>
        /// グラフィックデバイス管理クラス
        /// </summary>
        private GraphicsDeviceManager graphics = null;

        /// <summary>
        /// スプライトのバッチ化クラス
        /// </summary>
        private SpriteBatch spriteBatch = null;

        /// <summary>
        /// 基本エフェクト
        /// </summary>
        private BasicEffect basicEffect = null;

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

        /// <summary>
        /// インデックスバッファ
        /// </summary>
        private IndexBuffer indexBuffer = null;

        /// <summary>
        /// インデックスバッファの各頂点番号配列
        /// </summary>
        private static readonly Int16[] vertexIndices = new Int16[] {
            2, 0, 1, // 1枚目のポリゴン
            1, 3, 2, // 2枚目のポリゴン
            4, 0, 2, // 3枚目のポリゴン
            2, 6, 4, // 4枚目のポリゴン
            5, 1, 0, // 5枚目のポリゴン
            0, 4, 5, // 6枚目のポリゴン
            7, 3, 1, // 7枚目のポリゴン
            1, 5, 7, // 8枚目のポリゴン
            6, 2, 3, // 9枚目のポリゴン
            3, 7, 6, // 10枚目のポリゴン
            4, 6, 7, // 11枚目のポリゴン
            7, 5, 4  // 12枚目のポリゴン
        };


        /// <summary>
        /// GameMain コンストラクタ
        /// </summary>
        public GameMain()
        {
            // グラフィックデバイス管理クラスの作成
            this.graphics = new GraphicsDeviceManager(this);

            // ゲームコンテンツのルートディレクトリを設定
            this.Content.RootDirectory = "Content";

#if WINDOWS_PHONE
            // Windows Phone のデフォルトのフレームレートは 30 FPS
            this.TargetElapsedTime = TimeSpan.FromTicks(333333);

            // バックバッファサイズの設定
            this.graphics.PreferredBackBufferWidth = 480;
            this.graphics.PreferredBackBufferHeight = 800;

            // フルスクリーン表示
            this.graphics.IsFullScreen = true;
#endif
        }

        /// <summary>
        /// ゲームが始まる前の初期化処理を行うメソッド
        /// グラフィック以外のデータの読み込み、コンポーネントの初期化を行う
        /// </summary>
        protected override void Initialize()
        {
            // TODO: ここに初期化ロジックを書いてください

            // コンポーネントの初期化などを行います
            base.Initialize();
        }

        /// <summary>
        /// ゲームが始まるときに一回だけ呼ばれ
        /// すべてのゲームコンテンツを読み込みます
        /// </summary>
        protected override void LoadContent()
        {
            // テクスチャーを描画するためのスプライトバッチクラスを作成します
            this.spriteBatch = new SpriteBatch(this.GraphicsDevice);

            // エフェクトを作成
            this.basicEffect = new BasicEffect(this.GraphicsDevice);

            // エフェクトで頂点カラーを有効にする
            this.basicEffect.VertexColorEnabled = true;

            // ビューマトリックスをあらかじめ設定 ((10, 10, 10) から原点を見る)
            this.basicEffect.View = Matrix.CreateLookAt(
                    new Vector3(10.0f, 10.0f, 10.0f),
                    Vector3.Zero,
                    Vector3.Up
                );

            // プロジェクションマトリックスをあらかじめ設定
            this.basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(
                    MathHelper.ToRadians(45.0f),
                    (float)this.GraphicsDevice.Viewport.Width /
                        (float)this.GraphicsDevice.Viewport.Height,
                    1.0f,
                    100.0f
                );

            // 頂点の数
            int vertexCount = 8;

            // 頂点バッファ作成
            this.vertexBuffer = new VertexBuffer(this.GraphicsDevice,
                typeof(VertexPositionColor), vertexCount, BufferUsage.None);

            // 頂点データを作成する
            VertexPositionColor[] vertives = new VertexPositionColor[vertexCount];

            vertives[0] = new VertexPositionColor(new Vector3(-2.0f, 2.0f, -2.0f), Color.Yellow);
            vertives[1] = new VertexPositionColor(new Vector3(2.0f, 2.0f, -2.0f), Color.Gray);
            vertives[2] = new VertexPositionColor(new Vector3(-2.0f, 2.0f, 2.0f), Color.Purple);
            vertives[3] = new VertexPositionColor(new Vector3(2.0f, 2.0f, 2.0f), Color.Red);
            vertives[4] = new VertexPositionColor(new Vector3(-2.0f, -2.0f, -2.0f), Color.SkyBlue);
            vertives[5] = new VertexPositionColor(new Vector3(2.0f, -2.0f, -2.0f), Color.Orange);
            vertives[6] = new VertexPositionColor(new Vector3(-2.0f, -2.0f, 2.0f), Color.Green);
            vertives[7] = new VertexPositionColor(new Vector3(2.0f, -2.0f, 2.0f), Color.Blue);

            // 頂点データを頂点バッファに書き込む
            this.vertexBuffer.SetData(vertives);

            // インデックスバッファを作成
            this.indexBuffer = new IndexBuffer(this.GraphicsDevice,
                IndexElementSize.SixteenBits, 3 * 12, BufferUsage.None);

            // 頂点インデックスを書き込む
            this.indexBuffer.SetData(vertexIndices);
        }

        /// <summary>
        /// ゲームが終了するときに一回だけ呼ばれ
        /// すべてのゲームコンテンツをアンロードします
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: ContentManager で管理されていないコンテンツを
            //       ここでアンロードしてください
        }

        /// <summary>
        /// 描画以外のデータ更新等の処理を行うメソッド
        /// 主に入力処理、衝突判定などの物理計算、オーディオの再生など
        /// </summary>
        /// <param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
        protected override void Update(GameTime gameTime)
        {
            // Xbox 360 コントローラ、Windows Phone の BACK ボタンを押したときに
            // ゲームを終了させます
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }

            // TODO: ここに更新処理を記述してください

            // 登録された GameComponent を更新する
            base.Update(gameTime);
        }

        /// <summary>
        /// 描画処理を行うメソッド
        /// </summary>
        /// <param name="gameTime">このメソッドが呼ばれたときのゲーム時間</param>
        protected override void Draw(GameTime gameTime)
        {
            // 画面を指定した色でクリアします
            this.GraphicsDevice.Clear(Color.CornflowerBlue);

            // 描画に使用する頂点バッファをセット
            this.GraphicsDevice.SetVertexBuffer(this.vertexBuffer);

            // インデックスバッファをセット
            this.GraphicsDevice.Indices = this.indexBuffer;

            // パスの数だけ繰り替えし描画 (といっても BasicEffect は通常1回)
            foreach (EffectPass pass in this.basicEffect.CurrentTechnique.Passes)
            {
                // パスの開始
                pass.Apply();
                
                // インデックスを使用してポリゴンを描画する
                this.GraphicsDevice.DrawIndexedPrimitives(
                    PrimitiveType.TriangleList,
                    0,
                    0,
                    8,
                    0,
                    12
                );
            }

            // 登録された DrawableGameComponent を描画する
            base.Draw(gameTime);
        }
    }
}