用c#進行directX開發的一個簡單例子

來源:互聯網
上載者:User

這幾天一直在研究c#下進行directX3D開發,頗有些成績。

先貼出一個小例子和大家分享,我做的是一個旋轉的4稜錐。

如果有人對這方面感興趣不知道如何學習的話,我建議看兩個文檔<Managed DirectX 9圖形和遊戲編程簡略中文文檔>,<Managed DirectX 9 SDK 中文文檔>。

另外最好下載個DirectX SDK (August 2007).rar。裡面有些範例還是非常好的。自己到網上找,很多的。

一,首先保證你機子上裝了directx,沒裝的趕緊下載去裝。

二,建立一個c#的windows應用程式,添加兩個引用Microsoft.DirectX和Microsoft.DirectX.Direct3D;

三,form1.cs中代碼為:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX;          //開發directx需要包含的兩個命名空間
using Microsoft.DirectX.Direct3D;

 

namespace Rectangle
{
    public partial class form1 : Form
    {
       
        /// <summary>
        /// 裝置對象,情境中所有繪圖物件的父物件
        /// </summary>
        private Device device = null; 

        /// <summary>
        /// 座標系四稜錐頂點緩衝
        /// </summary>
        VertexBuffer vertexBuffer = null; 

        /// <summary>
        /// 此參數設定為必須,它定義了要建立的Direct3D裝置的表示參數,如背景緩衝區的高度、寬度和像素格式、如何從背景緩衝區複製到前台緩衝、以及螢幕顯示的方式等等
        /// </summary>
        PresentParameters presentParameters = new PresentParameters();
       
        /// <summary>
        /// 暫停標誌
        /// </summary>
        bool pause = false;

        /// <summary>
        /// 隨機數,用來產生隨機顏色用的
        /// </summary>
        Random rn = new Random();

        /// <summary>
        /// 建構函式,設定表單大小
        /// </summary>
        public form1()
        {
            this.ClientSize = new System.Drawing.Size(300, 300);
        }

        /// <summary>
        /// 初始化繪圖環境
        /// </summary>
        /// <returns></returns>
        public bool InitializeGraphics()
        {
            try
            {
                //設定螢幕顯示模式為視窗模式
                presentParameters.Windowed = true;
                //設定如何從背景緩衝區複製到前端緩衝區(SwapEffect.Discard表示緩衝區在顯示後立即被捨棄,這樣可以節省開銷)
                presentParameters.SwapEffect = SwapEffect.Discard;
                //建立一個裝置
                device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParameters);
                //為裝置釋放訂閱事件處理
                device.DeviceReset += new System.EventHandler(this.OnResetDevice);
               
                this.OnCreateDevice(device, null);
                this.OnResetDevice(device, null);
                pause = false;
                return true;
            }

            catch (DirectXException)
            {
                return false;
            }
        }

        /// <summary>
        /// 裝置建立時建立頂點緩衝
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnCreateDevice(object sender, EventArgs e)
        {
            Device dev = (Device)sender;

            //建立頂點緩衝,有個頂點
            vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 18, dev, 0, CustomVertex.PositionColored.Format, Pool.Default);
            //為建立頂點緩衝訂閱事件處理
            vertexBuffer.Created += new System.EventHandler(this.OnCreateVertexBuffer);

