첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

■ 3차원 실린더 그리기

------------------------------------------------------------------------------------------------------------------------


TestProject.zip


MainWindow.xaml

 

 

<Window x:Class="TestProject.MainWindow"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Width="800"

    Height="600"

    Title="3차원 실린더 그리기"

    Loaded="Window_Loaded"

    KeyDown="Window_KeyDown">

    <Grid>

        <Viewport3D Name="viewport3D" />

    </Grid>

</Window>

 

 

MainWindow.xaml.cs

 

 

using System;

using System.Windows;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Media3D;

 

namespace TestProject

{

    /// <summary>

    /// 메인 윈도우

    /// </summary>

    public partial class MainWindow : Window

    {

        //////////////////////////////////////////////////////////////////////////////////////////////////// Field

        ////////////////////////////////////////////////////////////////////////////////////////// Private

 

        #region Field

 

        /// <summary>

        /// 3차원 모델 그룹

        /// </summary>

        private Model3DGroup model3Dgroup = new Model3DGroup();

 

        /// <summary>

        /// 카메라

        /// </summary>

        private PerspectiveCamera camera;

 

        /// <summary>

        /// 카메라 파이

        /// </summary>

        private double cameraPhi = Math.PI / 6.0;

 

        /// <summary>

        /// 카메라 세타

        /// </summary>

        private double cameraTheta = Math.PI / 6.0;

 

        /// <summary>

        /// 카메라 R

        /// </summary>

        private double cameraR = 3.0;

 

        /// <summary>

        /// 카메라 델타 파이

        /// </summary>

        private const double CAMERA_DELTA_PHI = 0.1;

 

        /// <summary>

        /// 카메라 델타 세타

        /// </summary>

        private const double CAMERA_DELTA_THETA = 0.1;

 

        /// <summary>

        /// 카메라 델타 R

        /// </summary>

        private const double CAMERA_DELTA_R = 0.1;

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor

        ////////////////////////////////////////////////////////////////////////////////////////// Public

 

        #region 생성자 - MainWindow()

 

        /// <summary>

        /// 생성자

        /// </summary>

        public MainWindow()

        {

            InitializeComponent();

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method

        ////////////////////////////////////////////////////////////////////////////////////////// Private

        //////////////////////////////////////////////////////////////////////////////// Event

 

        #region 윈도우 로드시 처리하기 - Window_Loaded(sender, e)

 

        /// <summary>

        /// 윈도우 로드시 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void Window_Loaded(object sender, RoutedEventArgs e)

        {

            this.camera = new PerspectiveCamera();

 

            this.camera.FieldOfView = 60;

 

            this.viewport3D.Camera = this.camera;

 

            SetCameraPosition();

 

            DefineLight();

 

            DefineModel(this.model3Dgroup);

 

            ModelVisual3D modelVisual3D = new ModelVisual3D();

 

            modelVisual3D.Content = this.model3Dgroup;

 

            this.viewport3D.Children.Add(modelVisual3D);

        }

 

        #endregion

        #region 윈도우 키 DOWN 처리하기 - Window_KeyDown(sender, e)

 

        /// <summary>

        /// 윈도우 키 DOWN 처리하기

        /// </summary>

        /// <param name="sender">이벤트 발생자</param>

        /// <param name="e">이벤트 인자</param>

        private void Window_KeyDown(object sender, KeyEventArgs e)

        {

            switch(e.Key)

            {

                case Key.Up :

 

                    this.cameraPhi += CAMERA_DELTA_PHI;

 

                    if(this.cameraPhi > Math.PI / 2.0)

                    {

                        this.cameraPhi = Math.PI / 2.0;

                    }

 

                    break;

 

                case Key.Down :

 

                    this.cameraPhi -= CAMERA_DELTA_PHI;

 

                    if(this.cameraPhi < -Math.PI / 2.0)

                    {

                        this.cameraPhi = -Math.PI / 2.0;

                    }

 

                    break;

 

                case Key.Left :

 

                    this.cameraTheta += CAMERA_DELTA_THETA;

 

                    break;

 

                case Key.Right :

 

                    this.cameraTheta -= CAMERA_DELTA_THETA;

 

                    break;

 

                case Key.Add     :

                case Key.OemPlus :

 

                    this.cameraR -= CAMERA_DELTA_R;

 

                    if(this.cameraR < CAMERA_DELTA_R)

                    {

                        this.cameraR = CAMERA_DELTA_R;

                    }

 

                    break;

 

                case Key.Subtract :

                case Key.OemMinus :

 

                    this.cameraR += CAMERA_DELTA_R;

 

                    break;

            }

 

            SetCameraPosition();

        }

 

        #endregion

 

        //////////////////////////////////////////////////////////////////////////////// Function

 

        #region 카메라 위치 설정하기 - SetCameraPosition()

 

        /// <summary>

        /// 카메라 위치 설정하기

        /// </summary>

        private void SetCameraPosition()

        {

            double y   = this.cameraR * Math.Sin(this.cameraPhi);

            double hyp = this.cameraR * Math.Cos(this.cameraPhi);

            double x   = hyp * Math.Cos(this.cameraTheta);

            double z   = hyp * Math.Sin(this.cameraTheta);

 

            this.camera.Position = new Point3D(x, y, z);

 

            this.camera.LookDirection = new Vector3D(-x, -y, -z);

 

            this.camera.UpDirection = new Vector3D(0, 1, 0);

        }

 

        #endregion

        #region 조명 정의하기 - DefineLight()

 

        /// <summary>

        /// 조명 정의하기

        /// </summary>

        private void DefineLight()

        {

            AmbientLight ambientLight = new AmbientLight(Colors.Gray);

 

            DirectionalLight directionalLight = new DirectionalLight(Colors.Gray, new Vector3D(-1.0, -3.0, -2.0));

 

            this.model3Dgroup.Children.Add(ambientLight);

            this.model3Dgroup.Children.Add(directionalLight);

        }

 

        #endregion

        #region 삼각형 추가하기 - AddTriangle(meshGeometry3D, point3D1, point3D2, point3D3)

 

        /// <summary>

        /// 삼각형 추가하기

        /// </summary>

        /// <param name="meshGeometry3D">3차원 메시 기하</param>

        /// <param name="point3D1">3차원 포인트 1</param>

        /// <param name="point3D2">3차원 포인트 2</param>

        /// <param name="point3D3">3차원 포인트 3</param>

        private void AddTriangle(MeshGeometry3D meshGeometry3D, Point3D point3D1, Point3D point3D2, Point3D point3D3)

        {

            int index = meshGeometry3D.Positions.Count;

 

            meshGeometry3D.Positions.Add(point3D1);

            meshGeometry3D.Positions.Add(point3D2);

            meshGeometry3D.Positions.Add(point3D3);

 

            meshGeometry3D.TriangleIndices.Add(index++);

            meshGeometry3D.TriangleIndices.Add(index++);

            meshGeometry3D.TriangleIndices.Add(index  );

        }

 

        #endregion

        #region 실린더 추가하기 - AddCylinder(meshGeometry3D, endPoint3D, axisVector3D, radius, sideCount)

 

        /// <summary>

        /// 실린더 추가하기

        /// </summary>

        /// <param name="meshGeometry3D">3차원 메시 기하</param>

        /// <param name="endPoint3D">종단 3차원 포인트</param>

        /// <param name="axisVector3D">축 3차원 벡터</param>

        /// <param name="radius">반경</param>

        /// <param name="sideCount">면 카운트</param>

        private void AddCylinder(MeshGeometry3D meshGeometry3D, Point3D endPoint3D, Vector3D axisVector3D, double radius, int sideCount)

        {

            // 축에 수직인 2개의 벡터를 구한다.

            Vector3D v1;

 

            if((axisVector3D.Z < -0.01) || (axisVector3D.Z > 0.01))

            {

                v1 = new Vector3D(axisVector3D.Z, axisVector3D.Z, -axisVector3D.X - axisVector3D.Y);

            }

            else

            {

                v1 = new Vector3D(-axisVector3D.Y - axisVector3D.Z, axisVector3D.X, axisVector3D.X);

            }

 

            Vector3D v2 = Vector3D.CrossProduct(v1, axisVector3D);

 

            // 반지름 길이를 갖는 벡터를 만든다.

            v1 *= (radius / v1.Length);

            v2 *= (radius / v2.Length);

 

            // 상단 끝 캡을 만든다.

            double theta      = 0;

            double deltaTheta = 2 * Math.PI / sideCount;

 

            for(int i = 0; i < sideCount; i++)

            {

                Point3D p1 = endPoint3D + Math.Cos(theta) * v1 + Math.Sin(theta) * v2;

 

                theta += deltaTheta;

 

                Point3D p2 = endPoint3D + Math.Cos(theta) * v1 + Math.Sin(theta) * v2;

 

                AddTriangle(meshGeometry3D, endPoint3D, p1, p2);

            }

 

            // 하단 끝 캡을 만든다.

            Point3D endPoint3D2 = endPoint3D + axisVector3D;

 

            theta = 0;

 

            for(int i = 0; i < sideCount; i++)

            {

                Point3D p1 = endPoint3D2 + Math.Cos(theta) * v1 + Math.Sin(theta) * v2;

 

                theta += deltaTheta;

 

                Point3D p2 = endPoint3D2 + Math.Cos(theta) * v1 + Math.Sin(theta) * v2;

 

                AddTriangle(meshGeometry3D, endPoint3D2, p2, p1);

            }

 

            theta = 0;

 

            for(int i = 0; i < sideCount; i++)

            {

                Point3D p1 = endPoint3D + Math.Cos(theta) * v1 + Math.Sin(theta) * v2;

 

                theta += deltaTheta;

 

                Point3D p2 = endPoint3D + Math.Cos(theta) * v1 + Math.Sin(theta) * v2;

 

                Point3D p3 = p1 + axisVector3D;

                Point3D p4 = p2 + axisVector3D;

 

                AddTriangle(meshGeometry3D, p1, p3, p2);

                AddTriangle(meshGeometry3D, p2, p3, p4);

            }

        }

 

        #endregion

        #region 모델 정의하기 - DefineModel(model3DGroup)

 

        /// <summary>

        /// 모델 정의하기

        /// </summary>

        /// <param name="model3DGroup"></param>

        private void DefineModel(Model3DGroup model3DGroup)

        {

            // Y축 실린더를 정의한다.

            MeshGeometry3D mesh1 = new MeshGeometry3D();

 

            AddCylinder(mesh1, new Point3D(0, 1, 0), new Vector3D(0, -2, 0), 0.25, 6);

 

            SolidColorBrush brush1    = Brushes.LightGreen;

            DiffuseMaterial material1 = new DiffuseMaterial(brush1);

            GeometryModel3D model1    = new GeometryModel3D(mesh1, material1);

 

            model3DGroup.Children.Add(model1);

 

            // X축 실린더를 정의한다.

            MeshGeometry3D mesh2 = new MeshGeometry3D();

 

            AddCylinder(mesh2, new Point3D(-1, 0, 0), new Vector3D(2, 0, 0), 0.375, 8);

 

            SolidColorBrush brush2    = Brushes.Red;

            DiffuseMaterial material2 = new DiffuseMaterial(brush2);

            GeometryModel3D model2    = new GeometryModel3D(mesh2, material2);

 

            model3DGroup.Children.Add(model2);

 

            // Z축 실린더를 정의한다.

            MeshGeometry3D mesh3 = new MeshGeometry3D();

 

            AddCylinder(mesh3, new Point3D(0, 0, 1), new Vector3D(0, 0, -2), 0.5, 20);

 

            SolidColorBrush brush3    = Brushes.LightBlue;

            DiffuseMaterial material3 = new DiffuseMaterial(brush3);

            GeometryModel3D model3    = new GeometryModel3D(mesh3, material3);

 

            model3DGroup.Children.Add(model3);

        }

 

        #endregion

    }

}

 

------------------------------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker

댓글을 달아 주세요