开发这个功能的原因:
1、由于3d建模师使用的是3dsmax建模,所以有些材质转换为gltf、glb后材质参数会丢失。比如最常见的就是对象的金属度、粗糙度这俩材质需要代码里重新调整。
2、基于模型我们可能添加一些其他对象,比如为模型增加线框等。如果在每次加载模型后再进行添加线框程序,那么加载模型会变得比较慢。
总结:通过导出我们可以将运行满意的模型导出去,这样再次加载进来就会节省很多运算,并且加载速度也会变快!
效果:加载速度很快(1秒左右),之前在加载模型后开始运行创建线框的程序,但是加载渲染速度比较慢(大约3秒)
效果:
核心代码:
import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter.js";
/**
* 将场景对象导出为glb或者gltf格式
* 使用方法:this.exportGltf(model.gltf.scene,'glb',model.gltf.animations)
* @param {THREE.Object3D} model 场景对象
* @param {string} type 默认为glb,可以选择gltf导出或glb导出
* @param {Array} modelAnimation {AnimationClip,...} 动画切片数组对象
*/
function exportGltf(
model = model,
type = 'glb',
modelAnimation = animations
) {
const exporter = new GLTFExporter();
const options = {
trs: true, // 是否保留位置、旋转、缩放信息
animations: modelAnimation, // 导出的动画
binary: type == 'glb' ? true : false, // 是否以二进制格式输出
embedImages: true,//是否嵌入贴图
onlyVisible: true, //是否只导出可见物体
forcePowerOfTwoTextures: true,
includeCustomMaterials: true, //指定是否包含自定义材质
includeCustomAttributes: true, // 指定是否包含自定义属性
includeCustomTextures: true, // 指定是否包含自定义纹理
includeCustomSamplers: true, // 指定是否包含自定义采样器
includeCustomImages: true, // 指定是否包含自定义图像
includeCustomTechniques: true, // 指定是否包含自定义技术
includeCustomMaterialsCommon: true, //指定是否包含自定义 MaterialsCommon
includeCustomMeshes: true,//指定是否包含自定义网格
includeCustomSkins: true, //指定是否包含自定义皮肤
includeCustomNodes: true, // 指定是否包含自定义节点
includeCustomGeometries: true, //指定是否包含自定义几何体
includeCustomPrograms: true, // 指定是否包含自定义程序
includeCustomShaders: true, //指定是否包含自定义着色器
includeCustomExtensions: true, //指定是否包含自定义扩展。如果设置为true,则会包含在导出中定义的自定义GLTF扩展
}
exporter.parse(model, function (result) {
console.log(result)
if (result instanceof ArrayBuffer) {
// 将结果保存为GLB二进制文件
saveArrayBuffer(result, `${new Date().toLocaleString()}.glb`);
} else {
// 将结果保存为GLTF JSON文件
saveString(JSON.stringify(result), `${new Date().toLocaleString()}.gltf`);
}
function saveArrayBuffer(buffer, filename) {
// 将二进制数据保存为文件
const blob = new Blob([buffer], { type: 'application/octet-stream' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
URL.revokeObjectURL(url);
console.log('导出成功');
}
function saveString(text, filename) {
// 将字符串数据保存为文件
const blob = new Blob([text], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
URL.revokeObjectURL(url);
console.log('导出成功');
}
}, (err) => {
console.error(err);
}, options);
}
https://zhuanlan.zhihu.com/p/657534389http://Three.js 实现导出模型文件(.glb,.gltf)功能 GLTFExporter