网格检测
网格检测提供现实几何的网格表示,可实现虚拟与现实的视觉或逻辑交互,例如:
- 虚拟物体在现实环境中的物理模拟。
- 寻路。
- 物体摆放。
- 遮挡。
- 程序化效果。
API 提供网格列表、几何体、变换和语义标签。
数据可为预先捕获,也可实时重建,取决于底层系统。
支持
if (app.xr.meshDetection.supported) {
// mesh detection is supported
}
app.xr.on('start', () => {
if (app.xr.meshDetection.available) {
// mesh detection is available
}
});
访问
启动会话时添加功能标志:
app.xr.start(camera, pc.XRTYPE_AR, pc.XRSPACE_LOCALFLOOR, {
meshDetection: true
});
网格异步添加和移除:
app.xr.meshDetection.on('add', (xrMesh) => {
// a new XrMesh has been added
xrMesh.once('remove', () => {
// an XrMesh has been removed
});
});
也可读取 XrMesh 列表:
const xrMeshes = app.xr.meshDetection.meshes;
for (let i = 0; i < xrMeshes.length; i++) {
const xrMesh = xrMeshes[i];
}
网格
各网格为 XrMesh 实例,会话期间可增删,数据也可变化。
读取世界空间位置和旋转:
entity.setPosition(xrMesh.getPosition());
entity.setRotation(xrMesh.getRotation());
局部顶点和索引可构建可视网格。下面为每个 XrMesh 创建网格并添加到场景根:
app.xr.meshDetection.on('add', (xrMesh) => {
// geometry data
const mesh = new pc.Mesh(app.graphicsDevice);
mesh.clear(true, true); // ensure that mesh is created with dynamic buffers
mesh.setPositions(xrMesh.vertices); // set vertices
mesh.setNormals(pc.calculateNormals(xrMesh.vertices, xrMesh.indices)); // calculate normals
mesh.setIndices(xrMesh.indices); // set indices
mesh.update(pc.PRIMITIVE_TRIANGLES); // update buffers
const material = new pc.StandardMaterial();
const meshInstance = new pc.MeshInstance(mesh, material);
const entity = new pc.Entity();
// add render component
entity.addComponent('render', {
meshInstances: [ meshInstance ]
});
// add entity to the scene root
app.root.addChild(entity);
// clean up after XrMesh is removed
xrMesh.once('remove', () => {
material.destroy();
mesh.destroy();
entity.destroy();
});
});
语义标签
通过 XrMesh.label 可判断它表示何种现实对象。
例如 floor、wall、door、window、table、screen、global mesh、other 等。标签列表并非最终限制,平台可返回其他合适标签。
变化
底层支持时,几何体在会话期间可能更新,可监听并同步可视网格:
xrMesh.on('change', () => {
// vertices, indices and/or label has been changed
});