richoncode
(Richard Bailey)
1
I'm playing with resultbuilders and methods chaining to create declarative spatial scenes within a RealityKit RealityView.
In one case I'm struggling with getting to a cleanest declaration of a mesh entity (basic geormetry shape, color, metalic, etc). I tried a version that took in a SimpleMaterial, modified it and output a new simple material is the adjustment of the chained modified. I had issues with the getters and inits if simple material not having compatible types.
I'm looking at another appoach of having a builder syntax, but it its not as clean and error prone to use.
I'm open to all suggestions and feedback.
I will push this to public git when done-ish.
extension ModelComponent {
struct Builder {
var mesh: MeshResource?
var color: UIColor?
var isMetallic: Bool = false
func build() -> ModelComponent {
let materialColor = color ?? .white // Default color
let material = SimpleMaterial(color: materialColor, isMetallic: isMetallic)
let meshResource = mesh ?? MeshResource.generateBox(size: 0.1) // Default mesh
return ModelComponent(mesh: meshResource, materials: [material])
}
}
var builder: Builder {
return Builder()
}
}
extension ModelComponent.Builder {
mutating func box(_ size: Float) -> ModelComponent.Builder {
self.mesh = MeshResource.generateBox(size: size)
return self
}
mutating func color(_ color: UIColor) -> ModelComponent.Builder {
self.color = color
return self
}
mutating func metallic(_ isMetallic: Bool = true) -> ModelComponent.Builder {
self.isMetallic = isMetallic
return self
}
}
// Usage
let modelComponent = ModelComponent().builder
.box(0.1)
.color(.blue)
.metallic()
.build()