            this.OnCreateVertexBuffer(vertexBuffer, null);
        }

        /// <summary>
        /// 裝置撤銷的事件處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnResetDevice(object sender, EventArgs e)
        {
            Device dev = (Device)sender;
            //關閉剔除模式,使我們能看見此四稜錐的前面和後面
            dev.RenderState.CullMode = Cull.None;
            // 關閉情境裡的燈光,顯示頂點自己的顏色
            dev.RenderState.Lighting = false;
        }

        /// <summary>
        /// 建立頂點緩衝的事件處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnCreateVertexBuffer(object sender, EventArgs e)
        {
           
            VertexBuffer vb = (VertexBuffer)sender;
            CustomVertex.PositionColored[] verts = (CustomVertex.PositionColored[])vb.Lock(0, 0);
           
            //四稜錐原始的個點
            Vector3 vertex1 = new Vector3(25, 0, 0);
            Vector3 vertex2 = new Vector3(0, 0, -25);
            Vector3 vertex3 = new Vector3(-25, 0, 0);
            Vector3 vertex4 = new Vector3(0, 0, 25);
            Vector3 vertex5 = new Vector3(0, 25, 0);

            //四稜錐中包含個三角形,所以要構造個點來繪製
            verts[0].Position = vertex1;
            verts[1].Position = vertex2;
            verts[2].Position = vertex5;
            verts[3].Position = vertex2;
            verts[4].Position = vertex3;
            verts[5].Position = vertex5;
            verts[6].Position = vertex3;
            verts[7].Position = vertex4;
            verts[8].Position = vertex5;
            verts[9].Position = vertex4;
            verts[10].Position = vertex1;
            verts[11].Position = vertex5;
            verts[12].Position = vertex2;
            verts[13].Position = vertex1;
            verts[14].Position = vertex3;
            verts[15].Position = vertex3;
            verts[16].Position = vertex1;
            verts[17].Position = vertex4;

            //給每個點賦予隨機顏色
            for (int i = 0; i < 18; i++)
            {
                verts[i].Color = Color.FromArgb(SetColor(), SetColor(), SetColor()).ToArgb();

            }
                vb.Unlock();

 

        }

        /// <summary>
        /// 返回到之間的一個隨機數,用來產生隨機顏色
        /// </summary>
        /// <returns></returns>
        public int SetColor()
        {
            int number = rn.Next(256);
            return number;
        }

        /// <summary>
        /// 設定攝像機的位置
        /// </summary>
        private void SetupCamera()
        {
            //設定世界矩陣,根據系統已耗用時間而變化
            device.Transform.World = Matrix.RotationAxis(new Vector3((float)Math.Cos(Environment.TickCount / 250.0f), 1, (float)Math.Sin(Environment.TickCount / 250.0f)), Environment.TickCount / 3000.0f);
            //設定攝像機的位置,它在z軸上-50處,看著原點,y軸為正方向
            device.Transform.View = Matrix.LookAtLH(new Vector3(0.0f, 0.0f, -50f), new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 1.0f, 0.0f));

            //設定攝像機的視界,角度為度,看的最近為,看的最遠處為.不再這個視界中的影像都不會被顯示
            device.Transform.Projection = Matrix.PerspectiveFovLH(((float)(float)Math.PI / 2 ), 1.0f, 10.0f, 200.0f);
        }

        /// <summary>
        /// 繪製圖形
        /// </summary>
        public void Render()
        {
            if (device == null)
                return;

            if (pause)
                return;

            //背景設為綠色
            device.Clear(ClearFlags.Target, System.Drawing.Color.Blue, 1.0f, 0);
            //開始情境
            device.BeginScene();
            // 設定世界,視野和投影矩陣
            SetupCamera();

            // 給裝置指定頂點緩衝
            device.SetStreamSource(0, vertexBuffer, 0);

            //設定裝置的頂點格式
            device.VertexFormat = CustomVertex.PositionColored.Format;

            //繪製圖形,使用的方法為三角形列表,個數為個
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, 6);
                       
            //結束情境
            device.EndScene();

            //更新情境
            device.Present();
        }

        //重載OnPaint函數
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            //繪製圖形
            this.Render();
        }
    }
}

四,program.cs中的代碼為:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

 

namespace Rectangle
{
    static class Program
    {
        /// <summary>
        /// 應用程式的主進入點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            using (form1 frm = new form1())
            {

                if (!frm.InitializeGraphics()) // 初始化 Direct3D
                {
                    MessageBox.Show("不能初始化 Direct3D.程式將退出.");
                    return;
                }
                frm.Show();

                // While the form is still valid, render and process messages
                while (frm.Created)
                {
                    frm.Render();
                    Application.DoEvents(); //處理當前在訊息佇列中的所有 Windows 訊息
                }
            }
        }
    }
}
 

運行後你會看到一個不斷旋轉的四稜錐。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.