使用Three.js启用平滑着色 [英] Enable smooth shading with 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] 重新计算光滑曲面的法线。但是,它只适用于常规Geometries和Indexed BufferGeometries(或者,换句话说:如果几何体没有关于顶点被重用于相邻面的信息,它将无法工作)
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屋!