성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>.NET으로 구현하는 OpenGL (2) - VAO, VBO</h1> <p> 아래의 글에 이어,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > .NET으로 구현하는 OpenGL (1) - OpenGL.Net 라이브러리 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/11770'>http://www.sysnet.pe.kr/2/0/11770</a> </pre> <br /> 오늘은 두 번째 강좌의 내용을 따라 하려는데,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > TheThinMatrix/OpenGL-Tutorial-2 ; <a target='tab' href='https://github.com/TheThinMatrix/OpenGL-Tutorial-2'>https://github.com/TheThinMatrix/OpenGL-Tutorial-2</a> OpenGL 3D Game Tutorial 2: VAOs and VBOs ; <a target='tab' href='https://www.youtube.com/watch?v=WMiggUPst-Q'>https://www.youtube.com/watch?v=WMiggUPst-Q</a> </pre> <br /> 알아야 할 개념이 VAO와 VBO입니다. 이에 대해서는 저보다 더 자세하게 알고 있는 분들이 쓴 글들이 있으니 참고하시고,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [OpenGL-2] OpenGL 시작하기 ; <a target='tab' href='http://zamezzz.tistory.com/30'>http://zamezzz.tistory.com/30</a> Modern OpenGL 강좌 - 삼각형 그리기( 렌더링, Vertex Array Object, Vertex Buffer Object) ; <a target='tab' href='http://webnautes.tistory.com/1153'>http://webnautes.tistory.com/1153</a> </pre> <br /> OpenGL(뿐만 아니라 GPU 관련한 프로그램들)은 보통 CPU가 사용하는 RAM의 데이터를 GPU에 복사하는 절차가 필요합니다. 따라서 VAO든, VBO든 모두 GPU에서 연산할 때 반드시 GPU 메모리에 올라와 있어야 합니다. 하지만 GPU 메모리를 직접 제어하는 것은 아니고 코드에서는 Handle을 이용해 간접적으로 다루게 됩니다. 결국 VAO와 VBO는 우선 GPU 메모리에 대한 Handle을 반환받는 것으로 시작합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // VAO의 경우, uint vaoID = Gl.GenVertexArray(); // VBO의 경우 uint vboID = Gl.GenBuffer(); </pre> <br /> 그다음, 앞으로의 버퍼 관련 함수의 호출에 대해 해당 핸들이 가리키는 GPU 메모리를 대상으로 하겠다고 Bind를 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // VAO의 경우 Gl.BindVertexArray(vaoID); // VBO의 경우 Gl.BindBuffer(BufferTarget.ArrayBuffer, vboID); </pre> <br /> Bind 이후의 연산들은 이제 해당 VAO, VBO 문맥 하에서 이뤄집니다. 가령 VBO의 데이터를 CPU로부터 GPU에 복사할 때 사용하는 BindBuffer를 다음과 같이 사용할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // 이전에 BindBuffer한 GPU 메모리에 복사 Gl.BufferData(BufferTarget.ArrayBuffer, (uint)(data.Length * sizeof(float)), data, BufferUsage.StaticDraw); </pre> <br /> 또한, 현재 바인드 중인 VBO를 VAO에 연관시키는 VertexAttribPointer 함수도 마찬가지로 현재 바인드된 VAO를 대상으로 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // 이전에 BindVertexArray한 VAO에 현재 Bind된 VBO를 attributeNumber 슬롯에 설정 Gl.VertexAttribPointer(attributeNumber, coordinateSize, VertexAttribType.Float, false, 0, IntPtr.Zero); </pre> <br /> 바인딩 후 더 이상 해당 GPU 메모리 조작이 필요 없다면 다음과 같이 바인딩 해제를 할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // VAO의 경우 Gl.BindVertexArray(0); // VBO의 경우 Gl.BindBuffer(BufferTarget.ArrayBuffer, 0); </pre> <br /> 바인딩 해제는 문맥에서 제거한 것일 뿐 객체의 메모리가 제거된 것은 아닙니다. 해당 GPU 자원을 완전히 해제하려면 다음과 같이 삭제를 해야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // VAO의 경우 Gl.DeleteVertexArrays(vaoID); // VBO의 경우 Gl.DeleteBuffers(vboID); </pre> <br /> <hr style='width: 50%' /><br /> <br /> 아직 잘은 모르겠지만, 그려질 객체 하나에 VAO 하나가 할당됩니다. 그리고 그 VAO의 (OpenGL 세대마다 다르지만 현재는 보통 16개) 슬롯에는 VBO를 각각 매핑할 수 있습니다. "<a target='tab' href='https://www.youtube.com/watch?v=WMiggUPst-Q'>OpenGL 3D Game Tutorial 2: VAOs and VBOs</a>" 강좌에서는 화면에 사각형을 그리기 위해 2개의 삼각형 vertex를 사용하는데, 따라서 VAO 하나와 2개의 vertex 좌표를 연속으로 표현하는 float 배열 1개를 담은 VBO 하나를 생성합니다.<br /> <br /> 이를 정리하면 문맥 설정에 따라 다음과 같은 식으로 호출이 이뤄집니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // VAO 문맥을 구성하고, uint vaoID = Gl.GenVertexArray(); Gl.BindVertexArray(vaoID); { // 해당 VAO의 슬롯에 들어갈 VBO를 구성 uint vboID = Gl.GenBuffer(); Gl.BindBuffer(BufferTarget.ArrayBuffer, vboID); { // VBO 문맥의 데이터를 구성 (data == float [6] 버퍼로 vertex 위치를 보관) Gl.BufferData(BufferTarget.ArrayBuffer, (uint)(data.Length * sizeof(float)), data, BufferUsage.StaticDraw); } // 현재 설정된 VBO를 VAO 0번 슬롯에 할당 Gl.VertexAttribPointer(0, coordinateSize, VertexAttribType.Float, false, 0, IntPtr.Zero); } Gl.BindVertexArray(0); </pre> <br /> 저 작업들을 3D 객체 하나마다 해줘야 하고, 일단 구성이 끝난 후 Delete 하기 전까지는 VAO ID를 가지고 화면에 렌더링을 할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Gl.BindVertexArray(vaoID); // VAO 바인딩 { Gl.EnableVertexAttribArray(0); // VAO의 0번 슬롯 (이전에 vertex 데이터를 할당했었던) 활성화 Gl.DrawArrays(PrimitiveType.Triangles, 0, model.VertexCount); // vertex 데이터를 기준으로 화면에 렌더링 Gl.DisableVertexAttribArray(0); // 0번 슬롯 비활성 } Gl.BindVertexArray(0); </pre> <br /> 대충 어떤 식인지 감이 오시나요? ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 참고로 원 강좌의 자바 구현보다 닷넷이 편리한 점이 있다면, 자바의 경우 값 형식의 float와 참조 형식의 float가 따로 있기 때문에 해당 코드에서는 float [] 배열을 FloatBuffer 참조 타입으로 변환하고 있지만 이 과정은 C#의 경우 필요가 없으므로 다음과 같이 곧바로 float [] 변수를 Gl.BufferData에 전달할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > void storeDataInAttributeList(uint attributeNumber, <span style='color: blue; font-weight: bold'>float [] data</span>) { uint vboID = Gl.GenBuffer(); vbos.Add(vboID); Gl.BindBuffer(BufferTarget.ArrayBuffer, vboID); Gl.BufferData(BufferTarget.ArrayBuffer, (uint)data.Length, <span style='color: blue; font-weight: bold'>data</span>, BufferUsage.StaticDraw); Gl.VertexAttribPointer(attributeNumber, 3, VertexAttribType.Float, false, 0, IntPtr.Zero); Gl.BindBuffer(BufferTarget.ArrayBuffer, 0); } </pre> <br /> 그리고 예제와는 달리, data.Length가 FloatBuffer에서 바이트 단위의 길이를 반환해 주는 것 같은데 따라서 닷넷의 경우 다음과 같이 바꿔야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > void storeDataInAttributeList(uint attributeNumber, float [] data) { uint vboID = Gl.GenBuffer(); vbos.Add(vboID); Gl.BindBuffer(BufferTarget.ArrayBuffer, vboID); Gl.BufferData(BufferTarget.ArrayBuffer, <span style='color: blue; font-weight: bold'>(uint)(data.Length * sizeof(float))</span>, data, BufferUsage.StaticDraw); Gl.VertexAttribPointer(attributeNumber, 3, VertexAttribType.Float, false, 0, IntPtr.Zero); Gl.BindBuffer(BufferTarget.ArrayBuffer, 0); } </pre> <br /> <hr style='width: 50%' /><br /> <br /> 다음은 위에서 설명한 내용을 기반으로 Java 소스 코드를 닷넷 형식으로 변환한 것입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // 아래의 2개 파일은 변화가 없고. // DisplayManager.cs // Program.cs </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // Loader.cs using OpenGL; using System; using System.Collections.Generic; namespace GameApp { class Loader { List<uint> _vaos = new List<uint>(); List<uint> _vbos = new List<uint>(); public RawModel loadToVAO(float [] positions) { uint vaoID = createVAO(); storeDataInAttributeList(0, positions); unbindVAO(); return new RawModel(vaoID, positions.Length / 3); } public void CleanUp() { Gl.DeleteVertexArrays(_vaos.ToArray()); Gl.DeleteBuffers(_vbos.ToArray()); } uint createVAO() { uint vaoID = Gl.GenVertexArray(); _vaos.Add(vaoID); Gl.BindVertexArray(vaoID); return vaoID; } unsafe void storeDataInAttributeList(uint attributeNumber, float [] data) { uint vboID = Gl.GenBuffer(); _vbos.Add(vboID); Gl.BindBuffer(BufferTarget.ArrayBuffer, vboID); Gl.BufferData(BufferTarget.ArrayBuffer, (uint)(data.Length * sizeof(float)), data, BufferUsage.StaticDraw); Gl.VertexAttribPointer(attributeNumber, 3, VertexAttribType.Float, false, 0, IntPtr.Zero); Gl.BindBuffer(BufferTarget.ArrayBuffer, 0); } void unbindVAO() { Gl.BindVertexArray(0); } } } </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // RawModel.cs namespace GameApp { class RawModel { uint vaoID; public uint VaoID { get { return vaoID; } } int vertexCount; public int VertexCount { get { return vertexCount; } } public RawModel(uint vaoID, int vertexCount) { this.vaoID = vaoID; this.vertexCount = vertexCount; } } } </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // Renderer.cs using OpenGL; namespace GameApp { class Renderer { public void Prepare() { Gl.ClearColor(1, 0, 0, 1); Gl.Clear(ClearBufferMask.ColorBufferBit); } public void Render(RawModel model) { Gl.BindVertexArray(model.VaoID); Gl.EnableVertexAttribArray(0); Gl.DrawArrays(PrimitiveType.Triangles, 0, model.VertexCount); Gl.DisableVertexAttribArray(0); Gl.BindVertexArray(0); } } } </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using OpenGL; using System.Windows.Forms; namespace GameApp { public partial class MainForm : Form { DisplayManager _displayManager = new DisplayManager(); <span style='color: blue; font-weight: bold'>RawModel _model; Loader _loader; Renderer _renderer; float[] vertices = { -0.5f, 0.5f, 0f, -0.5f, -0.5f, 0f, 0.5f, -0.5f, 0f, 0.5f, -0.5f, 0f, 0.5f, 0.5f, 0f, -0.5f, 0.5f, 0f };</span> public MainForm() { InitializeComponent(); } private void glControl_ContextCreated(object sender, OpenGL.GlControlEventArgs e) { GlControl glControl = (GlControl)sender; _displayManager.createDisplay(glControl); <span style='color: blue; font-weight: bold'>_loader = new Loader(); _model = _loader.loadToVAO(vertices); _renderer = new Renderer();</span> } private void glControl_ContextUpdate(object sender, GlControlEventArgs e) { } private void glControl_ContextDestroying(object sender, GlControlEventArgs e) { <span style='color: blue; font-weight: bold'>_loader.CleanUp();</span> } private void glControl_Render(object sender, OpenGL.GlControlEventArgs e) { Control senderControl = (Control)sender; Gl.Viewport(0, 0, senderControl.ClientSize.Width, senderControl.ClientSize.Height); <span style='color: blue; font-weight: bold'>_renderer.Prepare(); _renderer.Render(_model);</span> _displayManager.updateDisplay(); } } } </pre> <br /> 위의 예제를 실행하면 다음과 같은 결과를 볼 수 있습니다.<br /> <br /> <img alt='opengl_tutorial_2_1.png' src='/SysWebRes/bbs/opengl_tutorial_2_1.png' /><br /> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1396&boardid=331301885'>첨부 파일은 이 글의 예제 프로젝트를 포함</a>합니다.)<br /> <br /> <hr style='width: 50%' /><br /> <br /> 마지막으로, <br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Tutorial 2 : 첫 삼각형 ; <a target='tab' href='http://www.opengl-tutorial.org/kr/beginners-tutorials/tutorial-2-the-first-triangle/'>http://www.opengl-tutorial.org/kr/beginners-tutorials/tutorial-2-the-first-triangle/</a> </pre> <br /> 위의 글에 보면 VBO를 VAO 슬롯에 할당할 때,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // attributeNumber == 0 Gl.VertexAttribPointer(<span style='color: blue; font-weight: bold'>attributeNumber</span>, 3, VertexAttribType.Float, false, 0, IntPtr.Zero); </pre> <br /> attributeNumber의 값은 shader의 layout에 맞춰야 한다고 합니다. 현재는 (아마도) 기본 shader를 사용하는 것이기 때문에 반드시 0을 지정해야 하고 vertex 좌표값을 포함하고 있어야 합니다. (테스트 삼아 attributeNumber에 다른 값을 지정하니 그냥 응용 프로그램이 비정상 종료됩니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
8043
(왼쪽의 숫자를 입력해야 합니다.)