Created
June 23, 2019 21:37
-
-
Save JaapWijnen/f344d318eadfe8892f897ef38d591436 to your computer and use it in GitHub Desktop.
recalculating normals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I'm rendering a subdivided quad of resolution x resolution vertices | |
let vertex = Vertex(position: position, normal: float3(0,0,0), texture: float2(0,0)) | |
vertices.append(vertex) | |
// vertices are stored in a vertices array, same for indices | |
// for every vertex but the last row and column we want to create two triangles | |
if x != resolution-1 && y != resolution-1 { | |
self.indices.append(contentsOf: [ | |
UInt16(i), UInt16(i + resolution), UInt16(i + resolution + 1), // triangle 1 | |
UInt16(i), UInt16(i + resolution + 1), UInt16(i + 1) // triangle 2 | |
]) | |
} | |
// recalculate normals | |
// access indices in pairs of three | |
for i in stride(from: 0, to: indices.count, by: 3) { | |
// grab the actual vertex index | |
let i0 = Int(indices[i]) | |
let i1 = Int(indices[i+1]) | |
let i2 = Int(indices[i+2]) | |
// grab the vertices of the triangle | |
let v0 = vertices[i0] | |
let v1 = vertices[i1] | |
let v2 = vertices[i2] | |
// create two vectors from triangle sides | |
let u = v1.position - v0.position | |
let v = v2.position - v0.position | |
// calculate normal | |
let n = normalize(cross(v, u)) | |
// add normal to all vertices of triangle | |
vertices[i0].normal += n | |
vertices[i1].normal += n | |
vertices[i2].normal += n | |
} | |
// normalize all vertices after summing all the normals | |
for i in 0..<vertices.count { | |
vertices[i].normal = normalize(vertices[i].normal) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment