GLTF 校验器( TypeScript)
TypeScript 执行 GLTF/ GLB 验证与正式的 Khronos 验证器兼容.
目录
特征
- ✅ 完整的 GLTF 2.0 验证 - 验证所有核心GLTF规格
- ✅ GLB 支持 - 完整的二进制 GLTF (. glb) 文件验证
- ✅ 扩展支持 - 验证流行的 GLTF 扩展 :
- KHR 材料 pbr specular 光滑
- KHR 材料 脱落
- KHR 材料 干净的外套
- KHR 材料 传输
- KHR 材料 量
- KHR 材料 or
- KHR 材料 光谱
- KHR 材质 sheen
- KHR 材料 发送 强度
- KHR 材料 异常
- KHR 物质 异构
- KHR 物质 分散
- KHR 材料 变量
- KHR 灯光 平分
- KHR 动能 指针
- KHR 文字 变形
- KHR 纹理 basisu
- KHR mesh 量化
- EXT 文字 网络
- ✅ 详细错误报告 - 与JSON指针位置的综合验证信息
- ✅ 类型脚本支持 - 包括全部类型脚本定义
- ✅ 高性能 - 优化验证算法
- ✅ 可配置 - 自定义验证选项和严重程度
快速链接
- 📦 npm 软件包
- 🌐 现场直播 - 试试你的浏览器!
- 📚 API 文档
- 💡 实例
- 🐛 报告错误
- ✨ 请求特性
- 🤝 贡献指南
- 🔒 安全政策
- 📖 GLTF 2. 0 规格
- 🎯 原始 Khronos 验证器
安装
npm install @dcl/gltf-validator-ts
快速启动
基本用途
import { GLTFValidator } from '@dcl/gltf-validator-ts';
// Create validator with default options
const validator = new GLTFValidator({
maxIssues: 100,
ignoredIssues: [],
onlyIssues: [],
severityOverrides: {}
});
// Validate a GLTF file
const gltfData = {
"asset": {
"version": "2.0"
},
// ... your GLTF data
};
const result = await validator.validate(gltfData);
console.log(`Errors: ${result.issues.numErrors}`);
console.log(`Warnings: ${result.issues.numWarnings}`);
// Print all validation messages
result.issues.messages.forEach(message => {
console.log(`${message.code}: ${message.message} at ${message.pointer}`);
});
正在验证 GLB 文件
import { parseGLB } from '@dcl/gltf-validator-ts';
// Parse GLB binary data
const glbBuffer = new Uint8Array(/* your GLB file data */);
const parseResult = parseGLB(glbBuffer);
if (parseResult.gltf) {
const result = await validator.validate(parseResult.gltf, true, parseResult.resources);
console.log('GLB validation complete:', result);
}
高级配置
const validator = new GLTFValidator({
maxIssues: 50, // Limit number of issues reported
ignoredIssues: ['UNUSED_OBJECT'], // Ignore specific issue codes
onlyIssues: [], // Only report specific issue codes (empty = all)
severityOverrides: { // Override severity levels
'UNUSED_OBJECT': 0 // Make unused objects errors instead of info
},
externalResourceFunction: async (uri: string) => {
// Custom function to load external resources
const response = await fetch(uri);
return new Uint8Array(await response.arrayBuffer());
}
});
快速示例
用真实的 GLB 模型尝试包含的示例 :
# Run the built-in example
npm run example
# Or run the TypeScript version
npm run example:ts
这验证了一个样本模型,并显示了不同的验证方法、问题报告和模型分析.
使用验证结果
const result = await validator.validate(gltfData);
// Access different types of issues
console.log(`Found ${result.issues.numErrors} errors`);
console.log(`Found ${result.issues.numWarnings} warnings`);
console.log(`Found ${result.issues.numInfos} info messages`);
// Filter messages by severity
const errors = result.issues.messages.filter(msg => msg.severity === 0);
const warnings = result.issues.messages.filter(msg => msg.severity === 1);
// Group messages by code
const messagesByCode = result.issues.messages.reduce((acc, msg) => {
acc[msg.code] = acc[msg.code] || [];
acc[msg.code].push(msg);
return acc;
}, {} as Record<string, typeof result.issues.messages>);
API 参考
GLTF 读取器
GLTF/GLB 验证的主要验证器类.
构造器
new GLTFValidator(options: ValidatorOptions)
选项:
maxIssues: number- 报告的问题最多(0=无限制)ignoredIssues: string[]- 一系列可忽略的发行代码onlyIssues: string[]- 只报告这些发行代码(空=全部)severityOverrides: Record<string, Severity>- 超越特定代码的严重程度水平externalResourceFunction?: (uri: string) => Promise<Uint8Array>- 装载外部资源的职能
方法
验证( gltf, 是 GLB 吗 ?, 资源 ?)
验证 GLTF 对象.
参数:
gltf: GLTF- GLTF 对象验证isGLB?: boolean- 是否是 GLB 文件( 默认: 假)resources?: ResourceReference[]- GLB验证的外部资源
回返情况: Promise<{ issues: Issues }>
工具函数
parseGLB( 数据)
将 GLB 二进制数据分解为 GLTF 对象和资源 .
参数:
data: Uint8Array- GLB 二进制数据
回返情况: { gltf?: GLTF, resources: ResourceReference[], errors?: string[] }
验证代码
验证人报告各种有具体代码的问题:
出错代码 (Severity 0)
TYPE_MISMATCH- 属性有错误的数据类型UNRESOLVED_REFERENCE- 提及不存在的对象INVALID_VALUE- 属性值无效UNDEFINED_PROPERTY- 缺少所需财产BUFFER_MISSING_GLB_DATA- GLB 缓冲器缺少二进制数据- 还有...
警告代码( 严重性 1)
UNEXPECTED_PROPERTY- 这个地点没有预期到的财产BUFFER_GLB_CHUNK_TOO_BIG- GLB块有额外的垫子NODE_SKINNED_MESH_NON_ROOT- 皮肤网状不是根部- 还有...
信息代码( 严重性 2)
UNUSED_OBJECT- 对象被定义但未使用UNSUPPORTED_EXTENSION- 扩展不支持验证符- 还有...
支持的扩展
此校验器支持以下 GLTF 扩展的校验 :
- KHR 材料 pbr specular 光滑 - 替代材料工作流程
- KHR 材料 脱落 - 未读材料
- KHR 材料 干净的外套 - 干衣材料
- KHR 材料 传输 - 传送材料
- KHR 材料 量 - 体积材料
- KHR 材料 or - 折射指数
- KHR 材料 光谱 - 光谱工作流程
- KHR 材质 sheen - 谢恩材料
- KHR 材料 发送 强度 - 应急力量
- KHR 材料 异常 - 迷你材料
- KHR 物质 异构 - 异同位素材料
- KHR 物质 分散 - 物质扩散
- KHR 材料 变量 - 材料变体
- KHR 灯光 平分 - 点灯
- KHR 动能 指针 - 动画指针
- KHR 文字 变形 - 纹理转化
- KHR 纹理 basisu - 基础通用纹理
- KHR mesh 量化 - 网格量化
- EXT 文字 网络 - WebP纹理
发展
设置
git clone https://github.com/decentraland/gltf-validator-ts.git
cd gltf-validator-ts
npm install
脚本
npm run build # Build the project
npm run test # Run tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage
npm run lint # Lint the code
npm run lint:fix # Lint and auto-fix issues
npm run format # Format code with Prettier
npm run typecheck # Type check without emitting
实例
这个 examples/ 目录包含显示如何使用验证符的实用示例 :
基本模型验证
# Run the basic example with included GLB model
npm run example
# View example source code
cat examples/basic/validate-model.ts
基本的例子表明:
- 从磁盘上装入 GLB 文件
- 不同的验证办法(基本、习惯、严格)
- 处理错误和结果解释
- 模型信息提取
- 问题过滤和报告
创建自定义示例
见 examples/README.md 关于创建您自己的验证实例和将验证符纳入工作流程的细节.
浏览器兼容性
校验器兼容现代浏览器和节点.js环境:
节点.js
- 最小版本: 节点.js 18.0.0+
- 建议: 节点.js 20.x或以上
- 平台支持: 视窗、 macOS、 Linux
浏览器支持
- 克罗梅/埃奇页:1
- 火花: 88+版本 翻译:
- 萨法里页:1
- 歌剧页:1
网络套装
浏览器已准备好的捆绑可直接用于网络应用程序:
<script src="https://unpkg.com/@dcl/gltf-validator-ts/web/scripts/gltf-validator.js"></script>
<script>
// GLTFValidator is available as a global variable
const validator = new GLTFValidator.GLTFValidator({
maxIssues: 100
});
</script>
或者用那个 现场演示 在浏览器中验证模型而无需安装.
性能提示
优化战略
1. 限制问题报告
const validator = new GLTFValidator({
maxIssues: 50 // Stop after finding 50 issues
});
2. 过滤器问题类型
const validator = new GLTFValidator({
onlyIssues: ['TYPE_MISMATCH', 'UNRESOLVED_REFERENCE'], // Only critical errors
ignoredIssues: ['UNUSED_OBJECT', 'UNSUPPORTED_EXTENSION'] // Ignore non-critical
});
3.批次验证
当验证多个文件时, 重用验证符实例 :
const validator = new GLTFValidator({ maxIssues: 100 });
for (const file of files) {
const result = await validator.validate(file);
// Process results
}
4. 记忆管理
对于大型 GLB 文件,请考虑用块处理或验证较小的段落 :
// Monitor memory usage for large files
if (fileSize > 50 * 1024 * 1024) { // > 50MB
console.warn('Large file detected, validation may be slow');
}
业绩基准
典型的验证时间( 在现代硬件上):
| 文件大小 | 验证时间 | 内存使用 |
|---|---|---|
| < 1 MB 设备 | < 100 分钟 | ~10 MB 键 |
| 1-10 MB 设备 | 100-500毫米口径 | ~50 MB 键 |
| 10-50 甲基溴 | 500ms-2s (英语) | ~200 MB 键 |
| > 50 甲基溴 | 2s+ 调用 | ~500 MB+ 键 |
排雷中心/发改委
GitHub 动作集成
在 CI 中验证 GLTF 文件的示例工作流程 :
name: Validate GLTF Assets
on:
push:
paths:
- 'assets/**/*.gltf'
- 'assets/**/*.glb'
jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install validator
run: npm install -g @dcl/gltf-validator-ts
- name: Validate GLTF files
run: |
for file in assets/**/*.{gltf,glb}; do
echo "Validating $file"
npx gltf-validate "$file" || exit 1
done
承诺前虎克
添加验证到您的 git 前承诺钩 :
#!/bin/sh
# .git/hooks/pre-commit
# Get list of staged GLTF/GLB files
FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(gltf|glb)$')
if [ -n "$FILES" ]; then
echo "Validating GLTF files..."
for file in $FILES; do
npx @dcl/gltf-validator-ts "$file" || exit 1
done
fi
构建管道集成
与您的构建工具融合 :
网页包 :
const { GLTFValidator } = require('@dcl/gltf-validator-ts');
module.exports = {
plugins: [
{
apply: (compiler) => {
compiler.hooks.emit.tapAsync('GLTFValidationPlugin', async (compilation, callback) => {
// Validate GLTF assets during build
// ...
callback();
});
}
}
]
};
解决问题
共同问题
安装问题
错误: 找不到模块“ @dcl/ gltf- validator- ts ”
# Clear npm cache and reinstall
npm cache clean --force
npm install @dcl/gltf-validator-ts
类型脚本定义出错
# Ensure TypeScript version is compatible
npm install typescript@latest --save-dev
审定问题
大文件导致内存出错
// Increase Node.js memory limit
// Run with: NODE_OPTIONS="--max-old-space-size=4096" node script.js
// Or validate in smaller chunks
const validator = new GLTFValidator({
maxIssues: 20 // Limit issues to reduce memory
});
未加载的外部资源
// Provide custom resource loading function
const validator = new GLTFValidator({
externalResourceFunction: async (uri) => {
const fullPath = path.resolve(baseDir, uri);
return fs.readFileSync(fullPath);
}
});
验证时间太长了
// Add timeout wrapper
const timeoutPromise = (promise, ms) => {
return Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Validation timeout')), ms)
)
]);
};
await timeoutPromise(validator.validate(gltf), 5000); // 5 second timeout
浏览器- 特定问题
CORS 装入外部资源时出错
- 确保向适当的中央遥感组织信头提供资源
- 可能时使用相对路径
- 执行外部资源的代理
浏览器中的模块加载错误
- 使用预建的 Web 捆绑而不是 ES 模块
- 或配置您的捆绑器( Webpack, Rollup)
获取帮助
- 检查现有问题数字 : GitHub 问题
- 读取光谱数字 : GLTF 2. 0 规格
- 与原样比较数字 : Khronos 验证器
- 创建问题: 包含文件实例、错误消息和环境细节
财务问题
一般问题
问:这是否与克罗诺斯的官方验证器相容? 答:对! 此校验器通过官方Khronos GLTF校验器测试套件的所有609+测试,确保完全兼容.
问:我能在浏览器中使用这个吗? 答:是的,有网包可用. 见 浏览器兼容性 区域并尝试 现场演示。 。 。 .
问:此与原验者何异? A:这是TypeScript的再执行,它与最初基于达特的验证器保持了100%的行为兼容性. 它提供了更好的TypeScript集成,并可用于更多的JavaScript/TypeScript环境.
问:它支持GLTF 1.0吗? A:不,这个校验器只支持GLTF 2.0规格. GLTF 1.0被贬值.
技术问题
问:我能从 URL 校验文件吗? 答:是,先获取文件,然后验证:
const response = await fetch('https://example.com/model.glb');
const arrayBuffer = await response.arrayBuffer();
const result = await validateBytes(new Uint8Array(arrayBuffer));
问:我如何忽略某些验证警告?
A: 使用 ignoredIssues 选项 :
const validator = new GLTFValidator({
ignoredIssues: ['UNUSED_OBJECT', 'BUFFER_GLB_CHUNK_TOO_BIG']
});
问:我可以警告错误吗?
A:是,使用 severityOverrides数字 :
const validator = new GLTFValidator({
severityOverrides: {
'UNEXPECTED_PROPERTY': 0 // Make warnings (1) into errors (0)
}
});
问:我如何验证一个GLTF文件的特定部分? 答:验证器检查整个结构,但可以通过JSON指针位置过滤结果:
const result = await validator.validate(gltf);
const meshIssues = result.issues.messages.filter(
msg => msg.pointer?.startsWith('/meshes/')
);
问:它是否验证了外部资源(图像,缓冲)?
A:是的,对于GLB文件,资源被嵌入. 对于有外部资源的 GLTF 文件,请提供 externalResourceFunction 装上它们.
业绩问题
问:我如何加快大文件的验证? 答:见 性能提示 节。 主要策略:限制问题,按类型过滤,再利用验证器实例.
问:我可以平行运行验证吗? A:是,创建多个验证器实例并同时验证文件:
await Promise.all(files.map(file =>
new GLTFValidator().validate(file)
));
问:支持的最大文件大小是多少? 甲:没有硬限制,但验证性能会退化为文件 > 50MB. 考虑用更小块验证或使用网络演示进行快速检查.
捐款
- 叉子存储器
- 创建您的特性分支( E)
git checkout -b feature/amazing-feature(中文(简体) ) - 做你的改变
- 为您的更改添加测试
- 确保所有测试合格(
npm test(中文(简体) ) - 提交更改( E)
git commit -am 'Add amazing feature'(中文(简体) ) - 推向分行(
git push origin feature/amazing-feature(中文(简体) ) - 打开拉请求
许可证
这个项目根据麻省理工学院许可证颁发——见 自由主义 详细文件.
项目来源
这个项目是 100%根据官方数据 Khronos GLTF 验证器 通过AI协助的发展进程创建.
发展进程
校验器被"vibe-code"通过:
- 复制综合测试套件 从 Khronos GLTF 验证器原始寄存器
- 利用大赦国际的援助 分析测试预期并创建完整的 TypeScript 执行
- 自动建立验证符 以通过全部 609+ 从原始仓库的测试
- 保持完全兼容 与原始验证人的行为和错误报告
信贷和分配
- 原始工作数字 : Khronos 组 GLTF 验证器
- 测试套件: 直接从官方仓库复制以确保兼容性
- 执行情况: AI 辅助类型Script 重写,通过所有原始测试
- 校正逻辑: 从测试预期中逆向设计以匹配原始行为
这个项目表明,如何通过学习综合测试套件,而不是从零开始重用AI来创建相容的实现.
承认
- 建筑根据 GLTF 2. 0 规格
- 支持从 GLTF 扩展登记册
- 测试套件和验证行为:完全基于官员 Khronos GLTF 验证器
- 类型脚本执行:使用克洛德的AI辅助开发