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

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
60 Is there a limit of vertices in WebGL? 웹지엘의 제약사항 졸리운_곰 2017.08.16 553
59 JavaScript Performance Monitor file 졸리운_곰 2017.08.16 371
58 Monitor Rendering Performance Within Three.js file 졸리운_곰 2017.08.16 541
57 List of WebGL frameworks 졸리운_곰 2017.08.16 499
56 From Unity to Three.js file 졸리운_곰 2017.08.16 1750
55 Collada dae to three.js json convertor sample file 졸리운_곰 2017.08.16 579
54 THREE.WebGLShader: Shader couldn't compile - Chrome Version 44.0.2403.125 #6929 file 졸리운_곰 2017.08.10 554
53 Uniforms types 졸리운_곰 2017.08.10 547
52 Custom shaders with Three.JS: Uniforms, textures and lighting file 졸리운_곰 2017.08.10 699
51 WebGL and ThreeJS Using Blender Models file 졸리운_곰 2017.08.05 355
» Importing a Modeled Mesh From Blender to Three.js file 졸리운_곰 2017.08.05 458
49 Using SketchUp Models OrcaXS edited this page on 27 Apr · 7 revisions 졸리운_곰 2017.08.05 459
48 Three.js Loading .mtl and .obj - object stays white file 졸리운_곰 2017.08.05 541
47 [three.js] How to Build a First Person Shooter in the Browser with Three.js and WebGL/HTML5 Canvas file 졸리운_곰 2017.07.22 534
46 [three.js] WebGLRenderer 졸리운_곰 2017.07.22 490
45 Clone an Object3D model from a Collada load call 졸리운_곰 2017.07.22 345
44 [three.js] Quaternion 4원수, 사원수 회전 졸리운_곰 2017.07.08 919
43 COLLADA, TinyXML, and OpenGL file 졸리운_곰 2017.07.06 502
42 [github][gist] Mouse-Picking Collada Models with THREE.js file 졸리운_곰 2017.07.06 584
41 Mouse-Picking Collada Models with three.js, Part II file 졸리운_곰 2017.07.06 338
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED