0

我正在尝试将网格导入 SCNGeometry。我确实想从 CPU 单独操作顶点。因此,我想根据以下帖子进行操作:https ://developer.apple.com/forums/thread/91618 。到目前为止,我已经将它导入模型 I/O 框架并创建了一个 MTLBuffer。

    let MDLPositionData = mesh?.vertexAttributeData(forAttributeNamed: "position", as: .float3)
    
    let vertexBuffer1 = device.makeBuffer(bytes: MDLPositionData!.dataStart,
                                          length: MDLPositionData!.bufferSize,
                                          options: [.cpuCacheModeWriteCombined])
    let vertexSource = SCNGeometrySource(
           buffer: vertexBuffer1!,
           vertexFormat: vertexFormat,
           semantic: SCNGeometrySource.Semantic.vertex,
           vertexCount: mesh!.vertexCount,
           dataOffset: 0,
           dataStride: MemoryLayout<vector_float3>.size)

SCNGeometry 需要索引元素才能正确显示网格。我从哪里得到这些?我尝试使用模型 I/O 中的子网格:

    let submesh = mesh?.submeshes?[0]
    let indexBuffer = (submesh as? MDLSubmesh)?.indexBuffer(asIndexType: .uInt32)
    let indexBufferData = Data(bytes: indexBuffer!.map().bytes, count: indexBuffer!.length)
    let indexElement = SCNGeometryElement(
        data: indexBufferData,
        primitiveType: SCNGeometryPrimitiveType.triangles,
        primitiveCount: indexBuffer!.length,
        bytesPerIndex: 32)
    let geo = SCNGeometry(sources: [vertexSource, normalSource], elements: [indexElement])

但这会引发错误 [SceneKit] Error: C3DMeshElementSetPrimitives invalid index buffer size并显示以下几何图形:The Teapot。似乎顶点没有正确连接。

如何获得正确的索引数据?谢谢!

4

0 回答 0