Skip to content

Instantly share code, notes, and snippets.

@hadiidbouk
Last active July 22, 2021 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadiidbouk/e3dc6c9bcdfead361acaebb4498826c6 to your computer and use it in GitHub Desktop.
Save hadiidbouk/e3dc6c9bcdfead361acaebb4498826c6 to your computer and use it in GitHub Desktop.
De Casteljau's algorithm implementation in Swift 5
import CoreGraphics
class Casteljau {
let count: Int
let x: [CGFloat]
let y: [CGFloat]
var b: [[CGFloat]]
init(p0: CGPoint, p1: CGPoint, p2: CGPoint, p3: CGPoint) {
let points = [p0, p1, p2, p3]
x = points.map(\.x)
y = points.map(\.y)
count = points.count
let nanArray = Array(repeating: CGFloat.nan, count: count)
b = Array(repeating: nanArray, count: count)
}
func point(at t: CGFloat) -> CGPoint {
return .init(x: evaluate(t: t, initialValues: x),
y: evaluate(t: t, initialValues: y))
}
}
private extension Casteljau {
func initialize(_ initialValues: [CGFloat]) {
for i in 0..<count {
b[0][i] = initialValues[i]
}
}
func evaluate(t: CGFloat, initialValues: [CGFloat]) -> CGFloat {
initialize(initialValues)
for j in 1..<count {
for i in 0..<count-j {
b[j][i] = b[j-1][i] * (1-t) + b[j-1][i+1] * t
}
}
return b[count-1][0]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment