MetalByTutorials/09-scene-graph/starter/SceneGraph/SceneGraph/Renderer.swift

155 lines
5.4 KiB
Swift

//
/**
* Copyright (c) 2019 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import MetalKit
class Renderer: NSObject {
static var device: MTLDevice!
static var commandQueue: MTLCommandQueue!
static var library: MTLLibrary!
static var colorPixelFormat: MTLPixelFormat!
static var fps: Int!
var uniforms = Uniforms()
var fragmentUniforms = FragmentUniforms()
let depthStencilState: MTLDepthStencilState
let lighting = Lighting()
lazy var camera: Camera = {
let camera = ArcballCamera()
camera.distance = 4
camera.target = [0, 1, 0]
camera.rotation = [-0.08, -0.24, 0]
return camera
}()
// Array of Models allows for rendering multiple models
var models: [Model] = []
init(metalView: MTKView) {
guard
let device = MTLCreateSystemDefaultDevice(),
let commandQueue = device.makeCommandQueue() else {
fatalError("GPU not available")
}
Renderer.device = device
Renderer.commandQueue = commandQueue
Renderer.library = device.makeDefaultLibrary()
Renderer.colorPixelFormat = metalView.colorPixelFormat
Renderer.fps = metalView.preferredFramesPerSecond
metalView.device = device
metalView.depthStencilPixelFormat = .depth32Float
depthStencilState = Renderer.buildDepthStencilState()!
super.init()
metalView.clearColor = MTLClearColor(red: 0.7, green: 0.9,
blue: 1, alpha: 1)
metalView.delegate = self
mtkView(metalView, drawableSizeWillChange: metalView.bounds.size)
// models
let ground = Model(name: "ground.obj")
ground.tiling = 32
models.append(ground)
let car = Model(name: "racing-car.obj")
car.rotation = [0, .pi / 2, 0]
car.position = [-0.8, 0, 0]
models.append(car)
let skeleton = Model(name: "skeleton.usda")
skeleton.position = [1.6, 0, 0]
skeleton.rotation = [0, .pi, 0]
skeleton.runAnimation(name: "idle")
models.append(skeleton)
fragmentUniforms.lightCount = lighting.count
}
static func buildDepthStencilState() -> MTLDepthStencilState? {
let descriptor = MTLDepthStencilDescriptor()
descriptor.depthCompareFunction = .less
descriptor.isDepthWriteEnabled = true
return
Renderer.device.makeDepthStencilState(descriptor: descriptor)
}
}
extension Renderer: MTKViewDelegate {
func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
camera.aspect = Float(view.bounds.width)/Float(view.bounds.height)
}
func draw(in view: MTKView) {
guard
let descriptor = view.currentRenderPassDescriptor,
let commandBuffer = Renderer.commandQueue.makeCommandBuffer(),
let renderEncoder =
commandBuffer.makeRenderCommandEncoder(descriptor: descriptor) else {
return
}
// update all the models' poses
let deltaTime = 1 / Float(Renderer.fps)
for model in models {
model.update(deltaTime: deltaTime)
}
renderEncoder.setDepthStencilState(depthStencilState)
uniforms.projectionMatrix = camera.projectionMatrix
uniforms.viewMatrix = camera.viewMatrix
fragmentUniforms.cameraPosition = camera.position
var lights = lighting.lights
renderEncoder.setFragmentBytes(&lights,
length: MemoryLayout<Light>.stride * lights.count,
index: Int(BufferIndexLights.rawValue))
// render all the models in the array
for model in models {
renderEncoder.pushDebugGroup(model.name)
model.render(renderEncoder: renderEncoder,
uniforms: uniforms,
fragmentUniforms: fragmentUniforms)
renderEncoder.popDebugGroup()
}
renderEncoder.endEncoding()
guard let drawable = view.currentDrawable else {
return
}
commandBuffer.present(drawable)
commandBuffer.commit()
commandBuffer.waitUntilCompleted()
}
}