Importing a Modeled Mesh From Blender to Three.js

It has been a very long time since the last Three.js rotating cube post. Better late than never, right? Here is the next part about the import and animation of a more complex mesh created in a modeling software. Yet, as we are not designer (and a fortiori, not 3D designer), we will focus on a not too complicated mesh: the marmelab logo.

marmelab logo

Modeling Marmelab Logo with Blender

We are going to use Blender, a free and open-source 3D modeler. First, let’s create the mesh. Fortunately, marmelab logo is quite simple: it is composed of five cubes glued together to form the letter M. Here is a video describing this modeling:

Export a Blender Mesh in JSON for Three.js

Now that we got our mesh (you can download it here), let’s take a look on how to export it for Three.js. Three.js expects to get a Mesh in JSON format. Fortunately, the community has already provided a Blender to Three.js exporter. So, download it and put the io_threefolder under your ~/.config/blender/2.69/scripts/addons/ folder or its equivalent depending your operating system (check the README for more informations).

Then, open the File > User preferences and go to the Addons tab. Search for Three.js and enable the found plug-in. Now, you should be able to see a File > Export > Three.js option. On the opened tab, ensure that Face Materials checkbox is checked. Otherwise, you won’t have materials, and Three.js is going to refuse to import your mesh.

Once saved, your file should look like the following:

{
    "metadata": {
        "uvs": 0,
        "type": "Geometry",
        "normals": 31,
        "generator": "io_three",
        "materials": 6,
        "version": 3,
        "vertices": 200,
        "faces": 198
    },
    "vertices":[/* ... */],
    "uvs": [],
    "name": "CubeGeometry",
    "materials": [/* ... */],
    "normals":[/* ... */],
    "faces":[/* ... */]
}

All required data is here. The most important are vertices, faces, normals (to compute lighting correctly), and materials.

Importing Mesh From Blender in Three.js

Now we got our mesh into an understandable format, let’s import it in Three.js. Based on the last tutorial code, we just have to replace our initCube function by an initMesh one:

var mesh = null;
function initMesh() {
    var loader = new THREE.JSONLoader();
    loader.load('./marmelab-logo.json', function(geometry) {
        mesh = new THREE.Mesh(geometry);
        scene.add(mesh);
    });
}

Note that as you load a file dynamically, you can’t open your file directly with a browser. You have to use a Web server. On Linux, you can use for instance the Node.js http-server package.

npm install -g http-server
http-server .

Rotating a Mesh

Do not forget to modify the rotateCube function:

function rotateMesh() {
    if (!mesh) {
        return;
    }

    mesh.rotation.x -= SPEED * 2;
    mesh.rotation.y -= SPEED;
    mesh.rotation.z -= SPEED * 3;
}

As you can see, working with a mesh is exactly the same as working with a primitive. We just check that our mesh is loaded to avoid a warning. Indeed, the loading function is an asynchronous one and then, the rendering loop may start before our model is in memory. A cleaner way to deal with it would be to start rendering only when model is loaded, but let’s keep it simple for this tutorial.

If your refresh your browser, you should now see a wireframed rotating marmelab logo. Yet, if you look deeper, you may see a graphical glitch:

Marmelab rotation logo's glitch

It seems some edges are broken. No mesh has been hurt during this animation, I swear. It is just a concrete example of the zFardistance from this previous post schema:

Perspective camera in WebGL

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

The value provided to the camera is not enough. So, we got two solutions: either increase the camera maximum length vision, or reduce the size of our mesh. Let choose the latter. Modify the initMesh method adding this line in the callback:

mesh.scale.x = mesh.scale.y = mesh.scale.z = 0.75;

This way, we reduce the size of our rotation logo by 25%. The glitch should have disappeared.

Changing Rotation Center Position

Rotation center is currently located at the bottom of one of the M branch. It would be far better if it occurred at the common point of all cubes. To do so, we have to translate the rotation origin, using transformation matrices. Sounds complicated? Fortunately, Three.js simplifies a lot our work:

