Skip to content

Instantly share code, notes, and snippets.

@patskovn
Created March 3, 2024 20:19
Show Gist options
  • Save patskovn/5d3080af2ccf6a3ba9d2aeb2b1788654 to your computer and use it in GitHub Desktop.
Save patskovn/5d3080af2ccf6a3ba9d2aeb2b1788654 to your computer and use it in GitHub Desktop.
class Camera {
private var _zoom: Float = 45.0
var position: SIMD3<Float> = .init(0, 0, 3)
var rotation: SIMD3<Float> = .init(repeating: 0)
var scale: SIMD3<Float> = .init(repeating: 1)
var projectionMatrix: matrix_float4x4 {
return Matrix.perspective(fov: Angle(degrees: Double(self._zoom)),
aspectRatio: Renderer.aspectRatio,
near: 0.1,
far: 1000)
}
var viewMatrix: matrix_float4x4 {
matrix_identity_float4x4
* Matrix.rotation(angle: .degrees(Double(rotation.x)), axis: Axis.x.simd)
* Matrix.rotation(angle: .degrees(Double(rotation.y)), axis: Axis.y.simd)
* Matrix.rotation(angle: .degrees(Double(rotation.z)), axis: Axis.z.simd)
* Matrix.translation(direction: -position)
}
}
extension Matrix {
static func perspective(fov: Angle, aspectRatio: Float, near: Float, far: Float) -> matrix_float4x4 {
let fov = Float(fov.radians)
let t: Float = tan(fov / 2)
let x: Float = 1 / (aspectRatio * t)
let y: Float = 1 / t
let z: Float = -((far + near) / (far - near))
let w: Float = -((2 * far * near) / (far - near))
var result = matrix_identity_float4x4
result.columns = (
SIMD4<Float>(x, 0, 0, 0),
SIMD4<Float>(0, y, 0, 0),
SIMD4<Float>(0, 0, z, -1),
SIMD4<Float>(0, 0, w, 0)
)
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment