Three.js中如何将非索引BufferGeometry转换为索引BufferGeometry?
将非索引BufferGeometry转换为索引BufferGeometry(Three.js)
直接用Three.js官方提供的BufferGeometryUtils.mergeVertices()工具函数就能解决问题——它会自动检测并合并重复顶点,同时生成对应的索引缓冲区,把非索引几何转为索引几何,大幅减少顶点数量。
步骤示例:
引入工具类
确保项目中引入了BufferGeometryUtils:// ES6 模块化导入 import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js'; // 或通过CDN引入(非模块化场景) // <script src="https://cdn.jsdelivr.net/npm/three@latest/examples/js/utils/BufferGeometryUtils.js"></script>执行转换
假设你已经加载得到非索引的BufferGeometry,命名为nonIndexedGeometry:// 转换为索引BufferGeometry const indexedGeometry = BufferGeometryUtils.mergeVertices(nonIndexedGeometry); // 验证结果 console.log(indexedGeometry.index); // 存在索引缓冲区(不再为null) console.log('原非索引顶点数:', nonIndexedGeometry.attributes.position.count); console.log('转换后索引顶点数:', indexedGeometry.attributes.position.count);自定义顶点合并精度
函数默认用0.0001的精度判断顶点是否重复,如果你的场景对精度要求不同,可以传入第二个参数调整:// 示例:使用0.01的精度合并顶点 const indexedGeometry = BufferGeometryUtils.mergeVertices(nonIndexedGeometry, 0.01);
额外优化建议
你之前的导出流程可以调整:不用先转非索引,直接把几何转为索引后再导出,这样加载后的顶点数就和原几何一致了:
// 先将原几何转为索引格式 const indexedGeom = BufferGeometryUtils.mergeVertices(mesh.geometry); // 导出索引几何的JSON const geomJSON = indexedGeom.toJSON(); // 加载时直接解析 const loadedGeom = geometriesLoader.parse(geomJSON);
内容的提问来源于stack exchange,提问作者Gangula
相关产品推荐
相关产品推荐

