C#でツールを作る その9.1 -Meshクラス-

前回のエントリでは、VertexBufferとIndexBufferを自分で作って描画していましたが、
複数のモデルを描画する際、モデル毎にVertexBuffer、IndexBufferを作るのは大変です。
モデルクラス的なものを自作してもいいですがそれも面倒です。

ということで、Direct3DのMeshクラスを使ってみます。

参考

サンプル

Cube生成関数

  • マテリアル単位でAttributeRangeを設定する必要がある。
private Mesh CreateCube()
{
    Mesh mesh = new Mesh( 12, 8, MeshFlags.SystemMemory, CustomVertex.PositionColored.Format, device );

    CustomVertex.PositionColored[] v = new CustomVertex.PositionColored[ 8 ];
    v[ 0 ] = new CustomVertex.PositionColored( -0.5f,  0.5f, -0.5f, Color.Red.ToArgb() );
    v[ 1 ] = new CustomVertex.PositionColored(  0.5f,  0.5f, -0.5f, Color.Magenta.ToArgb() );
    v[ 2 ] = new CustomVertex.PositionColored(  0.5f, -0.5f, -0.5f, Color.Blue.ToArgb() );
    v[ 3 ] = new CustomVertex.PositionColored( -0.5f, -0.5f, -0.5f, Color.Black.ToArgb() );
    v[ 4 ] = new CustomVertex.PositionColored( -0.5f,  0.5f,  0.5f, Color.Yellow.ToArgb() );
    v[ 5 ] = new CustomVertex.PositionColored(  0.5f,  0.5f,  0.5f, Color.White.ToArgb() );
    v[ 6 ] = new CustomVertex.PositionColored(  0.5f, -0.5f,  0.5f, Color.Cyan.ToArgb() );
    v[ 7 ] = new CustomVertex.PositionColored( -0.5f, -0.5f,  0.5f, Color.FromArgb( 0, 255, 0 ).ToArgb() );

    short[] i = new short[]{
        0, 1, 2,
        0, 2, 3,
        1, 5, 6,
        1, 6, 2,
        5, 4, 7,
        5, 7, 6,
        4, 0, 3,
        4, 3, 7,
        4, 5, 1,
        4, 1, 0,
        3, 2, 6,
        3, 6, 7
    };

    //マテリアル単位で頂点バッファ、インデックスバッファの使用領域を指定する。
    //今回はマテリアルを使用していないので、とりあえず全体を指定。
    AttributeRange attr = new AttributeRange();
    attr.AttributeId = 0;
    attr.FaceStart = 0;
    attr.FaceCount = 12;
    attr.VertexStart = 0;
    attr.VertexCount = 8;

    mesh.VertexBuffer.SetData( v, 0, LockFlags.None );
    mesh.IndexBuffer.SetData( i, 0, LockFlags.None );
    mesh.SetAttributeTable( new AttributeRange[]{ attr } );
    return mesh;
}

描画

  • マテリアル番号を指定する
    • 使ってないので0で良い
mesh.DrawSubset( 0 );  //マテリアル番号。とりあえず0