-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBufferProvider.swift
45 lines (38 loc) · 1.23 KB
/
BufferProvider.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//
// BufferProvider.swift
// Quake 3 BSP Renderer
//
// Created by Thomas Brunoli on 9/01/2016.
// Copyright © 2016 Thomas Brunoli. All rights reserved.
//
import Foundation
import Metal
class BufferProvider {
let inflightBuffersCount: Int
fileprivate var buffers: [MTLBuffer] = []
fileprivate var nextBufferIndex: Int = 0
fileprivate var availableBuffers: DispatchSemaphore
init(device: MTLDevice, inflightBuffersCount: Int, bufferSize: Int) {
self.inflightBuffersCount = inflightBuffersCount
availableBuffers = DispatchSemaphore(value: inflightBuffersCount)
for _ in 0..<inflightBuffersCount {
buffers.append(
device.makeBuffer(length: bufferSize, options: MTLResourceOptions())!
)
}
}
func nextBuffer() -> MTLBuffer {
let _ = availableBuffers.wait(timeout: DispatchTime.distantFuture)
let buffer = buffers[nextBufferIndex]
nextBufferIndex = (nextBufferIndex + 1) % inflightBuffersCount
return buffer
}
func finishedWithBuffer() {
availableBuffers.signal()
}
deinit {
for _ in 0...inflightBuffersCount {
finishedWithBuffer()
}
}
}