관리 메뉴


Kinesis´s Open Document

WebGL / Three.js - 시작하기 ( Getting Started ) #01 본문

MEMO/기술 자료/WebGL

WebGL / Three.js - 시작하기 ( Getting Started ) #01

Kinesis 2012. 8. 27. 14:37

웹 영역이 점점 넓어져 이제는 3D 영역 까지 삼켜가고 있다. 아직까지는 소프트웨어와 웹 영역이 구분이 되어 있지만 이것도 조만간 10년 이내에 웹 영역으로 많은 부분 흡수되어 트렌드의 전환이 이루어질 것 같다. 물론 이러한 것은 HTML5 과 함께 모습을 드러내기 시작한 WebGL 및 웹 소켓등과 같은 신기술의 등장이 있었기 때문이다.

 

그러나 사실상 현재로서는 이 WebGL 과 웹 소켓 및 HTML5 등이 완벽하지는 않다. 웹브라우저의 호환성등의 이유로 인해 발목잡혀 있기 때문이다. 더욱이 브라우저 사용율 90% 가량이 인터넷 익스플로러로 웹 호환성에서 가장 취약한 브라우저를 이용하는 우리나라는 더욱 말할 것도 없다.

 

인터넷 익스플로러에서 고수하는 고집이 얼마나 갈지는 장담할 수 없다. 우리나라에서 IE를 버리지 못하는 단 하나의 이유... 바로 공기업과 대부분의 연계처리 시스템으로 들어가버리면 "더럽고 추잡하다"고 표현하고 싶을 정도의 액티브엑스로 떡질된 국내 웹 환경 때문일 것이다. (표현이 격하기는 하지만, 개인적으로 액티브엑스를 혐오하다보니 표현이 이리 되어 양해를 구한다)

 

아무튼 모바일용 윈도우를 한번 버려야했던 MS가 다시한번 웹 브라우저 환경에서는 다시금 패배를 시인해야하지 않을까 싶지만, 여기서 서론은 거두절미하고 짬짬히 WebGL 에대해 살펴 보려고 한다.

 

그 중에서도 오늘은 WebGL 과 관련된 라이브러리 중 하나인 Three.js 를 살펴볼까 한다. (개인적으로는 3D 공부를 해본적이 없다. but, 나도 슬슬 3D 분야에 발을 담그기 위해 준비해야할 시기가 오는 것 같아 하나둘 준비를 하고자 한다. 노가다적인 번역을 통해서라도....! 따라서 같이 가주는 사람이 있다면 고마운 것이고, 아니면 아닌대로 공부를 해나가보도록 하자.)

 

 

 

