THREEJS - 获取场景中模型数据

在一些场景中,我们需要展示场景内的模型数据,如模型的数量、面片数以及顶点数等,下面给大家提供的就是对应的统计函数,在场景加载结束后,传入对应的scene即可:

/**
 * 获取场景内模型数量、顶点数及面片数
 * @param {*} view :需要计算的场景视图即scene
 */
function getSceneModelFaceNum(view) {
    let scene = view;
    let objects = 0; // 场景模型对象
    let vertices = 0; //模型顶点
    let triangles = 0; // 模型面片

    for (let index = 0; index < scene.children.length; index++) {
        let object = scene.children[index];
        object.traverseVisible(function (object) {
            objects++;
            if (object instanceof THREE.Mesh) {
                let geometry = object.geometry;
                if (geometry instanceof THREE.Geometry) {
                    vertices += geometry.vertices.length;
                    triangles += geometry.faces.length;
                } else if (geometry instanceof THREE.BufferGeometry && geometry.attributes.position) {
                    vertices += geometry.attributes.position.count;
                    if (geometry.index !== null) {
                        triangles += geometry.index.count / 3;
                    } else {
                        triangles += geometry.attributes.position.count / 3;
                    }
                }
            }
        });
    }
    console.log('模型对象数量: ' + objects, '模型顶点数: ' + vertices, '模型面片数: ' + triangles);
}

你可能感兴趣的:(THREEJS,three.js,javascript,canvas)