【Threejs-sdk】使用 mogl.js 快速匹配烘焙.
使用 mogl.js:模型烘焙(Baked)
github 欢迎加开源
本教程基于示例 packages/examples/src/views/examples/ModelBake.vue,演示如何为 GLB/GLTF/FBX 模型应用烘焙贴图(baked texture),并在运行时切换模式、强度与 UV 通道。
你将学到
- 使用 ModelLoader 的 bakedLighting 配置一键应用烘焙光照
- 维护“模型网格名 → 贴图路径”的映射表
- 两种应用模式:map(替换漫反射)与 lightMap(光照贴图)
- 调整光照强度与 UV 通道(UV1/UV2)
- 运行时应用/更新/移除烘焙光照与事件监听
核心概念速览
- bakedLighting: { enabled, textureMapping, mode, intensity, autoApply, channel }
- textureMapping:以 Mesh 名称为键,指向对应的烘焙贴图路径
- mode:‘map’ 替换漫反射;‘lightMap’ 使用光照贴图(推荐,保留材质颜色细节)
- channel:UV 通道索引(0=UV1,1=UV2,通常烘焙贴图使用 UV2)
1. 初始化场景与组件
import { Scene } from '@w3d/core';
import { ModelLoader, HDRLoader } from '@w3d/componenjs';const scene = new Scene(container, {renderer: { antialias: true, outputColorSpace: 'srgb' },camera: { fov: 45, position: [10, 8, 15], lookAt: [0, 0, 0] }
});
scene.init();
scene.renderer.enableShadow(true);
scene.renderer.enableResize();scene.registerComponent('ModelLoader', ModelLoader);
scene.registerComponent('HDRLoader', HDRLoader);
2. 可选:加载 HDR 环境
await scene.add('HDRLoader', {name: 'environment',url: '/textures/blouberg_sunrise_2_1k.hdr',asEnvironment: true,asBackground: true,intensity: 1.0
});
3. 准备烘焙贴图映射表
const bakeTextureMapping = {Castle_Exterior: '/bake/room/Castle_Exterior.jpg',Towers_Doors_and_Windows: '/bake/room/Towers_Doors_and_Windows.jpg',Ground_and_Fountain: '/bake/room/Ground_and_Fountain.jpg',Castle_Interior: '/bake/room/Castle_Interior.jpg'
};
4. 加载模型并启用烘焙光照
const model = await scene.add('ModelLoader', {name: 'castle',url: '/models/room.glb', // 也支持 .gltf / .fbx(自动识别)casjshadow: true,receiveShadow: true,bakedLighting: {enabled: true,textureMapping: bakeTextureMapping,mode: 'lightMap', // 'map' 或 'lightMap' 或则 'bake'intensity: 1.0,autoApply: true,channel: 1 // UV2(推荐)}
});
5. 运行时控制
// 应用 / 更新
await model.applyBakedLighting(bakeTextureMapping, {mode: 'lightMap',intensity: 1.2,channel: 1
});// 仅调整强度(lightMap 模式)
model.updateBakedIntensity(1.5);// 移除烘焙光照(还原原材质)
model.removeBakedLighting();
6. 事件监听
model.on('bakedLightingApplied', (e) => {console.log('已应用烘焙光照,对象数:', e.appliedCount, '模式:', e.mode, '强度:', e.intensity);
});
model.on('bakedLightingRemoved', (e) => {console.log('已移除烘焙光照');
});
7. 多格式支持与注意事项
- ModelLoader 自动识别 GLB/GLTF/FBX,无需手动选择 Loader
- SDK 自动处理:材质克隆、flipY=false、色彩空间、UV 通道设置等
- 建议优先使用 UV2(channel=1)的 lightMap 模式,保留原材质配色,效果更自然
8. 启动与清理
scene.start();
scene.dispose();
提示/FAQ
- textureMapping 的键需与模型 Mesh 名称精确匹配
- 若仅部分 Mesh 有烘焙贴图,其余 Mesh 会维持原材质
- 大型模型建议异步加载并展示进度条