使用 Three.js 启用平滑着色 [英] Enable smooth shading with Three.js

查看:49
本文介绍了使用 Three.js 启用平滑着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Three.js 的 MTL 和 OBJ 文件渲染一个带有纹理的对象.我的代码在这里有效,但我的模型显示为平面阴影.如何启用平滑着色?

I'm rendering an object with textures using MTL and OBJ files with Three.js. My code here works but my model is displayed as flat shaded. How do I enable smooth shading?

var scene = new THREE.Scene();  
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath('assets/');
mtlLoader.setBaseUrl('assets/');
mtlLoader.load('asset.mtl', function(materials) {

    materials.preload();

    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials(materials);
    objLoader.setPath('assets/');
    objLoader.load('asset.obj', function(object) {

       //
       // This solved my problem
       //
       object.traverse(function(child) {
           if(child instanceof THREE.Mesh)
           {
              child.material.shading = THREE.SmoothShading;
           }
       });
       //
       //

       scene.add(object);
    });
});

我根据接受的答案使用解决我的问题的解决方案更新了我的代码.

I updated my code with a solution that fixed my problem based on the accepted answer.

推荐答案

这可能是我现在能想到的两件事之一.

It could be one of two things that I can think of right now.

可能是材质设置为FlatShading.在这种情况下,只需以某种方式检索对象并使用 object.material.shading = THREE.SmoothShading; 来修复.

It could be that the material is set to FlatShading. In this case just somehow retrieve the object and use object.material.shading = THREE.SmoothShading; to fix.

如果这没有改变它,则对象可能包含逐顶点法线(意味着每个三角形的每个顶点都有一个法线附加到它)并且每个三角形的所有法线都指向相同的方向.这个最好在3d编辑过程中解决,不过你也可以在three.js中重新计算法线:

If that doesn't change it, it's possible that the object contains per-vertex-normals (meaning that every vertex of every triangle has a normal attached to it) and that all normals for each triangle point in the same direction. This is something that should better be solved in the 3d-editing process, but you can also re-compute the normals in three.js:

object.geometry.computeVertexNormals(true);

这应该[1]重新计算光滑表面的法线.但是,它仅适用于常规几何图形和索引缓冲区几何图形(或者,反过来说:如果几何图形没有有关被重用于相邻面的顶点的信息,它将不起作用)

This should [1] recompute the normals for smooth surfaces. However, it will only work for regular Geometries and Indexed BufferGeometries (or, to put it the other way around: it won't work if the geometry doesn't have information about vertices being reused for adjacent faces)

[1]:我没有亲自测试,只是按照我刚刚在代码中阅读的内容进行操作

这篇关于使用 Three.js 启用平滑着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