Microsoft MVP성태의 닷넷 이야기
Graphics: 27. .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리 [링크 복사], [링크+제목 복사]
조회: 19391
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 8개 있습니다.)
Graphics: 27. .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리
; https://www.sysnet.pe.kr/2/0/11770

Graphics: 28. .NET으로 구현하는 OpenGL (2) - VAO, VBO
; https://www.sysnet.pe.kr/2/0/11772

Graphics: 29. .NET으로 구현하는 OpenGL (3) - Index Buffer
; https://www.sysnet.pe.kr/2/0/11773

Graphics: 30. .NET으로 구현하는 OpenGL (4), (5) - Shader
; https://www.sysnet.pe.kr/2/0/11774

Graphics: 31. .NET으로 구현하는 OpenGL (6) - Texturing
; https://www.sysnet.pe.kr/2/0/11775

Graphics: 32. .NET으로 구현하는 OpenGL (7), (8) - Matrices and Uniform Variables, Model, View & Projection Matrices
; https://www.sysnet.pe.kr/2/0/11784

Graphics: 33. .NET으로 구현하는 OpenGL (9), (10) - OBJ File Format, Loading 3D Models
; https://www.sysnet.pe.kr/2/0/11787

Graphics: 34. .NET으로 구현하는 OpenGL (11) - Per-Pixel Lighting
; https://www.sysnet.pe.kr/2/0/11792




.NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리

제가 ^^ 게임 프로그래머는 아니지만, 좋은 OpenGL 강좌가 있길래 따라 해 봤습니다.

TheThinMatrix/OpenGL-Tutorial-1
; https://github.com/TheThinMatrix/OpenGL-Tutorial-1

OpenGL 3D Game Tutorial 1: The Display
; https://www.youtube.com/watch?v=VS8wlS9hF8E

위의 강좌는 Java로 하고 있지만 1편의 개발 환경 구성을 제외하고는 대부분 닷넷에서도 그대로 따라 할 수 있습니다. (아니, 그럴 것 같습니다. ^^) 닷넷으로 하는 경우, 저 강좌의 1편은 자바 특화 환경이라 굳이 볼 필요가 없습니다. 닷넷은, 닷넷에 맞게 구성해야 하는데 우선 C# 프로젝트에서 NuGet을 이용해 다음의 패키지를 설치합니다.

OpenGL.Net
; https://github.com/luca-piccioni/OpenGL.Net

이 글에서는 Windows Forms 응용 프로그램으로 호스팅할 것이므로, 다음의 3개 정도만 추가하면 됩니다.

Install-Package OpenGL.Net
Install-Package OpenGL.Net.Math
Install-Package OpenGL.Net.WinForms

그런 다음, MainForm에 "Toolbox"에 있는 OpenGL.Net.WinForms의 "GlControl"을 얹어 놓습니다.

opengl_tutorial_1_0.png

해당 GlControl의 속성 창을 이용해 다음의 4가지 이벤트를 구독하고,

  • ContextCreated
  • ContextDestroying
  • ContextUpdate
  • Render

"Animation" 속성 값을 "true"로 변경합니다

다시 말해, InitializeComponent (또는 그냥 MainForm의 생성자) 등의 메서드 안에 다음과 같은 코드가 추가되어 있으면 됩니다.

private void InitializeComponent()
{
    this.glControl = new OpenGL.GlControl();
    this.SuspendLayout();
    // 
    // glControl
    // 
    this.glControl.Animation = true;
    this.glControl.AnimationTimer = false;
    this.glControl.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
    this.glControl.ColorBits = ((uint)(24u));
    this.glControl.DepthBits = ((uint)(0u));
    this.glControl.Dock = System.Windows.Forms.DockStyle.Fill;
    this.glControl.Location = new System.Drawing.Point(0, 0);
    this.glControl.MultisampleBits = ((uint)(0u));
    this.glControl.Name = "glControl";
    this.glControl.Size = new System.Drawing.Size(581, 270);
    this.glControl.StencilBits = ((uint)(0u));
    this.glControl.TabIndex = 0;
    this.glControl.ContextCreated += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glControl_ContextCreated);
    this.glControl.ContextDestroying += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glControl_ContextDestroying);
    this.glControl.ContextUpdate += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glControl_ContextUpdate);
    this.glControl.Render += new System.EventHandler<OpenGL.GlControlEventArgs>(this.glControl_Render);
    // 
    // MainForm
    // 
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(581, 270);
    this.Controls.Add(this.glControl);
    this.Name = "MainForm";
    this.Text = "MainForm";
    this.ResumeLayout(false);
}

이하 나머지는, 일단은 기본 프로젝트 구성이 목적이니 그냥 기본에 속한 이벤트 핸들러 코드만 작성하겠습니다.

Gl.DebugProc _debugProc;

private void glControl_ContextCreated(object sender, OpenGL.GlControlEventArgs e)
{
    GlControl glControl = (GlControl)sender;
    _debugProc = GLDebugMessageCallbackProc;

    if (Gl.CurrentExtensions != null && Gl.CurrentExtensions.DebugOutput_ARB)
    {
        Gl.DebugMessageCallback(_debugProc, null);
        Gl.DebugMessageControl(Gl.DebugSource.DontCare, Gl.DebugType.DontCare, Gl.DebugSeverity.DontCare, 0, null, true);
    }

    if (Gl.CurrentVersion != null && Gl.CurrentVersion.Api == KhronosVersion.ApiGl && glControl.MultisampleBits > 0)
    {
        Gl.Enable(EnableCap.Multisample);
    }
}

private void GLDebugMessageCallbackProc(Gl.DebugSource source, Gl.DebugType type, uint id, Gl.DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
{
    string strMessage;

    unsafe
    {
        strMessage = Encoding.ASCII.GetString((byte*)message.ToPointer(), length);
    }

    Debug.WriteLine($"{source}, {type}, {severity}: {strMessage}");
}

private void glControl_ContextUpdate(object sender, GlControlEventArgs e)
{
}

private void glControl_ContextDestroying(object sender, GlControlEventArgs e)
{
}

private void glControl_Render(object sender, OpenGL.GlControlEventArgs e)
{
    Control senderControl = (Control)sender;
    Gl.Viewport(0, 0, senderControl.ClientSize.Width, senderControl.ClientSize.Height);
}

위의 변경 사항들은 원래의 OpenGL.NET 예제에 있는 것을 보고 베낀 것입니다. ^^ 좀 더 자세한 예제가 궁금하다면 다음을 참고하시고.

OpenGL.Net/Samples/HelloTriangle/
; https://github.com/luca-piccioni/OpenGL.Net/tree/master/Samples/HelloTriangle




위의 구조에 "OpenGL 3D Game Tutorial 1: The Display" 강좌의 DisplayManager 타입을,

// DisplayManager.cs

using OpenGL;
using System;

namespace GameApp
{
    public class DisplayManager
    {
        public void createDisplay()
        {
        }

        public void updateDisplay()
        {
        }

        public void closeDisplay()
        {
        }
    }
}

굳이 끼워 맞추자면 각각 ContextCreated, ContextUpdate, Render 이벤트 핸들러에서 다음과 같이 호출하는 식으로 작성할 수 있습니다.

using Khronos;
using OpenGL;
using System;
using System.Diagnostics;
using System.Text;

namespace GameApp
{
    public class DisplayManager
    {
        GlControl _glControl;
        Gl.DebugProc _debugProc;

        public void createDisplay(GlControl glControl)
        {
            _debugProc = GLDebugMessageCallbackProc;
            _glControl = glControl;

            if (Gl.CurrentExtensions != null && Gl.CurrentExtensions.DebugOutput_ARB)
            {
                Gl.DebugMessageCallback(_debugProc, null);
                Gl.DebugMessageControl(Gl.DebugSource.DontCare, Gl.DebugType.DontCare, Gl.DebugSeverity.DontCare, 0, null, true);
            }

            if (Gl.CurrentVersion != null && Gl.CurrentVersion.Api == KhronosVersion.ApiGl && glControl.MultisampleBits > 0)
            {
                Gl.Enable(EnableCap.Multisample);
            }
        }

        private void GLDebugMessageCallbackProc(Gl.DebugSource source, Gl.DebugType type, uint id, Gl.DebugSeverity severity, int length, IntPtr message, IntPtr userParam)
        {
            string strMessage;

            unsafe
            {
                strMessage = Encoding.ASCII.GetString((byte*)message.ToPointer(), length);
            }

            Debug.WriteLine($"{source}, {type}, {severity}: {strMessage}");
        }

        public unsafe void updateDisplay()
        {
        }

        public void closeDisplay()
        {
        }
    }
}

GlControl _glControl;

private void glControl_ContextCreated(object sender, OpenGL.GlControlEventArgs e)
{
    GlControl glControl = (GlControl)sender;
    _displayManager.createDisplay(glControl);
}

private void glControl_ContextDestroying(object sender, GlControlEventArgs e)
{
    _displayManager.closeDisplay();
}

private void glControl_Render(object sender, OpenGL.GlControlEventArgs e)
{
    // ...[생략]...

    _displayManager.updateDisplay();
}

그래도 이렇게만 하고 실행하면 너무 심심하니, Render 메서드에 다음과 같은 정도의 내용만 추가해 보겠습니다. (게임 개발자가 아니라서 ^^ 더 멋있는 예제를 추가할 수가 없군요.)

Random _random = new Random(Environment.TickCount);

private unsafe void glControl_Render(object sender, OpenGL.GlControlEventArgs e)
{
    Control senderControl = (Control)sender;
    Gl.Viewport(0, 0, senderControl.ClientSize.Width, senderControl.ClientSize.Height);

    int w = 200;
    int h = 200;
    uint* n = stackalloc uint[w * h * 3];

    {
        Gl.ClearColor(0.0f, 0.0f, 1.0f, 1.0f);
        Gl.Clear(ClearBufferMask.ColorBufferBit);

        for (int i = 0; i < (w * h * 3); i++)
        {
            *(n + i) = (uint)_random.Next(255) * 255u * 255u * 255u;
        }

        IntPtr ptr = new IntPtr(n);
        Gl.DrawPixels(w, h, PixelFormat.Bgr, PixelType.UnsignedInt, ptr);
    }

    _displayManager.updateDisplay();
}

이렇게 하고 실행하면 좌측 하단에 지글(?)거리는 화면을 볼 수 있습니다.

opengl_tutorial_1_1.png

(첨부 파일은 이 글의 예제 프로젝트를 포함합니다.)

그나저나... DirectX뿐만 아니라, OpenGL이 의외로 닷넷에서도 매끄럽게 잘 연동이 되어 놀랐습니다. ^^




참고로 MainForm 생성 시 1st-chance 예외로 꼭 System.InvalidOperationException이 발생합니다.

System.InvalidOperationException
  HResult=0x80131509
  Message=unable to load library at libbcm_host.so
  Source=OpenGL.Net
  StackTrace:
   at Khronos.GetProcAddressWindows.GetLibraryHandle(String libraryPath) in C:\OpenGL.Net\Khronos.Net\GetProcAddressOS.cs:line 304

Inner Exception 1:
Win32Exception: The specified module could not be found

무시하고 지나가면 되는데, System.InvalidOperationException 예외가 1st-chance 발생 시 멈추도록 설정되어 있다면 Visual Studio로 디버깅 시 무조건 한번 걸리게 되므로 "Debug" / "Exceptions..." 메뉴를 이용해 "thrown"으로 설정된 것을 해제해야 합니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 11/21/2020]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-03-26 09시06분
dotnet/Silk.NET - high-speed .NET multimedia, graphics, and compute; providing bindings to popular low-level APIs such as OpenGL, OpenCL, OpenAL, OpenXR, GLFW, SDL, Vulkan, Assimp, and DirectX.
; https://github.com/dotnet/Silk.NET
정성태
2022-07-22 09시14분
STRIDE - Open-source C# Game Engine
; https://www.stride3d.net/

