Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 3개 있습니다.)
.NET Framework: 281. Shader 강좌와 함께 배워보는 XNA Framework (1) - 기초 프로그램 구조
; https://www.sysnet.pe.kr/2/0/1196

.NET Framework: 282. Shader 강좌와 함께 배워보는 XNA Framework (2) - RenderMonkey의 Shader/Model 파일 연동
; https://www.sysnet.pe.kr/2/0/1197

.NET Framework: 285. Shader 강좌와 함께 배워보는 XNA Framework (3) - 텍스처 매핑 예제
; https://www.sysnet.pe.kr/2/0/1206




Shader 강좌와 함께 배워보는 XNA Framework (3) - 텍스처 매핑 예제


지난번 글에 이어서.

Shader 강좌와 함께 배워보는 XNA Framework (2) - RenderMonkey의 Shader/Model 파일 연동
; https://www.sysnet.pe.kr/2/0/1197

역시나 처음으로 "texture mapping"이라는 것도 해보게 되는군요. ^^

[포프의 쉐이더 입문강좌] 03. 텍스처매핑 Part 1 
; http://kblog.popekim.com/2011/12/03-part-1.html

[포프의 쉐이더 입문강좌] 03. 텍스처매핑 Part 2 
; http://kblog.popekim.com/2011/12/03-part-2.html

위에서 "Part 1"의 실습을 하면 RenderMonkey 도구의 "Vertex Shader" 코드만 포함하고 있기 때문에 정상적인 결과물을 볼 수 없습니다. 그래서 "Part 2" 강좌의 초입에 나오는 "Pixel Shader" 코드를 마저 입력해 주어야 컴파일이 성공하고 "Stream Mapping"까지 완료해야만 정상적인 지구본 모양의 이미지를 볼 수 있습니다.

ch3_texture_mapping_1.png

그렇게 렌더몽키 실습이 완료되었으면 본격적으로 XNAFramework 예제로 넘어가게 되는데요.

우선, 새롭게 실습한 RenderMonkey의 결과물을 각각 Sphere.x와 TextureMapping.fx 파일로 저장하고 TextureMapping의 원본으로 사용된 이미지 earth.jpg도 렌더몽키의 설치 디렉토리로부터(보통, C:\Program Files (x86)\AMD\RenderMonkey 1.82\Examples\Media\Textures) 복사해서 XNAMFramework 프로젝트에 복사합니다.

코드는 지난번의 예제 프로젝트를 기반으로 변경해 볼 텐데요.

WindowsGame1Content 프로젝트에 있는 기존 .x, .fx 자원을 삭제하고 새롭게 Sphere.x, TextureMapping.fx, earth.jpg 파일을 추가해 준 후 코드에 적용해 주는데, Sphere.x와 TextureMapping.fx는 기존 코드에 이미 Model/Effect 타입으로 정의되어 있기 때문에 이름만 바꿔주면 되고, earth.jpg 파일에 대해서는 Texture 타입으로 로드를 해줍니다.

Model _earthModel;
Effect _textureMappingShader;
Texture _earthTexture;

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);

    _spriteFont = Content.Load<SpriteFont>("Font");
    _earthModel = Content.Load<Model>("Sphere");
    _textureMappingShader = Content.Load<Effect>("TextureMapping");
    _earthTexture = Content.Load<Texture>("Earth");
}

마지막으로 _earthTexture 자원을 _textureMappingShader에 연결하는 코드를 넣어주면 끝입니다.

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    _matView = Matrix.CreateLookAt(new Vector3(0, 0, -200), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
    _matProjection = Matrix.CreatePerspectiveFieldOfView(FOV, ASPECT_RATIO, NEAR_PLANE, FAR_PLANE);
    _matWorld = Matrix.Identity;

    _textureMappingShader.Parameters["gWorldMatrix"].SetValue(_matWorld);
    _textureMappingShader.Parameters["gViewMatrix"].SetValue(_matView);
    _textureMappingShader.Parameters["gProjectionMatrix"].SetValue(_matProjection);
    _textureMappingShader.Parameters["DiffuseMap_Tex"].SetValue(_earthTexture);

    ... [생략] ...
    base.Draw(gameTime);
}

이제 빌드하고 실행하면 ^^ 정상적으로 지구본이 출력되는 것을 확인할 수 있습니다.

부가적으로, Part 2 강좌를 보면 지구본을 돌려주는 효과를 내도록 코드를 추가하고 있는데요. XNA에서도 다음과 같이 _matWorld 코드를 초기화하도록 변경해 주면 됩니다.

float _rotationY = 0.0f;

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    _matView = Matrix.CreateLookAt(new Vector3(0, 0, -200), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
    _matProjection = Matrix.CreatePerspectiveFieldOfView(FOV, ASPECT_RATIO, NEAR_PLANE, FAR_PLANE);

    _rotationY += 0.4f * PI / 180.0f;
    if (_rotationY > 2 * PI)
    {
        _rotationY -= 2 * PI;
    }

    _matWorld = Matrix.CreateRotationY(_rotationY);

    ... [생략] ...
}

다시 F5 키를 눌러서 실행하면, ^^ 와~~~ 지구본이 정말로 회전합니다.

ch3_texture_mapping_2.png

첨부된 파일은 위의 코드를 포함한 예제 프로젝트입니다.




참고로, 위의 글을 읽다 보면 UV 좌표라는 말이 나오는데요. 생소해서 찾아보니 다음과 같이 잘 설명된 글이 있습니다.

각종 3D 좌표 체계 정리
; http://bklist.egloos.com/tag/UV좌표/page/1
(위의 글을 보면, DirectX와 OpenGL의 z 좌표값이 반대로 된 것을 볼 수 있습니다. 개발자들 편하게 좀... 저런 건 맞춰주면 좋지 않았을까요? ^^;)

어쨌든 ^^ 잘 모르지만 이런 식으로 가랑비에 옷 젖듯 배워나가는 것도 좋겠지요.

마지막으로, 제 경우에 RenderMonkey 작업 시에 빌드를 했을 때 다음과 같은 오류가 발생해서 애를 먹었습니다.

Compiling vertex shader API(D3D) /../TextureMapping/Pass 0/Vertex Shader/
COMPILE ERROR: API(D3D) /../TextureMapping/Pass 0/Vertex Shader/ c:\program files (x86)\amd\rendermonkey 1.82\memory(17,11): error X3000: invalid target or usage string RENDERING ERROR(s):
Vertex shader 'Vertex Shader' failed to compile in pass 'Pass 0'. See Output window for details


처음엔 에러가 발생했다는 것만으로 당황해서 어찌할 줄 몰랐는데 "COMPILE ERROR"에 보면 (17,11)이라고 라인 수가 17에서 "invalid target or usage string"에 해당하는 오류가 났다는 것을 알게 되었습니다.

01: float4x4 gWorldMatrix;
02: float4x4 gViewMatrix;
03: float4x4 gProjectionMatrix;
04: 
05: struct VS_INPUT
06: {
07:    float4 mPosition : POSITION;
08:    float2 mTexCoord : TEXCOORD0;
09: };
10: 
11: struct VS_OUPUT
12: {
13:    float4 mPosition : POSITION;
14:    float2 mTexCoord : TEXCOORD0;
15: };
16: 
17: VS_OUTPUT vs_main(VS_INPUT Input)
18: {

VS_OUTPUT으로 되어 있는데, 11행에 보면 VS_OUPUT으로 실수했기 때문에 그런 에러가 발생한 것입니다. 나름, 오류가 발생한 위치를 알려주기 때문에 다음부터는 RenderMonkey의 컴파일 오류에 당황하지 않게 될 것 같습니다. ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/5/2021]

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

비밀번호

댓글 작성자
 




... 121  122  123  124  [125]  126  127  128  129  130  131  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
10797정성태5/23/201521579VC++: 91. 자식 스레드에 자동 상속되는 TEB의 SubProcessTag 필드파일 다운로드1
10796정성태5/23/201532406오류 유형: 293. SQL Server Management Studio 실행 시 "Cannot find one or more components" 오류
10795정성태5/23/201530529오류 유형: 292. InstallUtil로 .NET 서비스 등록 시 오류 - Operation is not supported. (Exception from HRESULT: 0x80131515). [3]
10794정성태5/22/201525494개발 환경 구성: 267. (무료) 마이크로소프트 온라인 강좌 소개 - 네트워킹 기초 [1]
2925정성태5/14/201525112디버깅 기술: 73. PDB 기호 파일의 경로 구성 방식파일 다운로드1
2924정성태5/14/201528410VS.NET IDE: 100. 비주얼 스튜디오 원격 디버깅 시 'Unknown function' 콜스택이 나온다면?
2923정성태5/12/201587758기타: 52. 도서: 시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지 [17]
2922정성태5/12/201524610오류 유형: 291. ssindex.cmd 실행 시 '...[tfs_collection_url]...' not found in srcsrv.ini 오류 발생
2921정성태5/9/201530960개발 환경 구성: 266. 인텔에서 구현한 최대 절전 모드 기능 - Intel® Rapid Start Technology
2920정성태5/9/201522092오류 유형: 290. 디스크 관리자의 파티션 축소 시, There is not enough space available on the disk(s) to complete this operation.
2919정성태5/9/201521943오류 유형: 289. Error: this template attempted to load component assembly 'NuGet.VisualStudio.Interop, ...'
2918정성태5/9/201540491Windows: 111. 복구(Recovery) 파티션 삭제하는 방법 [3]
2917정성태5/9/201530933오류 유형: 288. .NET Framework 4.6이 설치된 경우 "Intel® Rapid Storage Technology (Intel® RST) RAID Driver"가 설치 안 되는 문제 [5]
2916정성태5/9/201531997오류 유형: 287. 레지스트리 권한 오류 - Cannot edit [Registry key name]: Error writing the value's new contents.
2915정성태5/9/201531125개발 환경 구성: 265. TrustedInstaller 권한으로 프로그램 실행시키는 방법 [11]
2914정성태5/9/201528486DDK: 7. 정식 인증서가 있는 경우 Device Driver 서명하는 방법 [2]
2913정성태4/30/201526234.NET Framework: 511. Build 2015 행사에서 소개된 (맥/리눅스/윈도우 용 무료) Visual Studio Code 개발 도구 [8]
2912정성태4/29/201521966오류 유형: 286. VirtualBox에 Windows 8/2012 설치 시 "Error Code: 0x000000C4" 오류 발생
2911정성태4/29/201520547오류 유형: 285. Visual Studio 2015를 제거한 경우 Microsoft.VisualStudio.Web.PageInspector.Loader 어셈블리를 못 찾는 문제 [2]
2910정성태4/29/201524452오류 유형: 284. System.TypeLoadException: Could not load type 'System.Reflection.AssemblySignatureKeyAttribute' from assembly [1]
2909정성태4/29/201520591오류 유형: 283. WCF 연결 오류 - Expected record type 'PreambleAck'
2908정성태4/29/201528893오류 유형: 282. 원격에서 SQL 서버는 연결되지만, SQL Express는 연결되지 않는 경우
2907정성태4/29/201518944.NET Framework: 510. 제네릭(Generic) 인자에 대한 메타데이터 등록 확인
2906정성태4/28/201521543오류 유형: 281. DebugView로 인한 System.Diagnostics.Trace.WriteLine 멈춤(Hang) 현상
2905정성태4/27/201521927오류 유형: 280. HttpResponse.Headers.Add에서 "System.PlatformNotSupportedException: This operation requires IIS integrated pipeline mode." 예외 발생
2904정성태4/27/201527169DDK: 6. ZwTerminateProcess로 프로세스를 종료하는 Device Driver 프로그램 [2]파일 다운로드1
... 121  122  123  124  [125]  126  127  128  129  130  131  132  133  134  135  ...