C# Draw Rectangle and Draw 2D Texture in DirectX

in directx •  7 years ago 

directx.png

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;
using Microsoft.DirectX.Direct3D;
using System.Threading;

namespace directx
{

public partial class Form1 : Form
{

    Thread ServerThread;
    Microsoft.DirectX.Direct3D.Device device;
    Microsoft.DirectX.Direct3D.Font TextDev;
    Point MouseXY = new Point(0, 0);
    Texture texture;
    Texture txBox;
    bool ThreadRun = false;
    delegate void Drawing();

    Matrix mxWorld = Matrix.Translation(100, 100, 0);

    public Form1()
    {
        InitializeComponent();
        InitDevice();
        LoadTexture();

        (ServerThread = new Thread(new ThreadStart(ServerThreadFnc))).Start(); 
    }

    /// <summary>
    /// 윈도우의 컨트롤을 사용하고 Drawing과 Logic을 분리하기 위해서는 Thread 사용이 필수적이다.
    /// </summary>
    void ServerThreadFnc()
    {
        ThreadRun = true;
        while(ThreadRun)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    Drawing d = new Drawing(Render);
                    this.Invoke(d, new object[] { });
                }
                else
                {
                    
                    Render();
                }
            }catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Thread.Sleep(1);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    }

    void LoadTexture()
    {
        
        texture = TextureLoader.FromFile(device, Application.StartupPath+"\\mainframe.png");
        txBox = TextureLoader.FromFile(device, Application.StartupPath + "\\white.png");
    }

    private void InitDevice()
    {
        PresentParameters pp = new PresentParameters();
        pp.Windowed = true;
        pp.SwapEffect = SwapEffect.Discard;
        
        device = new Device(0, DeviceType.Hardware, pictureBox1, CreateFlags.HardwareVertexProcessing, pp);
        Console.WriteLine("("+device.Viewport.Width + ":" + device.Viewport.Height + ") (" + Width+":"+Height+")");

        System.Drawing.Font systemfont = new System.Drawing.Font("Arial", 12f, FontStyle.Regular);
        TextDev = new Microsoft.DirectX.Direct3D.Font(device, systemfont); 
    }

    /// <summary>
    /// 가로 형태의 라인을 만들고 싶다면 사용할수 있다.
    /// </summary>
    /// <param name="bx"></param>
    /// <param name="by"></param>
    /// <param name="bw"></param>
    /// <param name="color"></param>
    void DrawLine(int bx,int by,int bw,Color color)
    {
        Rectangle[] rects = new Rectangle[1];
        rects[0] = new Rectangle(bx, by, bw, 1);
        device.Clear(ClearFlags.Target, color, 0, 1, rects);
    }
    
    /// <summary>
    /// 삼각형도 한번 찍어보았다.
    /// </summary>
    void DrawTriangle()
    {
        CustomVertex.TransformedColored[] vertexes = new CustomVertex.TransformedColored[3];
        vertexes[0].Position = new Vector4(50, 50, 0, 1.0f);
        vertexes[0].Color = System.Drawing.Color.FromArgb(255, 255, 255).ToArgb();
        vertexes[1].Position = new Vector4(250, 50, 0, 1.0f);
        vertexes[1].Color = System.Drawing.Color.FromArgb(255, 255, 255).ToArgb();
        vertexes[2].Position = new Vector4(50, 250, 0, 1.0f);
        vertexes[2].Color = System.Drawing.Color.FromArgb(255, 255, 255).ToArgb();

        device.VertexFormat = CustomVertex.TransformedColored.Format;
        device.DrawUserPrimitives(PrimitiveType.TriangleList, 1, vertexes);
    }

    /// <summary>
    /// 텍스쳐를 원하는 크기와 위치에 찍는 함수를 만들었다.
    /// </summary>
    /// <param name="s"></param>
    /// <param name="tx"></param>
    /// <param name="SrcRect"></param>
    /// <param name="DesRect"></param>
    /// <param name="color"></param>
    /// <param name="RotateAngle"></param>
    void DrawTexture(Sprite s, Texture tx, Rectangle SrcRect, Rectangle DesRect , Color color , float RotateAngle = 0 )
    {
        Vector3 Scale = new Vector3((float)DesRect.Width / (float)SrcRect.Width, (float)DesRect.Height / (float)SrcRect.Height, 1);
        s.Transform = Matrix.Scaling(Scale) * Matrix.Translation(SrcRect.Width * Scale.X / (-2.0f), SrcRect.Height * Scale.Y / (-2.0f), 0)
                      * Matrix.RotationZ(RotateAngle) * Matrix.Translation(SrcRect.Width * Scale.X / (2.0f), SrcRect.Height * Scale.Y / (2.0f), 0);
        s.Transform = s.Transform * Matrix.Translation(DesRect.X, DesRect.Y, 0) ;
        s.Draw(tx, SrcRect, new Vector3(0f, 0f, 0.0f), new Vector3(0, 0, 0.0f), color);
        s.Transform = Matrix.Identity;
    }

    /// <summary>
    /// 박스를 찍어준다.
    /// </summary>
    /// <param name="s"></param>
    /// <param name="rt"></param>
    /// <param name="color"></param>
    /// <param name="LineWidth"></param>
    void DrawRectangle(Sprite s, Rectangle rt, Color color , int LineWidth = 2 )
    {
        Rectangle[] rects = new Rectangle[] {
            new Rectangle(rt.X, rt.Y, rt.Width, LineWidth),
            new Rectangle(rt.X, rt.Y + rt.Height - LineWidth, rt.Width, LineWidth),
            new Rectangle(rt.X, rt.Y, LineWidth, rt.Height),
            new Rectangle(rt.X + rt.Width - LineWidth, rt.Y, LineWidth, rt.Height)};

        foreach (Rectangle rect in rects)
            DrawTexture(s, txBox, new Rectangle(0, 0, 9, 9), rect, color);
    }

    void DrawBase(Sprite s)
    {
        for (int m = 0; m < (device.Viewport.Height+50 )/ 50; m++)
            for (int n = 0; n < (device.Viewport.Width+50) / 50; n++)
                if (n % 2 - m % 2 == 0)
                {
                    DrawTexture(s, txBox, new Rectangle(0, 0, 9, 9), new Rectangle(n * 50, m * 50, 50, 50), Color.Gray);
                }
    }

    float Angle = 0;
    void Render()
    {                        
        device.Clear(ClearFlags.Target, Color.Black, 0, 1);
        device.BeginScene();
        device.SetSamplerState(0, SamplerStageStates.MipFilter, false);
        device.SetSamplerState(0, SamplerStageStates.MagFilter, false);
        
        DrawTriangle();

        using(Sprite s = new Sprite(device))
        {
            s.Begin(SpriteFlags.AlphaBlend);
            DrawBase(s);
            DrawRectangle(s, new Rectangle(100, 100, 100, 100),Color.Red);
            DrawTexture(s, texture, new Rectangle(0, 0, 128, 128), new Rectangle(MouseXY.X, MouseXY.Y, 128, 128), Color.White, Angle);
            TextDev.DrawText(s, string.Format("Score : {0}", 11), new Point(0, 0), Color.White);
            s.End();                
        }            
        
        device.EndScene();            
        device.Present();

        Angle += 0.01f;       
    }

    
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        ThreadRun = false;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        MouseXY = e.Location;
        this.Text = MouseXY.ToString();
    }
     
}

}

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Congratulations @devagit! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Do not miss the last post from @steemitboard:

SteemitBoard Ranking update - A better rich list comparator
Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Congratulations @devagit! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

Click here to view your Board

Support SteemitBoard's project! Vote for its witness and get one more award!