咨询:如何通过Model Derivatives API获取Sketchup衍生MTL的原始材质名
问题
尝试获取Sketchup文件衍生的mtl文件中定义的材质名称。直接打开Sketchup导出的mtl文件时,能看到newmtl MaterialName格式的原始材质名,但通过Model Derivatives API解析获取的mtl文件内容里,所有材质名均显示为newmtl Obj.111这类Obj.*格式,无法拿到预期的原始名称。请问是否有其他方法可获取与对应模型片段关联的原始材质名?
当前用于获取mtl文件的代码如下:
const ForgeSDK = require('forge-apis'); this.derivativesApi = new ForgeSDK.DerivativesApi(null, 'US'); async getMTLFile(urn) { const manifest = await this.getManifest(urn); const objDerivatives = manifest.derivatives.find( (x) => x.outputType === 'obj' ); if (!objDerivatives?.children) { return null; } const mtlInfo = objDerivatives.children.find((x) => x.urn.endsWith('.mtl')); if (!mtlInfo) { return null; } const dm = await this.getDerivativeManifest(urn, mtlInfo.urn); return dm.body; } async getDerivativeManifest(urn, derivativeURN) { const urnB64 = Forge.toBase64(urn); const creds = await this.getCredentials(); const dm = await this.derivativesApi .getDerivativeManifest(urnB64, derivativeURN, {}, this.client, creds) .catch(Forge.parseError); if (!dm) { throw new Error( `Unable to retrieve derivative manifest. urn: ${urn}, derivativeURN: ${derivativeURN}` ); } return dm; }
解决方案
Model Derivatives导出OBJ格式时,会自动将材质重命名为Obj.*格式以避免命名冲突,但可以通过以下两种方式获取原始材质名与OBJ中重命名材质的映射关系:
1. 获取模型属性数据(Properties)
通过Derivatives API的getModelviewProperties接口获取模型的属性清单,其中包含每个模型对象的材质关联信息,可直接提取原始材质名称与Obj.*的映射:
async getMaterialMapping(urn) { const urnB64 = Forge.toBase64(urn); const creds = await this.getCredentials(); // 调用API获取模型属性 const propertiesRes = await this.derivativesApi.getModelviewProperties(urnB64, {}, this.client, creds) .catch(Forge.parseError); if (!propertiesRes) { throw new Error('Failed to fetch model properties'); } const materialMap = new Map(); // 遍历所有对象属性,提取材质映射 propertiesRes.data.collection.forEach(entity => { if (entity.properties && entity.properties.Material) { // entity.name 对应OBJ中的 Obj.* 名称,entity.properties.Material 是原始材质名 materialMap.set(entity.name, entity.properties.Material); } }); return materialMap; }
使用时,你可以先获取这个映射表,再结合mtl文件中的Obj.*名称,替换为原始材质名。
2. 导出SVF格式解析元数据
若导出SVF格式而非OBJ,可通过Derivatives API获取模型的完整元数据,其中包含更详细的材质信息与模型片段的关联关系,能直接拿到原始材质名称。SVF的元数据结构保留了模型的原始层级和材质映射,适合需要深度关联模型片段与材质的场景。
内容的提问来源于stack exchange,提问作者courtney
相关产品推荐
相关产品推荐