loader.load('./marmelab-logo.json', function(geometry) {
    mesh = new THREE.Mesh(geometry);
    mesh.scale.x = mesh.scale.y = mesh.scale.z = 0.75;
    mesh.translation = THREE.GeometryUtils.center(geometry);
    scene.add(mesh);
});

All the magic happens on the mesh.translation line. We retrieve the center of our mesh, thanks to the GeometryUtils.center, and then translate it accordingly to make it rotate on its center.

Loading Materials

Our Blender file contains several materials in order to colorize different faces. So, let’s add these materials to our mesh to get rid of this wireframe display. Materials are also loaded through the loader.load method. You just have to add a second argument materials to the callback function:

loader.load('./marmelab-logo.json', function(geometry, materials) {
    mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
    // ...
});

Do not forget to pass materials to the THREE.MeshFaceMaterial function, otherwise you would get the following error:

Cannot read property ‘uniforms’ of undefined

Let There Be Light

We don’t have wireframes anymore, but our textures are fully black. This is due to a lack of light on our scene.

Three.js mesh without lights

So, let’s create a new initLights method and let’s call it in our init function:

function initLights() {
    var light = new THREE.AmbientLight(0xffffff);
    scene.add(light);
}

We added here a white AmbientLight. This kind of light is applied everywhere, so you don’t have to worry about the light position. As we are going to see lights in more details in another post, I won’t cover it for the moment.

Woohoo! We now have a nice looking marmelab logo. As usual, demonstration and source code are both available on GitHub.

 

[출처] https://www.jonathan-petitcolas.com/2015/07/27/importing-blender-modelized-mesh-in-threejs.html

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
54 javascript : js Array에서 한 원소 삭제 : JavaScript: Remove Element from an Array 졸리운_곰 2018.05.24 323
53 [자바스크립트] 동일한 단어를 문자열에서 찾기, match() 함수 file 졸리운_곰 2018.05.24 346
52 Javascript 함수 생성 2가지 방법의 차이점 file 졸리운_곰 2018.05.24 498
51 React 시작하기 [javascript] 졸리운_곰 2018.05.20 509
50 javascript 에서 큐, 스택, 트리 졸리운_곰 2018.02.27 513
49 CKEditor. Plugin 직접 만들기. 예: Cy-GistInsert file 졸리운_곰 2018.02.21 459
48 템플릿 엔진을 벗어나고 싶은 이유, React 와 Angular 2 사이의 갈등 중간 정리 졸리운_곰 2017.09.26 1354
47 [CSS 기초] DIV 태그를 이용하여 프레임 나누기 file 졸리운_곰 2017.08.25 496
46 jQuery 스타일 & 속성 다루기 file 졸리운_곰 2017.08.25 598
45 Cross-origin resource sharing file 졸리운_곰 2017.08.05 403
44 HTTP 접근 제어 (CORS) 졸리운_곰 2017.08.05 290
43 자바스크립트 문자열 비교 예제; 대소 문자 구분/구분 없이 졸리운_곰 2017.07.22 1286
42 [javascript] hashtable 같은 key=value 예제 졸리운_곰 2017.07.22 484
41 Three.js-Object-Rotation-with-Quaternion file 졸리운_곰 2017.07.08 435
40 Javascript [자바스크립트] 변수 선언과 유효범위 졸리운_곰 2017.07.08 583
39 remove-innerhtml-from-div 태그 안의 html코드 삭제 졸리운_곰 2017.07.08 633
38 HTML5 동영상 임베딩 졸리운_곰 2017.06.18 421
37 Javascript 문자열을 실수(부동소수점) 변수로 변환 가을의곰 2017.06.10 518
36 HTML div 왼쪽, 오른쪽 배치 가을의곰 2017.06.10 493
35 HTML DIV tag: 테두리 너비 지정하는 방법 - WIDTH : 픽셀(px) 또는 퍼센트(%) file 가을의곰 2017.06.10 827
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED