2016-11-02 65 views
0

工作在此之後溶液:Custom SceneKit Geometry並轉換爲夫特3,碼成爲:借鑑SceneKit的線不會在設備

func drawLine() { 

    var verts = [SCNVector3(x: 0,y: 0,z: 0),SCNVector3(x: 1,y: 0,z: 0),SCNVector3(x: 0,y: 1,z: 0)] 

    let src = SCNGeometrySource(vertices: &verts, count: 3) 
    let indexes: [CInt] = [0, 1, 2] 

    let dat = NSData(
     bytes: indexes, 
     length: MemoryLayout<CInt>.size * indexes.count 
    ) 
    let ele = SCNGeometryElement(
     data: dat as Data, 
     primitiveType: .line, 
     primitiveCount: 2, 
     bytesPerIndex: MemoryLayout<CInt>.size 
    ) 
    let geo = SCNGeometry(sources: [src], elements: [ele]) 

    let nd = SCNNode(geometry: geo) 

    geo.materials.first?.lightingModel = .blinn 
    geo.materials.first?.diffuse.contents = UIColor.red 
    scene.rootNode.addChildNode(nd) 

} 

它上模擬器工作:

red line on simulator

但我在設備上出現錯誤:

/BuildRoot/Library/Caches/com.apple.xbs/Sources/Metal/Metal-85.83/ToolsLayers/Debug/MTLDebugRenderCommandEncoder.mm:130: failed assertion `indexBufferOffset(0) + (indexCount(4) * 4) must be <= [indexBuffer length](12).' 

發生了什麼事?

整個代碼是在這裏:Source code

回答

2

我回答我的問題,因爲我找到了一個解決方案,可以幫助別人。

問題出在「索引」上,3個索引不會繪製2個頂點。必須爲要繪製的每個頂點設置2個索引。

這是最後的功能:

func drawLine(_ verts : [SCNVector3], color : UIColor) -> SCNNode? { 

    if verts.count < 2 { return nil } 

    let src = SCNGeometrySource(vertices: verts, count: verts.count) 
    var indexes: [CInt] = [] 

    for i in 0...verts.count - 1 { 
     indexes.append(contentsOf: [CInt(i), CInt(i + 1)]) 
    } 

    let dat = NSData(
     bytes: indexes, 
     length: MemoryLayout<CInt>.size * indexes.count 
    ) 

    let ele = SCNGeometryElement(
     data: dat as Data, 
     primitiveType: .line, 
     primitiveCount: verts.count - 1, 
     bytesPerIndex: MemoryLayout<CInt>.size 
    ) 

    let line = SCNGeometry(sources: [src], elements: [ele]) 

    let node = SCNNode(geometry: line) 

    line.materials.first?.lightingModel = .blinn 
    line.materials.first?.diffuse.contents = color 

    return node 
} 

呼叫:

scene.rootNode.addChildNode(
    drawLine(
     [SCNVector3(x: -1,y: 0,z: 0), 
     SCNVector3(x: 1,y: 0.5,z: 1), 
     SCNVector3(x: 0,y: 1.5,z: 0)] , color: UIColor.red 
     )! 
) 

將借鑑: enter image description here