Skip to content

Commit

Permalink
Merge pull request #42 from gadirom/Dedicated-shaders
Browse files Browse the repository at this point in the history
Dedicated shaders
  • Loading branch information
gadirom authored Nov 23, 2022
2 parents 7f0e3ac + 81900b4 commit 86ea315
Show file tree
Hide file tree
Showing 29 changed files with 964 additions and 224 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1410"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "0055B518288CDCDA008580B0"
BuildableName = "Example.app"
BlueprintName = "Example"
ReferencedContainer = "container:Example.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
enableThreadSanitizer = "YES"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "0055B518288CDCDA008580B0"
BuildableName = "Example.app"
BlueprintName = "Example"
ReferencedContainer = "container:Example.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "0055B518288CDCDA008580B0"
BuildableName = "Example.app"
BlueprintName = "Example"
ReferencedContainer = "container:Example.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
33 changes: 14 additions & 19 deletions Example/Example/Example/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ struct ContentView: View {
@MetalState var vertexCount = 3 * particleCount
@MetalState var particleScale: Float = 1

@State var isDrawing = false
@State var n = 1
@State var laplacianPasses = 0

Expand All @@ -72,48 +71,43 @@ struct ContentView: View {

var body: some View {
VStack{
MetalBuilderView(isDrawing: $isDrawing,
viewSettings: viewSettings){ context in
MetalBuilderView(viewSettings: viewSettings){ context in
ComputeBlock(context: context,
particlesBuffer: $particlesBuffer,
vertexBuffer: $vertexBuffer,
particleScale: $particleScale,
u: uniforms)
Render(vertex: "vertexShader",
indexBuffer: indexBuffer,
Render(indexBuffer: indexBuffer,
indexCount: MetalBinding<Int>.constant(vertexIndexCount))
.uniforms(uniforms)//, name: "uni")
.toTexture(targetTexture)
.vertexBuf(vertexBuffer, offset: 0)
.vertexBytes(context.$viewportSize, space: "constant")
.source(
.vertexShader(VertexShader("vertexShader",
vertexOut:
"""
struct RasterizerData{
float4 position [[position]];
float4 color; //[[flat]]; // - use this flag to disable color interpolation
};
vertex RasterizerData
vertexShader(uint vertexID [[vertex_id]]){
""",
body:"""
RasterizerData out;
float2 pixelSpacePosition = vertices[vertexID].position.xy;
float2 pixelSpacePosition = vertices[vertex_id].position.xy;
float2 viewport = float2(viewportSize);
out.position = vector_float4(0.0, 0.0, 0.0, 1.0);
out.position.xy = pixelSpacePosition / (viewport / 2.0);
out.color = vertices[vertexID].color;
out.color = vertices[vertex_id].color;
return out;
}
""")
.fragmentShader(FragmentShader("fragmentShader", source:
"""))
.fragmentShader(FragmentShader("fragmentShader", body:
"""
fragment float4 fragmentShader(RasterizerData in [[stage_in]]){
return in.color;
}
"""))
// Render(vertex: "vertexShader", fragment: "fragmentShader", count: vertexCount)
// .uniforms(uniforms)//, name: "uni")
Expand Down Expand Up @@ -147,11 +141,9 @@ struct ContentView: View {
//let _ = print("compile")
}
.onResize{ size in
if isDrawing {return}
createParticles(particlesBuf: particlesBuffer,
viewportSize: size)
createIndices(indexBuffer, count: vertexCount)
isDrawing = true
}
if showUniforms{
UniformsView(uniforms)
Expand All @@ -177,8 +169,11 @@ struct ContentView: View {

Button {
if let json = json {
showUniforms = false
uniforms.import(json: json)
//showUniforms.toggle()
DispatchQueue.main.asyncAfter(deadline: .now()+0.01) {
showUniforms = true
}
}
} label: {
Text("Load Uniforms")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,10 @@ public final class MetalBuilderRenderer{
unowned var device: MTLDevice!
var commandQueue: MTLCommandQueue!

var startTime: Double = 0
var pausedTime: Double = 0
var justStarted = true

var commandBuffer: MTLCommandBuffer!

let timer = MetalBuilderTimer()

//@MetalState var viewportSize: simd_uint2 = [0, 0]
}

Expand Down Expand Up @@ -53,14 +51,15 @@ public extension MetalBuilderRenderer{
librarySource: String,
helpers: String,
options: MetalBuilderCompileOptions = .default,
renderingContent: MetalRenderingContent) throws{
renderingContent: MetalBuilderContent) throws{

self.init()

self.device = renderInfo.device
self.commandQueue = device.makeCommandQueue()

let context = MetalBuilderRenderingContext()
context.timer = timer

do{

Expand All @@ -80,12 +79,8 @@ public extension MetalBuilderRenderer{

commandBuffer = try startEncode()

if justStarted {
startTime = CFAbsoluteTimeGetCurrent()
justStarted = false
}
renderData.context.time = Float(CFAbsoluteTimeGetCurrent()-startTime)
//print(renderData.context.time)
timer.count()
renderData.context.time = timer.time

for pass in renderData.passes{

Expand All @@ -110,15 +105,9 @@ public extension MetalBuilderRenderer{
}

func pauseTime(){
guard !justStarted
else{return}
pausedTime = CFAbsoluteTimeGetCurrent()
print("time paused!")
timer.backgroundPause()
}
func resumeTime(){
guard !justStarted
else{return}
startTime += CFAbsoluteTimeGetCurrent()-pausedTime
print("time resumed!")
timer.backgroundResume()
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,26 @@
import MetalKit

/// Class that is passed to the MetalContent closure and contain useful values.
/// Use these values in CPU code or pass them into shaders.
/// Class that is passed to the MetalContent closure and contain useful values and methods.
/// Use the values in CPU code or pass them into shaders.
public final class MetalBuilderRenderingContext{
/// Viewport size that can be used in a shader
/// Viewport size that can be used in a shader.
@MetalState(metalName: "viewportSize") public var viewportSize: simd_uint2 = [0,0]
/// Scale factor of the view. Used to convert point coordinates into pixel coordinates
/// Scale factor of the view. Used to convert point coordinates into pixel coordinates.
@MetalState(metalName: "scaleFactor") public var scaleFactor: Float = 1
/// Render time. Starts at zero and pauses when the app is in a background phase
/// Render time. Starts at zero and pauses when the app is in a background phase.
///
/// You can manually pause and start the timer using `pauseTime` and `resumeTime` methods.
@MetalState(metalName: "time") public var time: Float = 0


weak var timer: MetalBuilderTimer?

/// Pauses the timer.
public func pauseTime(){
timer?.manualPause()
}
/// Resumes the timer.
public func resumeTime(){
timer?.manualResume()
}
}
67 changes: 67 additions & 0 deletions Sources/MetalBuilder/MetalBuilderRenderer/MetalBuilderTimer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import AVFoundation

class MetalBuilderTimer{

public var time: Float{
_time
}

private var _time: Float = 0
private var startTime: Double = 0
private var pausedTime: Double = 0
private var justStarted = true
private var paused = true

private var manualPaused = false

// private let timerQueue = DispatchQueue(label: "MetalBuilderTimer_Queue",
// qos: .userInitiated)

func count(){
//timerQueue.sync {
if justStarted {
startTime = CFAbsoluteTimeGetCurrent()
justStarted = false
paused = false
}
if paused { return }
_time = Float(CFAbsoluteTimeGetCurrent()-startTime)
//}
}
//Pause and resume manually by the client
func manualPause(){
manualPaused = true
pauseTime()
}
func manualResume(){
manualPaused = false
resumeTime()
}
//Pause and resume for going in and from background
func backgroundPause(){
pauseTime()
}
func backgroundResume(){
if manualPaused { return }
resumeTime()
}

private func pauseTime(){
guard !justStarted
else{return}
guard !paused
else{return}
pausedTime = CFAbsoluteTimeGetCurrent()
paused = true
print("time paused!")
}
private func resumeTime(){
guard !justStarted
else{return}
guard paused
else{return}
startTime += CFAbsoluteTimeGetCurrent()-pausedTime
paused = false
print("time resumed!")
}
}
2 changes: 1 addition & 1 deletion Sources/MetalBuilder/MetalBuilderRenderer/RenderData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ struct RenderData{

init(){}

init(from renderingContent: MetalRenderingContent,
init(from renderingContent: MetalBuilderContent,
librarySource: String,
helpers: String,
options: MetalBuilderCompileOptions,
Expand Down
Loading

0 comments on commit 86ea315

Please sign in to comment.