如何使用SceneKit使用自定义SCNGeometry显示彩色点云?

Eva*_*ang 7 macos scenekit swift

我目前正致力于使用Swift开发OS X软件,以显示从PLY文件中读取的点云.该文件转换为一个数组,PointCloudVertex其定义如下:

struct PointCloudVertex {
    let x: Double, y: Double, z: Double
    let r: Double, g: Double, b: Double
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试SCNGeometry从数组中构建一个:

var vertices = [PointCloudVertex]()
for p in points {
    let v = PointCloudVertex(x: p[0], y: p[1], z: p[2], r: p[3], g: p[4], b: p[5])
    vertices.append(v)
}
let vertexData = NSData(bytes: &vertices, length: sizeof(PointCloudVertex) * points.count)
let positionSource = SCNGeometrySource(data: vertexData, semantic: SCNGeometrySourceSemanticVertex, vectorCount: points.count, floatComponents: true, componentsPerVector: 3, bytesPerComponent: sizeof(Double), dataOffset: 0, dataStride: sizeof(PointCloudVertex))
let colorSource = SCNGeometrySource(data: vertexData, semantic: SCNGeometrySourceSemanticColor, vectorCount: points.count, floatComponents: true, componentsPerVector: 3, bytesPerComponent: sizeof(CGFloat), dataOffset: sizeof(Double) * 3, dataStride: sizeof(PointCloudVertex))
let elements = SCNGeometryElement(data: nil, primitiveType: .Point, primitiveCount: points.count, bytesPerIndex: sizeof(Int))
let pointCloud = SCNGeometry(sources: [positionSource, colorSource], elements: [elements])
let pcNode = SCNNode(geometry: pointCloud)
self.modelScene.rootNode.addChildNode(pcNode)
Run Code Online (Sandbox Code Playgroud)

哪里points[[Double]]存储所有点的位置和颜色数据.我尝试显示点云.位置是正确的,但所有点都是黑色而不是我传给的颜色PointCloudVertex.此外,我还尝试使用SCNMaterial与几何相关联的颜色仍然是黑色.那么如何以丰富多彩的方式显示点云呢?我知道SceneKit有一些自定义渲染API,我想知道它是否会有所帮助.如果有一些代码可能会有所帮助,因为我对OpenGL或金属绘图的东西不太熟悉.

顺便说一下,我也试图用它SCNSphere来显示点云,它可以工作,但我需要SCNSphere为每个点创建一个.我的Mac使用这种方法耗尽内存,因为我有大约100万个点可以显示.

PLY文件采用以下格式:

ply
format ascii 1.0
comment VCGLIB generated
element vertex 684398
property float x
property float y
property float z
property uchar red
property uchar green
property uchar blue
property uchar alpha
end_header
7.42808 15.3133 1.45829 55 45 43 255 
3.92053 20.8015 -32.8147 156 141 121 255 
4.80496 21.0725 -34.3995 160 146 133 255 
8.09035 14.6247 33.5683 127 119 101 255 
14.66 20.5331 -26.406 70 64 40 255 
-0.911526 14.6359 7.66687 157 146 150 255 
...
Run Code Online (Sandbox Code Playgroud)

在我的PLY文件阅读器方法中,正文部分中的每一行都被转换为[Double](最后一列,即alpha值,被丢弃).对于红色,绿色和蓝色值,我将它们除以255,因此值介于0和1之间.