본문 바로가기
프로그래밍

텍스쳐를 붙인 3D프리미티브 표시하기

by 건우아빠유리남편 2009. 7. 14.
반응형

텍스쳐를 붙인 3D프리미티브를 표시하는 프로그램을 만듭니다.

 

리소스 추가

이번 프로그램에선 그림 한 장 쓰고..이제 알아서 프로젝트에 추가하십셔.

heniheni.png

 

이펙트 파일 추가

이번 프로그램에서는 이펙트 파일을 하나 쓸 겁니다. 프로젝트에 추가 ㄱㄱ

이펙트 파일에 대해서는 또 다음 시간에..

 

TextureEffect.fx

float4x4 worldViewProj : WORLDVIEWPROJECTION;

texture  cubeTexture;

 

struct VS_INPUT {

    float4 pos      : POSITION;

    float4 texcoord : TEXCOORD0;

};

 

struct VS_OUTPUT {

    float4 pos      : POSITION;

    float4 texcoord : TEXCOORD0;

};

 

sampler textureSampler = sampler_state {

    Texture  =<cubeTexture>;

    mipfilter=LINEAR;

};

 

VS_OUTPUT VS_TextureTech(VS_INPUT In) {

 

    VS_OUTPUT Out=(VS_OUTPUT)0;

 

    Out.pos     =mul(In.pos,worldViewProj);

    Out.texcoord=In.texcoord;

 

    return Out;

}

 

float4 PS_TextureTech(VS_OUTPUT Out) : COLOR {

    return tex2D(textureSampler,Out.texcoord).rgba;

}

 

technique TextureTech {

    pass P0 {

        vertexShader=compile vs_2_0 VS_TextureTech();

        pixelShader =compile ps_2_0 PS_TextureTech();

    }

}

 

소스코드 편집

 

Game1.cs를 편집한다.

Game1.cs

using System;

using System.Collections.Generic;

using Microsoft.Xna.Framework;

using Microsoft.Xna.Framework.Audio;

using Microsoft.Xna.Framework.Graphics;

using Microsoft.Xna.Framework.Input;

using Microsoft.Xna.Framework.Storage;

using Microsoft.Xna.Framework.Content;

 

//텍스쳐를 붙인 프리미티브 3D

namespace TextureEx {

    public class Game1 : Game {

        //시스템

        private GraphicsDeviceManager graphics;

        private ContentManager        content;  

 

        //3D프리미티브

        private Matrix                  worldViewProj; //월드xx사영행렬

        private Effect                  effect;       //이펙트

        private VertexDeclaration       cubeVertexDec; //정점정의

        private VertexPositionTexture[] cubeVertices; //정점들

        private VertexBuffer            vertexBuffer; //정점버퍼

        private short[]                 cubeIndices;  //인덱스리스트

        private IndexBuffer             indexBuffer;  //인덱스버퍼

        private Texture                 cubeTexture;  //입방체텍스쳐

 

        //constructor

        public Game1() {

            graphics =new GraphicsDeviceManager(this);

            content  =new ContentManager(Services);

        }

 

        //좌표변환 초기화

        private void InitializeTransform() {

            //월드 변환행렬

            Matrix world =

                Matrix.CreateRotationX((float)Math.PI / 6.0f) *

//X 30도회전

                Matrix.CreateRotationY((float)Math.PI / 6.0f); 

//Y 30도회전

 

            //뷰 매트릭스

            Matrix view = Matrix.CreateLookAt(

                new Vector3(0, 0, 5), //시점

                Vector3.Zero,        //참조점

                Vector3.Up);         //UP레벨

 

            //사영변환행렬

            Matrix projection = Matrix.CreatePerspectiveFieldOfView(

                (float)Math.PI / 4.0f, //시야각(라디안 단위)

                (float)graphics.GraphicsDevice.Viewport.Width /

                (float)graphics.GraphicsDevice.Viewport.Height, //종횡도

                1.0f,                 //니어 클립면의 거리

                100.0f);              //파 클립면의 거리

 

            //월드xx사영행렬

            worldViewProj = world * view * projection;

        }

 

        //이펙트 읽어오기

        private void InitializeEffect() {

            cubeTexture = content.Load<Texture2D>("heniheni");         //텍스쳐

            effect = content.Load<Effect>("TextureEffect");            //이펙트파일

            effect.Parameters["worldViewProj"].SetValue(worldViewProj); //이어주기

            effect.Parameters["cubeTexture"].SetValue(cubeTexture);

            effect.CurrentTechnique = effect.Techniques["TextureTech"];

        }

 

        //입방체 초기화

        private void InitializeCube() {

            //입방체 정점정의

            cubeVertexDec = new VertexDeclaration(

                graphics.GraphicsDevice,              //그래픽스디바이스

                VertexPositionTexture.VertexElements); //요소배열

 

            //정점

            Vector3 topLeftFront     = new Vector3(-1.0f,  1.0f,  1.0f);

            Vector3 bottomLeftFront  = new Vector3(-1.0f, -1.0f,  1.0f);

            Vector3 topRightFront    = new Vector3( 1.0f,  1.0f,  1.0f);

            Vector3 bottomRightFront = new Vector3( 1.0f, -1.0f,  1.0f);

            Vector3 topLeftBack      = new Vector3(-1.0f,  1.0f, -1.0f);

            Vector3 topRightBack     = new Vector3( 1.0f,  1.0f, -1.0f);

            Vector3 bottomLeftBack   = new Vector3(-1.0f, -1.0f, -1.0f);

            Vector3 bottomRightBack  = new Vector3( 1.0f, -1.0f, -1.0f);

 

            //텍스쳐 정점

            Vector2 textureTopLeft     = new Vector2(0.0f, 0.0f);

            Vector2 textureTopRight    = new Vector2(1.0f, 0.0f);

            Vector2 textureBottomLeft  = new Vector2(0.0f, 1.0f);

            Vector2 textureBottomRight = new Vector2(1.0f, 1.0f);

 

 

            //입방체 정점

            cubeVertices = new VertexPositionTexture[36];

 

            //

            cubeVertices[0] = new VertexPositionTexture(topLeftFront,    textureTopLeft);

            cubeVertices[1] = new VertexPositionTexture(bottomLeftFront, textureBottomLeft);

            cubeVertices[2] = new VertexPositionTexture(topRightFront,   textureTopRight);

            cubeVertices[3] = new VertexPositionTexture(bottomRightFront,textureBottomRight);

 

            //

            cubeVertices[4] = new VertexPositionTexture(topLeftBack,    textureTopRight);

            cubeVertices[5] = new VertexPositionTexture(topRightBack,   textureTopLeft);

            cubeVertices[6] = new VertexPositionTexture(bottomLeftBack, textureBottomRight);

            cubeVertices[7] = new VertexPositionTexture(bottomRightBack,textureBottomLeft);

 

            //

            cubeVertices[8]  = new VertexPositionTexture(topLeftFront, textureBottomLeft);

            cubeVertices[9]  = new VertexPositionTexture(topRightBack, textureTopRight);

            cubeVertices[10] = new VertexPositionTexture(topLeftBack,  textureTopLeft);

            cubeVertices[11] = new VertexPositionTexture(topRightFront,textureBottomRight);

 

            //아래

            cubeVertices[12] = new VertexPositionTexture(bottomLeftFront, textureTopLeft);

            cubeVertices[13] = new VertexPositionTexture(bottomLeftBack,  textureBottomLeft);

            cubeVertices[14] = new VertexPositionTexture(bottomRightBack, textureBottomRight);

            cubeVertices[15] = new VertexPositionTexture(bottomRightFront,textureTopRight);

 

            //왼쪽

            cubeVertices[16] = new VertexPositionTexture(topLeftFront,    textureTopRight);

            cubeVertices[17] = new VertexPositionTexture(bottomLeftFront, textureBottomRight);

            cubeVertices[18] = new VertexPositionTexture(topRightFront,   textureTopLeft);

            cubeVertices[19] = new VertexPositionTexture(bottomRightFront,textureBottomLeft);

 

            //정점버퍼

            vertexBuffer = new VertexBuffer(

                graphics.GraphicsDevice,

                VertexPositionTexture.SizeInBytes * cubeVertices.Length,

                ResourceUsage.None,

                ResourceManagementMode.Automatic);

            vertexBuffer.SetData<VertexPositionTexture>(cubeVertices);

           

            //인덱스리스트

            cubeIndices = new short[] {  

                 0,  1,  2,  //앞면

                 1,  3,  2,

                 4,  5,  6,  //뒷면

                 6,  5,  7,

                 8,  9, 10,  //윗면

                 8, 11,  9,

                12, 13, 14,  //아랫면

                12, 14, 15,

                16, 13, 17,  //왼쪽면

                10, 13, 16,

                18, 19, 14,  //오른쪽면

                 9, 18, 14 };

 

            //인덱스 버퍼

            indexBuffer = new IndexBuffer(graphics.GraphicsDevice,

                sizeof(short) * cubeIndices.Length,

                ResourceUsage.None,

                ResourceManagementMode.Automatic,

                IndexElementSize.SixteenBits);

            indexBuffer.SetData<short>(cubeIndices);

        }

 

        //그래픽스 로드

        protected override void LoadGraphicsContent(bool loadAllContent) {

            InitializeTransform();

            if (loadAllContent) {

                InitializeEffect();

                InitializeCube();

            }

        }

 

        //그래픽스 언로드

        protected override void UnloadGraphicsContent(bool unloadAllContent) {

            if (unloadAllContent == true) {

                content.Unload();

            }

        }

 

        //그리기

        protected override void Draw(GameTime gameTime) {

            //화면 클리어

            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

 

            //cull모드 설정

            graphics.GraphicsDevice.RenderState.CullMode =

                CullMode.CullClockwiseFace;

 

            //정점 정의

            graphics.GraphicsDevice.VertexDeclaration = cubeVertexDec;

 

            //정점 버퍼

            graphics.GraphicsDevice.Vertices[0].SetSource(

                vertexBuffer,

                0,

                VertexPositionTexture.SizeInBytes);

 

            //인덱스 버퍼 지정

            graphics.GraphicsDevice.Indices = indexBuffer;

 

            //입방체 그리기

            effect.Begin();

            foreach (EffectPass pass in effect.CurrentTechnique.Passes) {

                pass.Begin();

                graphics.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,

                    0,

                    0,

                    cubeVertices.Length,

                    0,

                    12);

                pass.End();

            }

            effect.End();

 

            //베이스 그리기

            base.Draw(gameTime);

        }

 

   

    }

}

 

반응형

'프로그래밍' 카테고리의 다른 글

[3.0] 3D 모델 표시하기  (0) 2009.07.14
텍스쳐 어둡게 하기  (0) 2009.07.14
ViewingPipeline  (0) 2009.07.14
3D프리미티브 표시하기  (0) 2009.07.14
커스텀쉐이더 이용하기  (0) 2009.07.14

댓글