在 Mate-Engine 中使用 UniGLTF 2.0 完成 glTF 材质导入导出:PBR、UniUnlit 与 URP 全面指南
在 Mate-Engine 中使用 UniGLTF 2.0 完成 glTF 材质导入导出:PBR、UniUnlit 与 URP 全面指南
本文以
Assets/MATE ENGINE - Packages/UniGLTF/README.md为核心,系统讲解 UniGLTF 2.0 在 Unity 2019.4+ 环境下的 glTF-2.0 导入/导出能力,重点剖析其内置的材质转换体系:PBR(金属粗糙度)与 Unity Standard Shader 的相互转换、UniGLTF/UniUnlit无光照材质与KHR_materials_unlit的完整闭环,以及KHR_texture_transform的(部分)实现。结合仓库源码与测试用例,读者将掌握编辑器菜单导入导出流程、材质参数映射细节、顶点色支持边界与 URP 实验性支持的真实状况,并了解该组件如何在 Mate-Engine 中作为 VRM/glTF 资源管线的底层基石发挥作用。
UniGLTF 2.0 是什么
UniGLTF 是 VRM Consortium(vrm-c)维护的 glTF 2.0 导入/导出工具库,可运行于 Unity 编辑器和运行时(Runtime)两条路径。在 Mate-Engine 仓库中,它以独立包的形式存放在 Assets/MATE ENGINE - Packages/UniGLTF,并与同目录下的 VRM / VRM10 包协同,构成整个虚拟形象(Avatar)资源加载与导出体系的基础层。
仓库中该包的 package.json 声明了包名 com.vrmc.gltf、版本 0.128.3,描述为 "GLTF importer and exporter"(package.json);运行时版本常量则定义在 UniGLTFVersion.cs,当前为 2.64.3。README 明确其支持范围:
- Unity 版本:支持 2019.4 及以后版本;
- 能力:可在 Unity 编辑器和运行时中导入、导出 glTF-2.0 格式文件;
- 扩展实现:完整实现
KHR_materials_unlit;部分实现KHR_texture_transform; - 兼容性:可以导入 KhronosGroup 官方 glTF-Sample-Models 中的绝大多数 2.0 样例模型(README 原文所述,仓库场景与测试可进一步佐证)。
从源码结构看,UniGLTF 包内分为 Runtime(UniGLTF、UniHumanoid、UniJSON、SpringBoneJobs、MeshUtility、Utils 等子模块)、Editor(导入菜单、导出窗口、MeshUtility、生成器等)与 Tests 三大区域,材质处理集中在 Runtime/UniGLTF/IO/MaterialIO,下文将围绕这些源码逐步展开。
材质处理:PBR(金属粗糙度)与 Unity Standard Shader
转换目标
README 的 Material → PBR 一节给出了两个核心承诺:
- 尽可能在 glTF PBR 与 Unity Standard Shader 之间进行转换;
- 处理 metal-roughness(金属粗糙度)与 occlusion(环境光遮蔽)在 RGBA 通道上的不兼容问题。
导入方向:glTF → Unity Standard Shader
导入侧的核心实现在 BuiltInGltfPbrMaterialImporter.cs,其目标 Shader 是 Shader.Find("Standard")。源码中的注释完整列出了被映射的 Standard Shader 属性清单:_Color、_MainTex、_Cutoff、_Glossiness、_Metallic、_MetallicGlossMap、_BumpScale、_BumpMap、_Parallax、_ParallaxMap、_OcclusionStrength、_OcclusionMap、_EmissionColor、_EmissionMap、_DetailMask、_DetailAlbedoMap、_DetailNormalMapScale、_DetailNormalMap、_UVSec、_Mode、_SrcBlend、_DstBlend、_ZWrite。
导入时的关键映射逻辑(同一文件 TryCreateParam):
| glTF 字段 | Unity Standard 属性 | 处理说明 |
|---|---|---|
pbrMetallicRoughness.baseColorFactor |
_Color |
经 ImportLinearBaseColorFactor 读取线性基色因子并转为 gamma 空间色值 |
pbrMetallicRoughness.baseColorTexture |
_MainTex |
以 sRGB 纹理导入 |
pbrMetallicRoughness.metallicRoughnessTexture |
_MetallicGlossMap |
同时启用 _METALLICGLOSSMAP 关键字,并将 _Metallic 与 _GlossMapScale 硬编码为 1.0(源码注释引用了 UniVRM issue #212) |
pbrMetallicRoughness.metallicFactor |
_Metallic |
仅在无 metal-roughness 贴图时使用 |
pbrMetallicRoughness.roughnessFactor |
_Glossiness |
按 _Glossiness = 1.0 - roughnessFactor 转换(光滑度 = 1 − 粗糙度) |
normalTexture |
_BumpMap、_BumpScale |
启用 _NORMALMAP 关键字,法线缩放取 normalTexture.scale |
occlusionTexture |
_OcclusionMap、_OcclusionStrength |
遮蔽强度取 occlusionTexture.strength |
emissiveFactor / emissiveTexture |
_EmissionColor / _EmissionMap |
启用 _EMISSION 并清除 EmissiveIsBlack 标志;发射色同样转为 gamma 空间 |
alphaMode |
_Mode 与混合状态 |
见下文透明度模式映射 |
alphaMode 映射(同一源码末尾的 Action<Material>):
OPAQUE→_Mode = Opaque,关闭所有 alpha 关键字,renderQueue = -1(默认队列);MASK→_Mode = Cutout,RenderType = TransparentCutout,SrcBlend = One、DstBlend = Zero、ZWrite = 1,启用_ALPHATEST_ON,_Cutoff取自alphaCutoff,renderQueue = 2450;BLEND→_Mode = Fade,RenderType = Transparent,SrcBlend = SrcAlpha、DstBlend = OneMinusSrcAlpha、ZWrite = 0,启用_ALPHABLEND_ON,renderQueue = 3000。
导出方向:Unity Standard Shader → glTF
导出侧由 BuiltInGltfMaterialExporter.cs 分派。它维护了一张支持列表:
public static readonly string[] SupportedShaderNames =
{
BuiltInStandardMaterialExporter.TargetShaderName, // Standard
BuiltInUniUnlitMaterialExporter.TargetShaderName, // UniGLTF/UniUnlit
"Unlit/Color",
"Unlit/Texture",
"Unlit/Transparent",
"Unlit/Transparent Cutout",
};
对于不在支持列表中的材质,会记录 Material {name} fallbacks. 日志并回退到 Fallback 导出器。材质导出遵循 glTF 规范采用金属粗糙度工作流:光泽度(_Glossiness)在导出时按 1 - Glossiness 反推为 roughnessFactor。
通道不兼容问题如何解决
README 提到的 "metal roughness 和 occlusion RGBA 通道不兼容" 是指:glTF 规定 metal-roughness 贴图的 B 通道 存放金属度、G 通道 存放粗糙度;而 occlusion 贴图只使用 R 通道。Unity Standard Shader 的 _MetallicGlossMap 使用 G 通道金属、A 通道光泽度,_OcclusionMap 使用 R 通道——两套布局并不一致。
UniGLTF 通过着色器重排方案处理:仓库 Resources/UniGLTF 下提供了 StandardMapImporter.shader(导入时重组)与 StandardMapExporter.shader(导出时重组),在纹理采样层面完成通道搬运。GltfPbrTextureImporter.TryStandardTexture 会把 metallicRoughnessTexture 与 occlusionTexture 合并到同一张 Standard Map 描述中(参见 GltfTextureImporter.cs 的 TryCreateStandard),由 StandardMapImporter shader 在运行时重建正确通道。测试用例 EditorTextureSerializerTests.cs 中亦注释 "R channel is occlusion in glTF spec",印证了这一约定。
Unlit 材质:UniGLTF/UniUnlit 与 KHR_materials_unlit
导入规则
README 明确了 Unlit 相关约定:
- 导入:使用 UniGLTF 自己的
UniGLTF/UniUnlitshader; - 导出:可以导出
UniGLTF/UniUnlit以及 Unity 内置的 unlit 材质; - 顶点色:只有
UniGLTF/UniUnlit支持顶点色。
导入实现:检测 KHR_materials_unlit
glTF 材质通过 KHR_materials_unlit 扩展标记为无光照。该扩展的数据模型在 KHR_materials_unlit.cs:IsEnable 检查材质 extensions 中是否存在键 KHR_materials_unlit(扩展内容为空对象 {}),CreateDefault 会生成 baseColorFactor = (1,1,1,1)、roughnessFactor = 0.9、metallicFactor = 0 的默认 PBR 基底并挂上扩展标记。
导入主流程在 BuiltInGltfUnlitMaterialImporter.cs:
- 若
glTF_KHR_materials_unlit.IsEnable(src)为 false,直接返回; baseColorFactor转为_Color(gamma 空间);baseColorTexture以 sRGB 导入为_MainTex,并应用KHR_texture_transform的 offset/scale(GltfTextureImporter.GetTextureOffsetAndScale);- 根据
alphaMode调用UniUnlitUtil.SetRenderMode:OPAQUE→Opaque、BLEND→Transparent、MASK→Cutout(并写入alphaCutoff到_Cutoff); doubleSided为 true 时SetCullMode(Off),否则SetCullMode(Back);- 若网格带顶点色(
data.MaterialHasVertexColor),SetVColBlendMode(Multiply); - 最终调用
UniUnlitUtil.ValidateProperties(material, true)统一校正混合状态与关键字。
UniUnlit shader 的属性与渲染模式
Shader 定义在 UniUnlit.shader,公开属性包括:
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
_MainTex |
2D | 白色 | 主纹理(RGBA) |
_Color |
COLOR | (1,1,1,1) | 主颜色 |
_Cutoff |
Range(0,1) | 0.5 | Alpha 裁剪阈值(仅 Cutout 模式) |
_BlendMode |
Float(隐藏) | 0 | 渲染模式:0 Opaque / 1 Cutout / 2 Transparent |
_CullMode |
Float(隐藏) | 2 | 剔除模式:0 Off / 2 Back |
_VColBlendMode |
Float(隐藏) | 0 | 顶点色混合:0 None / 1 Multiply |
_SrcBlend/_DstBlend/_ZWrite |
Float(隐藏) | 1/0/1 | 混合与深度写入状态 |
对应的枚举与工具方法定义在 UniUnlitUtil.cs:UniUnlitRenderMode(Opaque=0、Cutout=1、Transparent=2)、UniUnlitCullMode(Off=0、Back=2,Front 被注释掉)、UniUnlitVertexColorBlendOp(None=0、Multiply=1)。ValidateProperties 会根据模式设置正确的 RenderType 标签、混合系数、_ZWrite 与关键字(_ALPHATEST_ON、_ALPHABLEND_ON、_VERTEXCOL_MUL):
- Opaque:
RenderType=Opaque,SrcBlend=One、DstBlend=Zero、ZWrite=1,renderQueue 保持 -1; - Cutout:
RenderType=TransparentCutout,ZWrite=1,启用_ALPHATEST_ON,用户手动切换时 renderQueue 设为 AlphaTest(2450); - Transparent:
RenderType=Transparent,SrcBlend=SrcAlpha、DstBlend=OneMinusSrcAlpha、ZWrite=0,启用_ALPHABLEND_ON,用户手动切换时 renderQueue 设为 Transparent(3000)。
Shader 的片元函数逻辑:col = tex2D(_MainTex, uv) * _Color;启用 _VERTEXCOL_MUL 时再乘顶点色;启用 _ALPHATEST_ON 时执行 clip(col.a - _Cutoff);Opaque 模式下强制 col.a = 1.0;最后应用雾效。这正好印证 README 中"只有 UniGLTF/UniUnlit 支持顶点色"的表述——顶点色数据仅在 _VERTEXCOL_MUL 关键字启用时才会被 Shader 读取。
编辑器侧由 UniUnlitEditor.cs(自定义 ShaderGUI)提供 Inspector 面板,包含 Rendering(Rendering Type、Cull Mode、Cutoff)、Color(Main Tex + Color、Texture Offset/Scale、Vertex Color Blend Mode)、Options(GI、Render Queue)三个分组。当从 Standard Shader 切换到 UniUnlit 时,AssignNewShaderToMaterial 会读取旧材质的 _Mode 并映射到对应渲染模式。
导出实现:UniUnlit → KHR_materials_unlit
builtInUniUnlitMaterialExporter.cs(源码文件名为 BuiltInUniUnlitMaterialExporter.cs)只处理 shader 名为 UniGLTF/UniUnlit 的材质:
- 渲染模式映射:Opaque→
alphaMode=OPAQUE;Cutout→alphaMode=MASK并写出alphaCutoff = _Cutoff;Transparent→alphaMode=BLEND; - 剔除映射:CullMode Off→
doubleSided=true;Back→doubleSided=false; _Color从 sRGB 转线性写入baseColorFactor;_MainTex注册为 sRGB 纹理写入baseColorTexture(非 Opaque 时按预乘 alpha 处理),并通过GltfMaterialExportUtils.ExportTextureTransform写出纹理变换。
Unity 内置 Unlit/Color、Unlit/Texture、Unlit/Transparent、Unlit/Transparent Cutout 则由 BuiltInGenericUnlitMaterialExporter 分别按 OPAQUE/BLEND/MASK 导出(分派逻辑见 BuiltInGltfMaterialExporter.cs)。
测试验证
Tests/UniGLTF/MaterialTests.cs 覆盖了:
glTF_KHR_materials_unlit_Test:验证扩展的序列化/反序列化与IsEnable判定(ForTest()构造扩展后IsEnable返回 true);UnlitShaderImportTest:枚举 OPAQUE/BLEND/MASK × Color/Texture 的各种组合,断言所有带KHR_materials_unlit的材质均可被识别为 unlit;TextureTransformTest:用offset=(0.3, 0.2)、scale=(0.5, 0.6)的材质导出,断言生成的KHR_texture_transform扩展值一致;MaterialExportTest:验证 emissive 颜色从 gamma 到线性的导出换算。
KHR_texture_transform:部分实现的范围
README 注明 KHR_texture_transform 为部分实现。仓库中的数据结构定义在 KHR_texture_transform.cs,含四个字段:
| 字段 | 类型 | 默认值 | glTF 约束 |
|---|---|---|---|
offset |
float[2] | (0, 0) | 元素个数必须为 2 |
rotation |
float | 0 | 弧度制旋转 |
scale |
float[2] | (1, 1) | 元素个数必须为 2 |
texCoord |
int | — | 必须 ≥ 0 |
序列化路径 Serialize(glTFTextureInfo, offset, scale) 只写入 offset 与 scale;反序列化路径 Deserialize 虽能解析 rotation 与 texCoord,但在未知键时抛出 NotImplementedException。
导入时 GltfTextureImporter.cs 的 GetTextureOffsetAndScale 读取扩展并调用 TextureTransform.VerticalFlipScaleOffset 做 Y 轴翻转校正(Unity UV 与 glTF 纹理坐标方向差异),最终作为 TextureDescriptor 的 offset/scale 传入,运行时表现为 Material 的 _MainTex_ST(Tiling/Offset)。导出时 GltfMaterialExportUtils.cs 从 src.GetTextureOffset/GetTextureScale 反向写出扩展。
从源码可以推断,"部分实现"的边界在于:offset 与 scale 的导入导出是完整闭环(并有测试佐证),而 rotation 与 texCoord 虽可反序列化但不在常用转换路径中使用,实际纹理变换以平铺/偏移为主。
URP 支持:仅导入的实验性功能
README 对 URP 的支持描述非常克制:import only,experimental。
仓库中 URP 相关代码位于 MaterialIO/URP,包含 URP 侧的导入与导出实现。导入侧使用 URP Lit/Unlit shader 生成材质描述(URP 的 Lit 材质导入逻辑与 Built-in 的 Standard 导入类似,但目标 shader 为 Universal Render Pipeline/Lit);导出侧 UrpGltfMaterialExporter.cs 依次尝试 UrpLit、UrpUnlit、UrpUniUnlit 导出器,失败则回退到 Fallback。
需要说明的边界:
- README 仅声明"导入"可用且为实验性质,导出路径在源码中存在但不受 README 承诺约束;
- 在 Mate-Engine 主场景中,项目的渲染管线配置(见 Settings/PC_Renderer.asset 等 URP 资产)意味着 URP 分支是仓库实际使用的路径之一;但从该包文档口径看,官方推荐路径仍是 Built-in RP 下使用 Standard / UniUnlit;
- 实际使用时应先在小规模资源上验证 URP 导入效果,再决定是否全量接入。
编辑器实操:导入与导出 glTF
菜单入口
UniGLTF 通过 Unity 菜单提供编辑器工作流,入口定义在 TopMenu.cs,统一挂在 UniGLTF 菜单下:
UniGLTF/Version: UniGLTF-2.64.3:版本信息;UniGLTF/Export glTF...:打开导出窗口(GltfExportWindow.MENU_NAME);UniGLTF/Import glTF... (*.gltf|*.glb|*.zip):打开导入对话框;UniGLTF/MeshUtility:网格工具(骨骼网格擦除、网格整合等)。
导入流程
导入入口 GltfImportMenu.ImportGltfFileToGameObject(GltfImportMenu.cs)支持 .gltf、.glb、.zip 三种格式(Windows 编辑器下文件选择器可同时过滤三种扩展名,macOS/Linux 下因平台限制只允许 .glb,见 UniGltfEditorDialog.cs):
- Play 模式:解析文件 →
new ImporterContext(data)→context.Load()→ 加载到场景并选中生成的 GameObject; - 非 Play 模式:禁止从 Assets 目录内导入(日志警告
disallow import from folder under the Assets)→ 选择保存路径 → 复制文件(.gltf会连带复制关联的 buffer 与 image 资源文件)→ 作为 Prefab 资产导入并选中。
运行时导入则由 ImporterContext 配合 AwaitCaller(RuntimeOnlyAwaitCaller 等,见 Runtime/UniGLTF/IO/AwaitCaller)支持异步加载,用于 Play 模式下动态加载 glTF。
导出流程
导出由 gltfExporter 驱动(gltfExporter.cs),核心步骤:
Prepare(GameObject):对目标实例化副本,通过ReverseRecursive(m_settings.InverseAxis.Create())把 Unity 左手系转换到 glTF 右手系(注意 Z 轴翻转),单个无子物体的根会临时套一层 dummy parent;Export():按FreezeMesh设置决定是否用BoneNormalizer.NormalizeHierarchyFreezeMesh烘焙旋转/缩放进网格 → 遍历节点 → 导出材质与纹理(_gltf.materials = Materials.Select(x => m_materialExporter.ExportMaterial(...)))→ 导出网格(DivideVertexBuffer决定共用/分割顶点缓冲)与 BlendShape 索引映射 → 导出节点/蒙皮(inverseBindMatrices、joints、skeleton)→ 可选动画导出 → 纹理统一注册写出。
导出窗口与设置项集中在 Editor/UniGLTF 与 GltfExportSettings.cs,其中包括坐标轴反转(InverseAxis)、顶点缓冲划分(DivideVertexBuffer)、网格烘焙(FreezeMesh)等选项,实际使用时可依据目标 glTF 消费端要求调整。
在 Mate-Engine 中的实际定位
Mate-Engine 仓库将 UniGLTF 与 VRM / VRM10 包放在同一目录(MATE ENGINE - Packages),说明其虚拟形象管线依赖 UniGLTF 提供的 glTF 基础能力:自定义 VRM 模型加载(VRMLoader)、模型导出与 SDK 工具链(MEModelExporter.cs、ModExporterWindow.cs)等,最终都落在 glTF 级别的网格、材质、纹理、蒙皮与动画序列化之上。本文所讲的材质转换规则,正是理解这些上层工具导出结果(如 .me 与 glTF/VRM 资源)的关键。
许可与分发
UniGLTF 以 MIT 协议开源,许可文本见仓库内 LICENSE.md(README 中对应的 License 链接在仓库中即此文件)。README 中提供的下载地址指向 UniVRM 的 Releases 页面,读者可按需获取更新版本;仓库内当前包含的即是 Mate-Engine 实际依赖并已验证的版本(0.128.3 包 / 2.64.3 运行时版本)。
关键文件速查
- 包元信息:package.json
- 版本常量:UniGLTFVersion.cs
- PBR 导入(Built-in RP):BuiltInGltfPbrMaterialImporter.cs
- Unlit 导入:BuiltInGltfUnlitMaterialImporter.cs
- UniUnlit shader:UniUnlit.shader
- UniUnlit 工具类:UniUnlitUtil.cs
- UniUnlit 编辑器:UniUnlitEditor.cs
- 材质导出分派:BuiltInGltfMaterialExporter.cs
- UniUnlit 导出:BuiltInUniUnlitMaterialExporter.cs
- 扩展定义:KHR_materials_unlit.cs、KHR_texture_transform.cs
- 纹理导入:GltfTextureImporter.cs
- 导入/导出菜单:GltfImportMenu.cs、TopMenu.cs
- 导出主流程:gltfExporter.cs
- 材质相关测试:MaterialTests.cs