1

I am quite new to swift and Xcode however, I have been programming in other languages for several years. I am trying to procedurally create a 3D mesh in SceneKit (iOS). My code works as expected however, when running the application the generated object renders a flat black colour, ignoring all lighting. I have also added a cube to the scene to show that the scene lighting is working.

I would imagine that there is either a problem with the shader or that I need to define the normals of the geometry to fix this. I have tried playing around with a few properties of the SCNMaterial, but they don't seem to change anything.

If it is just a case of defining the normals, please could you advise how I would do this in Swift / SceneKit. Or perhaps I have missed something else, any help would be much appreciated.

Screenshot below: Rendering black, unlit

My code below:

  public static func CreateMesh (size: CGFloat, resolution: CGFloat) -> SCNNode? {
    let axisCount = Int(floor(size / resolution))
    let bottomLeft = CGVector(
        dx: CGFloat(-(axisCount / 2)) * resolution,
        dy: CGFloat(-(axisCount / 2)) * resolution
    )

    var verts = Array(
        repeating: Array(
            repeating: (i: Int(0), pos: SCNVector3.init(x: 0, y: 0, z: 0)),
            count: axisCount),
        count: axisCount
    )
    var vertsStream = [SCNVector3]()

    var i : Int = 0
    for x in 0...axisCount-1 {
        for y in 0...axisCount-1 {
            verts[x][y] = (
                i,
                SCNVector3(
                    x: Float(bottomLeft.dx + CGFloat(x) * resolution),
                    y: Float.random(in: 0..<0.1),
                    z: Float(bottomLeft.dy + CGFloat(y) * resolution)
                )
            )
            vertsStream.append(verts[x][y].pos)

            i += 1
        }
    }

    var tris = [(a: Int, b: Int, c: Int)]()
    var trisStream = [UInt16]()
    for x in 0...axisCount - 2 {
        for y in 0...axisCount - 2 {
            // Quad
            tris.append((
                a: verts[x][y].i,
                b: verts[x][y+1].i,
                c: verts[x+1][y+1].i
            ))
            tris.append((
                a: verts[x+1][y+1].i,
                b: verts[x+1][y].i,
                c: verts[x][y].i
            ))
        }
    }
    for t in tris {
        trisStream.append(UInt16(t.a))
        trisStream.append(UInt16(t.b))
        trisStream.append(UInt16(t.c))
    }

    // Create scene element
    let geometrySource = SCNGeometrySource(vertices: vertsStream)
    let geometryElement = SCNGeometryElement(indices: trisStream, primitiveType: .triangles)
    let geometryFinal = SCNGeometry(sources: [geometrySource], elements: [geometryElement])
    let node = SCNNode(geometry: geometryFinal)

    ////////////////////////
    // FIX MATERIAL
    ////////////////////////
    let mat = SCNMaterial()
    mat.diffuse.intensity = 1
    mat.lightingModel = .blinn
    mat.blendMode = .replace

    node.geometry?.materials = [mat]

    return node
}
Edric
  • 24,639
  • 13
  • 81
  • 91
Brandon Kynoch
  • 150
  • 1
  • 1
  • 7

1 Answers1

1

After a lot of searching I managed to find a post with a line of code that looks something like this:

let gsNormals = SCNGeometrySource(normals: normalStream)

So from there I managed to work out how to set the surface normals. It seems like there really isn't a lot of online content / learning material when it comes to the more advanced topics like this in Xcode / Swift, which is quite unfortunate.

I have set it up to create a parabolic shape plane, just for testing. But this code will be used to generate a mesh from a height map, which should now be easy to implement. I think it's pretty useful code, so I have included it below incase anyone else ever has the same issue that I did.

fixed normals, correct lighting

public static func CreateMesh (size: CGFloat, resolution: CGFloat) -> SCNNode? {
    let axisCount = Int(floor(size / resolution))
    let bottomLeft = CGVector(
        dx: CGFloat(-(axisCount / 2)) * resolution,
        dy: CGFloat(-(axisCount / 2)) * resolution
    )

    /// Verticies ///
    var verts = Array(
        repeating: Array(
            repeating: (i: Int(0), pos: SCNVector3.init(x: 0, y: 0, z: 0)),
            count: axisCount),
        count: axisCount
    )
    var vertsStream = [SCNVector3]()

    var i = 0
    for x in 0...axisCount - 1 {
        for y in 0...axisCount - 1 {
            var dx = axisCount / 2 - x
            dx = dx * dx
            var dy = axisCount / 2 - y
            dy = dy * dy
            let yVal = Float(Double(dx + dy) * 0.0125)
            verts[x][y] = (
                i: i,
                pos: SCNVector3(
                    x: Float(bottomLeft.dx + CGFloat(x) * resolution),
                    //y: Float.random(in: 0..<0.1),
                    y: yVal,
                    z: Float(bottomLeft.dy + CGFloat(y) * resolution)
                )
            )

            vertsStream.append(verts[x][y].pos)

            i += 1
        }
    }
    ///

    /// Triangles ///
    var tris = [(a: Int, b: Int, c: Int)]()
    var trisStream = [UInt32]()
    for x in 0...axisCount - 2 {
        for y in 0...axisCount - 2 {
            // Quad
            tris.append((
                a: verts[x][y].i,
                b: verts[x][y+1].i,
                c: verts[x+1][y].i
            ))
            tris.append((
                a: verts[x+1][y].i,
                b: verts[x][y+1].i,
                c: verts[x+1][y+1].i
            ))
        }
    }
    for t in tris {
        trisStream.append(UInt32(t.a))
        trisStream.append(UInt32(t.b))
        trisStream.append(UInt32(t.c))
    }
    ///

    /// Normals ///
    var normalStream = [SCNVector3]()
    for x in 0...axisCount - 1 {
        for y in 0...axisCount - 1 {
            // calculate normal vector perp to average plane
            let leftX = x == 0 ? 0 : x - 1
            let rightX = x == axisCount - 1 ? axisCount - 1 : x + 1
            let leftY = y == 0 ? 0 : y - 1
            let rightY = y == axisCount - 1 ? axisCount - 1 : y + 1

            let avgXVector = float3(verts[rightX][y].pos) - float3(verts[leftX][y].pos)
            let avgYVector = float3(verts[x][rightY].pos) - float3(verts[x][leftY].pos)

            // If you are unfamiliar with how to calculate normals
            // search for vector cross product, this is used to find
            // a vector that is orthogonal to two other vectors, in our
            // case perpendicular to the surface
            let normal = cross(
                normalize(avgYVector),
                normalize(avgXVector)
            )

            normalStream.append(SCNVector3(normal))
        }
    }
    ///

    // Create scene element
    let gsGeometry = SCNGeometrySource(vertices: vertsStream)
    let gsNormals = SCNGeometrySource(normals: normalStream)

    let geometryElement = SCNGeometryElement(indices: trisStream, primitiveType: .triangles)
    let geometryFinal = SCNGeometry(sources: [gsGeometry, gsNormals], elements: [geometryElement])

    let node = SCNNode(geometry: geometryFinal)

    let mat = SCNMaterial()
    mat.isDoubleSided = true
    mat.lightingModel = .blinn

    node.geometry?.materials = [mat]

    return node
}
Brandon Kynoch
  • 150
  • 1
  • 1
  • 7
  • I was in a similar situation - for me the problem was that `SCNGeometryElement` init method requires an array of `UInt32`s, just as you have in your answer but not in the question. Using just Integer fails silently :/ – Aderstedt Aug 27 '19 at 19:19