在Autodesk Forge Viewer中重新计算边界框可以使用以下代码示例:
function computeBoundingBox(viewer, model) {
const modelInstanceTree = model.getData().instanceTree;
const rootId = modelInstanceTree.getRootId();
let boundingBox = new THREE.Box3();
const fragIds = [];
modelInstanceTree.enumNodeFragments(rootId, (fragId) => {
fragIds.push(fragId);
});
fragIds.forEach((fragId) => {
const fragBoundingBox = new THREE.Box3();
modelInstanceTree.getWorldBounds(fragId, fragBoundingBox);
boundingBox.union(fragBoundingBox);
});
const min = boundingBox.min;
const max = boundingBox.max;
const worldMin = new THREE.Vector3(min.x, min.y, min.z);
const worldMax = new THREE.Vector3(max.x, max.y, max.z);
const worldSize = worldMax.clone().sub(worldMin);
const center = worldMin.clone().add(worldSize.clone().multiplyScalar(0.5));
const size = Math.max(worldSize.x, worldSize.y, worldSize.z);
const newBoundingBox = new THREE.Box3(
new THREE.Vector3(center.x - size / 2, center.y - size / 2, center.z - size / 2),
new THREE.Vector3(center.x + size / 2, center.y + size / 2, center.z + size / 2)
);
viewer.impl.invalidate(true, true, true);
return newBoundingBox;
}
const viewer = new Autodesk.Viewing.Private.GuiViewer3D(document.getElementById('viewer'));
const options = {
env: 'AutodeskProduction',
getAccessToken: getForgeToken,
};
Autodesk.Viewing.Initializer(options, () => {
viewer.start();
viewer.loadModel('your-model-url', (model) => {
const boundingBox = computeBoundingBox(viewer, model);
console.log('New Bounding Box:', boundingBox);
});
});
请确保在上述代码中将'your-model-url'
替换为您要加载的模型的URL。
这段代码通过遍历模型的所有碎片(fragments)并获取其世界边界框(world bounds),然后合并所有碎片的边界框以计算出新的边界框。最后,它使用新的边界框更新了Viewer的显示,并返回计算出的新边界框对象。
请注意,此代码示例假设您已经通过合适的方式(例如使用Forge OAuth认证)获取了访问令牌(access token)。如果您还没有设置获取访问令牌的函数getForgeToken
,则需要相应地实现它。