[ Link : https://github.com/mrdoob/three.js/wiki/Getting-Started ] 에 가보면 Getting Started 라는 제목의 Wiki 페이지를 볼 수 있다. 아주 간단하게 three.js 를 이용하여 사각형의 3D 객체를 만드는 튜토리얼이다. 해당 문서를 따라 만들어지는 최종 결과물의 모습은 다음과 같다.

 

 

이제 어떻게 해서 이렇게 3D 객체가 생성이 되는지 문서를 읽어가면서 이해해보도록 하자.

 


 

 

Three.js scenes are very easy to setup and only require a few lines of code to initialize. Scenes are constructed using a few different types of objects: cameras, lights, and meshes.

Three.js 장면은 단 몇줄의 코드만으로 매우 간단하게 초기화 설정을 할 수 있습니다. 장면은 카메라, 빛, 메쉬 등 몇 가지의 개별 오브젝트로 구성되어 집니다.

 

The first step in rendering a three.js scene is creating the WebGL renderer object. The following code creates an HTML canvas object 800x640 pixels, adds it to the document's body, and initializes a three.js scene.

three.js 장면을 렌더링 하는 첫번째 단계는 WebGL 렌더러 오브젝트를 생성하는 것입니다. 다음의 코드는 800x640 픽셀의 캔버스를 생성, 문서의 본문에 추가하여 three.js 장면을 초기화 합니다.

 

var renderer = new THREE.WebGLRenderer();
renderer.setSize( 800, 640 );
document.body.appendChild( renderer.domElement );

 

var scene = new THREE.Scene();

 

The second step is to define a camera which the renderer object will use in rendering.

두번째 단계는 렌더링에 사용될 렌더러 오브젝트에 카메라를 선언하는 것입니다.

 

var camera = new THREE.PerspectiveCamera(
    35,         // Field of view
    800 / 640,  // Aspect ratio
    .1,         // Near
    10000       // Far
);
camera.position.set( -15, 10, 15 );
camera.lookAt( scene.position );
scene.add( camera );

 

The first parameter passed determines how wide the field of view is. The second parameter is the aspect ratio which is calculated by dividing the viewing area's width by its height. The third and fourth parameters specify cut-off points for objects in the camera's view. If an object's distance from the camera does not fall in the range between NEAR and FAR then that object is not rendered. The last line sets the camera's XYZ coordinates to -15, 10, and 15 respectively.

첫번째 파라메터는 필드를 얼마나 넓게 볼 것인지 결정하여 전달합니다. 두번째 파라미터는 보는 영역의 높이와 폭을 나누어 계산한 비율(화면비율)입니다. 세번째와 네번째 파라미터는 카메라의 뷰에서 객체에 대한 절단 포인트를 지정합니다. 만약 객체의 거리가 NEAR 과 FAR 의 범위에 속하지 않는다면 렌더링이 되지 않습니다. 마지막 라인은 카메라의 XYZ 좌표를 -15, 10, 15 좌표로 각각 설정합니다.

 

Step three creates a white cube that is 5 units wide, tall and deep, adds the Lambert material, and adds it to the scene.

세번째 단계는 가로, 높이, 깊이가 각각 5유닛인 흰색의 큐브를 생성, 재질을 추가한 뒤 장면에 삽입합니다.

 

var cube = new THREE.Mesh(
    new THREE.CubeGeometry( 5, 5, 5 ),
    new THREE.MeshLambertMaterial( { color: 0xFF0000 } )
);
scene.add( cube );

 

For the last step in setting up a scene we create a yellow light source and add it to the scene.

노란 빛의 소스를 장면에 추가하는 것을 마지막으로 우리는 장면을 설정의 마지막 단계를 끝내게 됩니다.

 

var light = new THREE.PointLight( 0xFFFF00 );
light.position.set( 10, 0, 10 );
scene.add( light );

 

Finally we render the scene which displays our scene through the camera's eye.

최종적으로 우리는 렌더링을 통해 카메라의 렌즈를 통해 비추어진 장면을 볼 수 있게 됩니다.

 

renderer.render(scene, camera);

 

Everything together in a working example with a minimal HTML template:

일련의 과정을 함께 진행한 최소한의 예제 HTML 템플릿은 다음과 같을겁니다.

 

<!DOCTYPE html>

<html>

<head>
    <title>Getting Started with Three.js</title>

    <script type="text/javascript" src="Three.js"></script>
    <script type="text/javascript">
    window.onload = function() {

            var renderer = new THREE.WebGLRenderer();
            renderer.setSize( 800, 600 );
            document.body.appendChild( renderer.domElement );

            var scene = new THREE.Scene();

            var camera = new THREE.PerspectiveCamera(
                                            35,             // Field of view
                                            800 / 600,      // Aspect ratio
                                            0.1,            // Near plane
                                            10000           // Far plane
                                        );
            camera.position.set( -15, 10, 10 );
            camera.lookAt( scene.position );

            scene.add( camera );

            var cube = new THREE.Mesh(
                                    new THREE.CubeGeometry( 5, 5, 5 ),
                                    new THREE.MeshLambertMaterial( { color: 0xFF0000 } )
                                );
            scene.add( cube );

            var light = new THREE.PointLight( 0xFFFF00 );
            light.position.set( 10, 0, 10 );
            scene.add( light );

            renderer.render( scene, camera );

        };
    </script>
</head>

<body></body>

</html>

 

 


 

초안용 메모 2012.08.27 Kinesis 작성

 

 

 


Comments