Microsoft MVP성태의 닷넷 이야기
Graphics: 31. .NET으로 구현하는 OpenGL (6) - Texturing [링크 복사], [링크+제목 복사]
조회: 13376
글쓴 사람
정성태 (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 (6) - Texturing

아래의 글에 이어,

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

6회 강좌는,

OpenGL 3D Game Tutorial 6: Texturing
; https://youtu.be/SPt-aogu72A

3D 객체에 texture를 입히는 방법에 대해 설명하고 있습니다. OpenGL에서 texture는 이미지의 색상 데이터를 구하는 것에서 시작하는데, 아쉽게도 OpenGL 자체는 이미지 파일들에 대한 로드 방법을 제공하지 않습니다. 즉, 그 부분은 우리가 직접 구현해야 하는 것입니다. 가령, 그나마 가장 간단한 유형인 BMP 파일의 경우 아래의 글에 설명하는 데로,

Tutorial 5 : A Textured Cube
; http://www.opengl-tutorial.org/kr/beginners-tutorials/tutorial-5-a-textured-cube/

직접 이미지의 데이터를 로드해서 glGenTextures, glBindTexture, glTexImage2D 등의 함수를 이용해 사용할 수 있습니다. 그런데, 사실 저건 C/C++의 상황에서 그런 것이고 닷넷이라면 Bitmap 타입이 알아서 대표적인 이미지들에 대한 데이터 처리를 해주므로,

OpenGL C# (OpenTK) Load and Draw Image functions not working
; https://stackoverflow.com/questions/11645368/opengl-c-sharp-opentk-load-and-draw-image-functions-not-working

그나마 간단하게 OpenGL 리소스로 바인딩할 수 있습니다. 혹은, 다양한 이미지 파일을 OpenGL 용으로 바인딩해주는 라이브러리를 가져다 쓰는 것도 가능합니다. soil이 그런 용도로 사용할 수 있는 오픈 소스인데요,

soil 1.16.0 - Simple OpenGL Image Library 
; https://www.nuget.org/packages/soil/
; http://www.lonesock.net/soil.html

NuGet에서도 제공하긴 하지만 아쉽게도 해당 라이브러리는 C/C++ 용으로 닷넷에서는 사용할 수 없습니다. 대신... ^^ 제가 저 라이브러리를 .NET 용으로 래핑했으므로,

SOIL(Simple OpenGL Image Library) - Native DLL 및 .NET DLL 제공
; https://www.sysnet.pe.kr/2/0/11768
; https://www.nuget.org/packages/SoilDotnet

저걸 가져다 쓰시면 됩니다.

Install-Package SoilDotnet

자, 그럼 지난 5회 강좌의 소스 코드에 texture를 입히는 과정을 진행해 보겠습니다.




우선, 3D 객체의 정보를 담고 있는 Model에 texture 매핑 정보를 담을 UV 좌표 데이터를 연결해야 합니다.

// MainForm.cs

float[] _textureCoords =
{
    0,0, // V0
    0,1, // V1
    1,1, // V2
    1,0, // V3
};

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

    // ...[생략]...

    // 3D 객체에 _textureCoords UV 좌표 데이터를 추가
    _model = _loader.loadToVAO(_vertices, _textureCoords, _indices);

    // ...[생략]...
}

loadToVAO에서는 당연히 _textureCoords 데이터를 GPU 메모리에 올리고, VAO의 슬롯 하나에 UV 데이터를 바인딩합니다.

// Loader.cs

public RawModel loadToVAO(float [] positions, float [] textures, int[] indices)
{
    uint vaoID = createVAO();

    bindIndicesBuffer(indices);
    storeDataInAttributeList(0, 3, positions); // Position 데이터를 VAO의 0번 슬롯에 할당
    storeDataInAttributeList(1, 2, textures);  // textures UV 매핑 데이터를 VAO의 1번 슬롯에 할당
    unbindVAO();

    return new RawModel(vaoID, positions.Length);
}

unsafe void storeDataInAttributeList(uint attributeNumber, int coordinateSize, 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, coordinateSize, VertexAttribType.Float, false, 0, IntPtr.Zero);

    Gl.BindBuffer(BufferTarget.ArrayBuffer, 0);
}

texture UV 매핑 데이터를 Model에 넣었으니 이제 해당 texture를 로드해야 합니다. 이를 위해 Texture 처리를 Loader 타입에 제공하고,

// Loader.cs

List _textures = new List();

public void CleanUp()
{
    Gl.DeleteVertexArrays(_vaos.ToArray());
    Gl.DeleteBuffers(_vbos.ToArray());
    Gl.DeleteTextures(_textures.ToArray());
}

public uint loadTexture(string fileName)
{
    string filePath = $".\\res\\{fileName}.png";

    uint tex2d_id = Soil.NET.WrapSOIL.load_OGL_texture(filePath, Soil.NET.WrapSOIL.SOIL_LOAD.AUTO, Soil.NET.WrapSOIL.SOIL_NEW.ID,
        Soil.NET.WrapSOIL.SOIL_FLAG.MIPMAPS | Soil.NET.WrapSOIL.SOIL_FLAG.NTSC_SAFE_RGB | Soil.NET.WrapSOIL.SOIL_FLAG.COMPRESS_TO_DXT);

    _textures.Add(tex2d_id);
    return tex2d_id;
}

Model에 입힐 Texture 자원의 바인딩 핸들을 보관할 ModelTexture 타입과,

// ModelTexture.cs

namespace GameApp
{
    public class ModelTexture
    {
        uint _textureID;
        public uint ID
        {
            get { return _textureID; }
        }

        public ModelTexture(uint id)
        {
            this._textureID = id;
        }
    }
}

Texture가 지정된 Model을 나타내는 TextureModel 타입을 만듭니다. (작명이 다소 혼란스럽지만 원 강좌의 내용을 그대로 따라 했습니다.)

// TextureModel.cs

namespace GameApp.Model
{
    public class TextureModel
    {
        RawModel _rawModel;
        public RawModel RawModel
        {
            get { return _rawModel; }
        }

        ModelTexture _texture;
        public ModelTexture Texture
        {
            get { return _texture; }
        }

        public TextureModel(RawModel model, ModelTexture texture)
        {
            this._rawModel = model;
            this._texture = texture;
        }
    }
}

이제 이것들을 통합해서 초기화하면 데이터는 모두 마련이 됩니다.

// MainForm.cs

ModelTexture _texture;
TextureModel _textureModel;

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

    // SOIL.NET 초기화
    bool result = Soil.NET.WrapSOIL.Initialize();
    if (result == false)
    {
        MessageBox.Show("SOIL: Not initialized: " + Soil.NET.WrapSOIL.GetSoilLastError());
        return;
    }

    _loader = new Loader();
    _renderer = new Renderer();
    _model = _loader.loadToVAO(_vertices, _textureCoords, _indices);
    _texture = new ModelTexture(_loader.loadTexture("image"));
    _textureModel = new TextureModel(_model, _texture);
    _shader = new StaticShader();
}

(잊지 말고 /res 폴더에 256x256 크기의 image.png 파일을 넣어둡니다.)




나머지는 이제 렌더링과 관련된 변경을 해야 합니다. Texture가 지정된 Model이 되었으므로 이제 Renderer 타입에서는 _textureModel을 렌더링할 수 있어야 합니다.

// MainForm.cs

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

    _renderer.Prepare();
    _shader.Start();
    _renderer.Render(_textureModel);
    _shader.Stop();

    _displayManager.updateDisplay();
}

따라서 Renderer의 Redner 메서드도 다음과 같이 바뀌게 됩니다.

public void Render(TextureModel textureModel)
{
    RawModel model = textureModel.RawModel;
    Gl.BindVertexArray(model.VaoID);
    Gl.EnableVertexAttribArray(0);
    Gl.EnableVertexAttribArray(1); // UV 매핑 데이터 Slot 활성

    Gl.ActiveTexture(TextureUnit.Texture0);
    Gl.BindTexture(TextureTarget.Texture2d, textureModel.Texture.ID);
    Gl.DrawElements(PrimitiveType.Triangles, model.VertexCount, DrawElementsType.UnsignedInt, IntPtr.Zero);

    Gl.DisableVertexAttribArray(0);
    Gl.DisableVertexAttribArray(1); // UV 매핑 데이터 Slot 비활성
    Gl.BindVertexArray(0);
}

끝입니다. 이렇게 변경하고 실행하면 다음과 같은 화면을 볼 수 있습니다.

opengl_tutorial_6_1.png

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




참고로 이번에도 역시, bindAttribute의 코드는 없애도 실행에는 아무런 지장이 없습니다.

// StaticShader.cs

public class StaticShader : ShaderProgram
{
    const string VERTEX_FILE = "./shaders/vertexShader.txt";
    const string FRAGMENT_FILE = "./shaders/fragmentShader.txt";

    public StaticShader() : base(VERTEX_FILE, FRAGMENT_FILE)
    {
    }

    protected override void bindAttributes()
    {
        // base.bindAttribute(0, "_position");
        // base.bindAttribute(1, "_textureCoords");
    }
}





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







[최초 등록일: ]
[최종 수정일: 11/18/2018]

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13428정성태10/25/20232961닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233152닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233322스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233140닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233115스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233268닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233313닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235458스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233148스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233840닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233396닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233186오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233677닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233445디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233641닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236917닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233411Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20234926닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233783닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233762Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233515닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233474VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233919닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233427오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233262오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/20233326닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...