On .NET Live - Taking .NET game development in Stride
; https://www.youtube.com/watch?v=J6g5y8m26zs&ab_channel=dotNET

Graph3D: A Windows.Forms Render Control in C#
; https://www.codeproject.com/Articles/5293980/Graph3D-A-Windows-Forms-Render-Control-in-Csharp
정성태
2023-06-27 08시43분
ComputeSharp 2.0 - DirextX 12 및 D2D1으로 GPU에서 C#을 쉽게 실행
; https://forum.dotnetdev.kr/t/computesharp-2-0-dirextx-12-d2d1-gpu-c/7498
정성태

... 16  17  18  19  20  21  22  23  24  25  [26]  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
12970정성태2/15/20227813.NET Framework: 1156. C# - ffmpeg(FFmpeg.AutoGen): Bitmap으로부터 h264 형식의 파일로 쓰기 [1]파일 다운로드1
12969정성태2/14/20226450개발 환경 구성: 638. Visual Studio의 Connection Manager 기능(Remote SSH 관리)을 위한 명령행 도구 - 두 번째 이야기파일 다운로드1
12968정성태2/14/20226608오류 유형: 794. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for '...'.
12967정성태2/14/20226992VC++: 153. Visual C++ - C99 표준의 Compund Literals 빌드 방법 [4]
12966정성태2/13/20226857.NET Framework: 1155. C# - ffmpeg(FFmpeg.AutoGen): Bitmap으로부터 yuv420p + rawvideo 형식의 파일로 쓰기파일 다운로드1
12965정성태2/13/20226722.NET Framework: 1154. "Hanja Hangul Project v1.01 (파이썬)"의 C# 버전
12964정성태2/11/20227034.NET Framework: 1153. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 avio_reading.c 예제 포팅파일 다운로드1
12963정성태2/11/20227792.NET Framework: 1152. C# - 화면 캡처한 이미지를 ffmpeg(FFmpeg.AutoGen)로 동영상 처리 (저해상도 현상 해결)파일 다운로드1
12962정성태2/9/20227635오류 유형: 793. 마이크로소프트 스토어 - 제품이 존재하지 않습니다. 재고가 없는 것일 수 있습니다.
12961정성태2/8/20227765.NET Framework: 1151. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 프레임의 크기 및 포맷 변경 예제(scaling_video.c) [7]파일 다운로드1
12960정성태2/8/20227188개발 환경 구성: 637. ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) - 세 번째 이야기
12959정성태2/7/20227891.NET Framework: 1150. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 디코딩 예제(decode_video.c) - 두 번째 이야기 [2]파일 다운로드1
12958정성태2/6/20227960.NET Framework: 1149. C# - ffmpeg(FFmpeg.AutoGen) - 비디오 프레임 디코딩 [2]파일 다운로드1
12957정성태2/6/20227580개발 환경 구성: 636. ffmpeg.exe를 이용해 planar 포맷의 데이터를 packed 형식으로 변환하는 방법? [2]
12956정성태2/4/20226786.NET Framework: 1148. C# - ffmpeg(FFmpeg.AutoGen) - decoding 과정 [2]파일 다운로드1
12955정성태2/4/20226180개발 환경 구성: 635. 비주얼 스튜디오에서 실행하던 ASP.NET Core (.NET Framework) 응용 프로그램을 명령행에서 실행하는 방법 (2)
12954정성태2/4/20226041VS.NET IDE: 173. 비주얼 스튜디오 - Output 창에 색상이 지정된 출력 결과가 "[39m[22m" 식의 문자로 나오는 문제
12953정성태2/2/20226298Linux: 48. Windows 11 + WSL 우분투 GUI 환경에서 한글 출력
12952정성태2/2/20226776.NET Framework: 1148. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 오디오 필터 예제(filter_audio.c)파일 다운로드1
12951정성태2/2/20226737.NET Framework: 1147. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 오디오 필터링 예제(filtering_audio.c)파일 다운로드1
12950정성태2/1/20226379.NET Framework: 1146. .NET 6에 추가되지 않은 Generic Math (예: INumber<T>)
12949정성태2/1/20226222.NET Framework: 1145. C# - ffmpeg(FFmpeg.AutoGen) - Codec 정보 열람 및 사용 준비파일 다운로드1
12948정성태1/30/20226348.NET Framework: 1144. C# - ffmpeg(FFmpeg.AutoGen) AVFormatContext를 이용해 ffprobe처럼 정보 출력파일 다운로드1
12947정성태1/30/20227497개발 환경 구성: 634. ffmpeg.exe - 기존 동영상 컨테이너에 다중 스트림을 추가하는 방법
12946정성태1/28/20226024오류 유형: 792. .NET Core - 로컬 개발 중에 docker 호스팅으로 바꾸는 경우 SQL 서버 접근 방법
12945정성태1/28/20226263오류 유형: 791. SQL 서버 로그인 시 localhost는 되고, 127.0.0.1로는 안 되는 문제
... 16  17  18  19  20  21  22  23  24  25  [26]  27  28  29  30  ...