如何使用 RealityKit 渲染规范面网格?

问题描述 投票:0回答:1

我正在尝试使用 RealityKit 渲染面部网格,但尚未成功。因此,当 ARKit 检测到人脸时,ARSession 会生成一个 ARFaceAnchor,其中包含人脸几何网格。

但无法生成为模型实体。

有人可以帮忙吗?

swift swiftui arkit realitykit
1个回答
3
投票

RealityKit 中的规范面网格

要在 iOS RealityKit 中以编程方式生成和渲染 ARKit 的规范面网格(由 1220 个顶点组成的 ARFaceGeometry 对象),请使用以下代码:

import ARKit
import RealityKit

class ControllerView: UIViewController {
    
    @IBOutlet var arView: ARView!
    var anchor = AnchorEntity()
    var model = ModelEntity()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        arView.automaticallyConfigureSession = false
        arView.session.delegate = self

        guard ARFaceTrackingConfiguration.isSupported
        else { 
            fatalError("We can't run face tracking config") 
        }
                
        let config = ARFaceTrackingConfiguration()
        config.maximumNumberOfTrackedFaces = 1
        arView.session.run(config)
    }
}

然后创建一个转换面锚点子属性的方法。请注意,我使用 for-in 循环将索引从

[Int16]
转换为
[UInt32]
类型(类型转换在这里没有帮助)。

extension ControllerView {
    
    private func nutsAndBoltsOf(_ anchor: ARFaceAnchor) -> MeshDescriptor {
        
        let vertices: [simd_float3] = anchor.geometry.vertices
        var triangleIndices: [UInt32] = []
        let texCoords: [simd_float2] = anchor.geometry.textureCoordinates
        
        for index in anchor.geometry.triangleIndices {         // [Int16]
            triangleIndices.append(UInt32(index))
        }
        print(vertices.count)         // 1220 vertices
        
        var descriptor = MeshDescriptor(name: "canonical_face_mesh")
        descriptor.positions = MeshBuffers.Positions(vertices)
        descriptor.primitives = .triangles(triangleIndices)
        descriptor.textureCoordinates = MeshBuffers.TextureCoordinates(texCoords)
        return descriptor
    }
}

最后,让我们运行委托的方法来提供网格资源:

extension ControllerView: ARSessionDelegate {
    
    func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {

        guard let faceAnchor = anchors[0] as? ARFaceAnchor else { return }
        arView.session.add(anchor: faceAnchor)
        self.anchor = AnchorEntity(anchor: faceAnchor)
        self.anchor.scale *= 1.2

        let mesh: MeshResource = try! .generate(from: [nutsAndBoltsOf(faceAnchor)])
        var material = SimpleMaterial(color: .magenta, isMetallic: true)
        self.model = ModelEntity(mesh: mesh, materials: [material])
        self.anchor.addChild(self.model)
        arView.scene.anchors.append(self.anchor)
    }
}

结果(在 iPadOS 16.2 中的第四代 iPad Pro 上测试)。


我还建议您查看有关 RealityKit 2.0 中的 可视化检测到的飞机 的帖子。

圣诞快乐!

© www.soinside.com 2019 - 2024. All rights reserved.