16 Nisan 2008 Çarşamba

Managed Directx Örnek Uygulama - 1

Bu uygulamada ekrana temel şekillerin nasıl çizdirildiğini inceleyeceğiz. İlk uygulama olduğu için texture yerine şimdilik vertexleri boyamayı tercih ediyoruz. Yani kullanacağımız vertex tipi “TransformedColored” olacak.

using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using Direct3D = Microsoft.DirectX.Direct3D;

namespace Oyun1
{
 public class oyun : Form
 {
  Device device=null;
  VertexBuffer vertbuffer=null;
  public oyun()
  {
   this.ClientSize = new Size(450,450);
   this.Text = "Oyun Deneme!";
  }
  public bool grafik_hazirla()
  {
   try
   {
    PresentParameters d3dpp = new PresentParameters();
    d3dpp.Windowed = true;
    d3dpp.SwapEffect = SwapEffect.Discard;
    device = new Device(0,DeviceType.Hardware,this,CreateFlags.SoftwareVertexProcessing,d3dpp);
    vertbuffer = new VertexBuffer(typeof(CustomVertex.TransformedColored),4,device,Usage.WriteOnly,CustomVertex.TransformedColored.Format,Pool.Default);
    GraphicsStream stm = vertbuffer.Lock(0,0,0);
    CustomVertex.TransformedColored[] verts = new Microsoft.DirectX.Direct3D.CustomVertex.TransformedColored[4];
    verts[0].X = 100; verts[0].Y = 100;verts[0].Z = 0;verts[0].Rhw = 1;verts[0].Color = System.Drawing.Color.Blue.ToArgb();
    verts[1].X = 300; verts[1].Y = 100;verts[1].Z = 0;verts[1].Rhw = 1;verts[1].Color = System.Drawing.Color.Black.ToArgb();
    verts[2].X = 100; verts[2].Y = 300;verts[2].Z = 0;verts[2].Rhw = 1;verts[2].Color = System.Drawing.Color.Red.ToArgb();
    verts[3].X = 300; verts[3].Y = 300;verts[3].Z = 0;verts[3].Rhw = 1;verts[3].Color = System.Drawing.Color.Brown.ToArgb();
    stm.Write(verts);
    vertbuffer.Unlock();
    return true;
   }
   catch(DirectXException hata)
   {
    MessageBox.Show(hata.ToString());
    return false;
   }
  }
  private void render()
  {
   if(device==null)
    return;
   device.Clear(ClearFlags.Target,System.Drawing.Color.BlueViolet,1.0f,0);
   device.BeginScene();
   device.SetStreamSource(0,vertbuffer,0);
   device.VertexFormat = CustomVertex.TransformedColored.Format;
   device.DrawPrimitives(PrimitiveType.TriangleStrip,0,2);
   device.EndScene();
   device.Present();
  }
  protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
  {
   this.render();
  }
  protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
  {
   if ((int)(byte)e.KeyChar == (int)System.Windows.Forms.Keys.Escape)
    this.Close();
  }
  static void Main()
  {
   using(oyun f1=new oyun())
   {
    if(!f1.grafik_hazirla())
    {
     MessageBox.Show("Grafik Hazırlanamıyor!");
     return;
    }
    f1.Show();
    while(f1.Created)
    {
     f1.render();
     Application.DoEvents();
    }
   }
  }
 }
}

Hiç yorum yok: