Getting Started with RealityKit: Shaders

RealityKit Shaders Banner Image

What Is a Shader?

source: https://courses.cs.washington.edu/courses/cse458/99sp/info/sl/examples.html

Creating a Basic Shader With RealityKit

[
[-0.5, 0.5, 0.5], [0.5, 0.5, 0.5],
[-0.5, 0.5, -0.5], [0.5, 0.5, -0.5]
]
// Create the cube
let cubeModel = ModelEntity(
mesh: .generateBox(size: 1),
materials: [SimpleMaterial(color: .red, isMetallic: false)]
)

// Fetch the default metal library
let mtlLibrary = MTLCreateSystemDefaultDevice()!
.makeDefaultLibrary()!

// Fetch the geometry modifier by name
let geomModifier = CustomMaterial.GeometryModifier(
named: "simpleStretch", in: mtlLibrary
)

// Take each of the model's current materials,
// and apply the geometry shader to it.
cubeModel.model?.materials = cubeModel.model?.materials.map {
try! CustomMaterial(from: $0, geometryModifier: geomModifier)
} ?? [Material]()

Creating a Slightly More Advanced Shader

import RealityGeometries

var oceanMat = SimpleMaterial(color: .blue, isMetallic: false)
oceanMat.metallic = .float(0.7)
oceanMat.roughness = 0.9

let modelEnt = ModelEntity(
mesh: try! .generateDetailedPlane(
width: 2, depth: 2, vertices: (100, 100)
), materials: [oceanMat]
)
// Fetch the default metal library
let mtlLibrary = MTLCreateSystemDefaultDevice()!.makeDefaultLibrary()!
let geometryShader = CustomMaterial.GeometryModifier(
named: "waveMotion", in: mtlLibrary
)

modelEnt.model?.materials = modelEnt.model?.materials.map {
try! CustomMaterial(from: $0, geometryModifier: geometryShader)
} ?? [Material]()
// Fetch the default metal library
let mtlLibrary = MTLCreateSystemDefaultDevice()!
.makeDefaultLibrary()!
// Fetch the "waveMotion" geometry modifier
let geometryShader = CustomMaterial.GeometryModifier(
named: "waveMotion", in: mtlLibrary
)
// Fetch the "waveSurface" surface shader
let surfaceShader = CustomMaterial.SurfaceShader(
named: "waveSurface", in: mtlLibrary
)
// Apply both to the material
modelEnt.model?.materials = modelEnt.model?.materials.map {
try! CustomMaterial(
from: $0,
surfaceShader: surfaceShader,
geometryModifier: geometryShader
)
} ?? [Material]()

Conclusion

Excited about all things Augmented Reality! Developer Evangelist at Agora.io.