Skip to content

Commit

Permalink
Revert "Merge pull request #30 from frenzibyte/metal-gpu-fences"
Browse files Browse the repository at this point in the history
This reverts commit b84af63, reversing
changes made to 6a43198.
  • Loading branch information
frenzibyte committed Jul 13, 2023
1 parent d907d7f commit 9166e43
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 83 deletions.
6 changes: 1 addition & 5 deletions src/Veldrid.MetalBindings/MTLCommandBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,6 @@ public void addCompletedHandler(MTLCommandBufferHandler block)
public void addCompletedHandler(IntPtr block)
=> objc_msgSend(NativePtr, sel_addCompletedHandler, block);

public void encodeSignalEvent(IntPtr @event, ulong value)
=> objc_msgSend(NativePtr, sel_encodeSignalEvent, @event, value);

public MTLCommandBufferStatus status => (MTLCommandBufferStatus)uint_objc_msgSend(NativePtr, sel_status);

private static readonly Selector sel_renderCommandEncoderWithDescriptor = "renderCommandEncoderWithDescriptor:";
Expand All @@ -44,7 +41,6 @@ public void encodeSignalEvent(IntPtr @event, ulong value)
private static readonly Selector sel_computeCommandEncoder = "computeCommandEncoder";
private static readonly Selector sel_waitUntilCompleted = "waitUntilCompleted";
private static readonly Selector sel_addCompletedHandler = "addCompletedHandler:";
private static readonly Selector sel_encodeSignalEvent = "encodeSignalEvent:value:";
private static readonly Selector sel_status = "status";
}
}
}
6 changes: 1 addition & 5 deletions src/Veldrid.MetalBindings/MTLDevice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,6 @@ public MTLSamplerState newSamplerStateWithDescriptor(MTLSamplerDescriptor descri
public MTLDepthStencilState newDepthStencilStateWithDescriptor(MTLDepthStencilDescriptor descriptor)
=> objc_msgSend<MTLDepthStencilState>(NativePtr, sel_newDepthStencilStateWithDescriptor, descriptor.NativePtr);

public MTLSharedEvent newSharedEvent()
=> objc_msgSend<MTLSharedEvent>(NativePtr, sel_newSharedEvent);

public Bool8 supportsTextureSampleCount(UIntPtr sampleCount)
=> bool8_objc_msgSend(NativePtr, sel_supportsTextureSampleCount, sampleCount);

Expand Down Expand Up @@ -146,9 +143,8 @@ public Bool8 isDepth24Stencil8PixelFormatSupported
private static readonly Selector sel_newTextureWithDescriptor = "newTextureWithDescriptor:";
private static readonly Selector sel_newSamplerStateWithDescriptor = "newSamplerStateWithDescriptor:";
private static readonly Selector sel_newDepthStencilStateWithDescriptor = "newDepthStencilStateWithDescriptor:";
private static readonly Selector sel_newSharedEvent = "newSharedEvent";
private static readonly Selector sel_supportsTextureSampleCount = "supportsTextureSampleCount:";
private static readonly Selector sel_supportsFeatureSet = "supportsFeatureSet:";
private static readonly Selector sel_isDepth24Stencil8PixelFormatSupported = "isDepth24Stencil8PixelFormatSupported";
}
}
}
25 changes: 0 additions & 25 deletions src/Veldrid.MetalBindings/MTLSharedEvent.cs

This file was deleted.

4 changes: 0 additions & 4 deletions src/Veldrid.MetalBindings/ObjectiveCRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ public static unsafe class ObjectiveCRuntime
[DllImport(ObjCLibrary, EntryPoint = "objc_msgSend")]
public static extern void objc_msgSend(IntPtr receiver, Selector selector, double a);
[DllImport(ObjCLibrary, EntryPoint = "objc_msgSend")]
public static extern void objc_msgSend(IntPtr receiver, Selector selector, ulong a);
[DllImport(ObjCLibrary, EntryPoint = "objc_msgSend")]
public static extern void objc_msgSend(IntPtr receiver, Selector selector, CGRect a);
[DllImport(ObjCLibrary, EntryPoint = "objc_msgSend")]
public static extern void objc_msgSend(IntPtr receiver, Selector selector, IntPtr a, uint b);
Expand Down Expand Up @@ -58,8 +56,6 @@ public static unsafe class ObjectiveCRuntime
public static extern void objc_msgSend(IntPtr receiver, Selector selector, MTLPrimitiveType a, UIntPtr b, MTLIndexType c, IntPtr d, UIntPtr e, UIntPtr f);
[DllImport(ObjCLibrary, EntryPoint = "objc_msgSend")]
public static extern void objc_msgSend(IntPtr receiver, Selector selector, MTLPrimitiveType a, MTLBuffer b, UIntPtr c);
[DllImport(ObjCLibrary, EntryPoint = "objc_msgSend")]
public static extern void objc_msgSend(IntPtr receiver, Selector selector, IntPtr a, ulong b);

[DllImport(ObjCLibrary, EntryPoint = "objc_msgSend")]
public static extern void objc_msgSend(
Expand Down
10 changes: 10 additions & 0 deletions src/Veldrid/MTL/MTLCommandList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ internal unsafe class MTLCommandList : CommandList
private readonly List<MTLBuffer> _availableStagingBuffers = new List<MTLBuffer>();
private readonly Dictionary<MTLCommandBuffer, List<MTLBuffer>> _submittedStagingBuffers = new Dictionary<MTLCommandBuffer, List<MTLBuffer>>();
private readonly object _submittedCommandsLock = new object();
private MTLFence _completionFence;

public MTLCommandBuffer CommandBuffer => _cb;

Expand Down Expand Up @@ -407,8 +408,17 @@ private MTLBuffer GetFreeStagingBuffer(uint sizeInBytes)
return Util.AssertSubtype<DeviceBuffer, MTLBuffer>(staging);
}

public void SetCompletionFence(MTLFence fence)
{
Debug.Assert(_completionFence == null);
_completionFence = fence;
}

public void OnCompleted(MTLCommandBuffer cb)
{
_completionFence?.Set();
_completionFence = null;

lock (_submittedCommandsLock)
{
if (_submittedStagingBuffers.TryGetValue(cb, out List<MTLBuffer> bufferList))
Expand Down
28 changes: 16 additions & 12 deletions src/Veldrid/MTL/MTLFence.cs
Original file line number Diff line number Diff line change
@@ -1,35 +1,39 @@
using Veldrid.MetalBindings;
using System;
using System.Threading;

namespace Veldrid.MTL
{
internal class MTLFence : Fence
{
public const ulong NOT_SIGNALED = 0;
public const ulong SIGNALED = 1;

private MTLSharedEvent _event;
private readonly ManualResetEvent _mre;
private bool _disposed;

public MTLFence(bool signaled, MTLGraphicsDevice gd)
public MTLFence(bool signaled)
{
_event = gd.Device.newSharedEvent();
_mre = new ManualResetEvent(signaled);
}

public override string Name { get; set; }
public ManualResetEvent ResetEvent => _mre;

public override void Reset() => _event.signaledValue = NOT_SIGNALED;
public MTLSharedEvent SharedEvent => _event;

public override bool Signaled => _event.signaledValue == SIGNALED;
public void Set() => _mre.Set();
public override void Reset() => _mre.Reset();
public override bool Signaled => _mre.WaitOne(0);
public override bool IsDisposed => _disposed;

public override void Dispose()
{
if (!_disposed)
{
ObjectiveCRuntime.release(_event.NativePtr);
_mre.Dispose();
_disposed = true;
}
}

internal bool Wait(ulong nanosecondTimeout)
{
ulong timeout = Math.Min(int.MaxValue, nanosecondTimeout / 1_000_000);
return _mre.WaitOne((int)timeout);
}
}
}
101 changes: 70 additions & 31 deletions src/Veldrid/MTL/MTLGraphicsDevice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ namespace Veldrid.MTL
internal unsafe class MTLGraphicsDevice : GraphicsDevice
{
private static readonly Lazy<bool> s_isSupported = new Lazy<bool>(GetIsSupported);

private static readonly Dictionary<IntPtr, MTLGraphicsDevice> s_aotRegisteredBlocks
= new Dictionary<IntPtr, MTLGraphicsDevice>();

Expand Down Expand Up @@ -158,12 +157,10 @@ public MTLGraphicsDevice(

TextureSampleCount[] allSampleCounts = (TextureSampleCount[])Enum.GetValues(typeof(TextureSampleCount));
_supportedSampleCounts = new bool[allSampleCounts.Length];

for (int i = 0; i < allSampleCounts.Length; i++)
{
TextureSampleCount count = allSampleCounts[i];
uint uintValue = FormatHelpers.GetSampleCountUInt32(count);

if (_device.supportsTextureSampleCount((UIntPtr)uintValue))
{
_supportedSampleCounts[i] = true;
Expand Down Expand Up @@ -235,16 +232,14 @@ private protected override void SubmitCommandsCore(CommandList commandList, Fenc
{
MTLCommandList mtlCL = Util.AssertSubtype<CommandList, MTLCommandList>(commandList);

if (fence != null)
{
MTLFence mtlFence = Util.AssertSubtype<Fence, MTLFence>(fence);
mtlCL.CommandBuffer.encodeSignalEvent(mtlFence.SharedEvent.NativePtr, MTLFence.SIGNALED);
}

mtlCL.CommandBuffer.addCompletedHandler(_completionBlockLiteral);

lock (_submittedCommandsLock)
{
if (fence != null)
{
mtlCL.SetCompletionFence(Util.AssertSubtype<Fence, MTLFence>(fence));
}

_submittedCLs.Add(mtlCL.CommandBuffer, mtlCL);
_latestSubmittedCB = mtlCL.Commit();
}
Expand Down Expand Up @@ -310,7 +305,6 @@ private protected override bool GetPixelFormatSupportCore(
uint maxWidth;
uint maxHeight;
uint maxDepth;

if (type == TextureType.Texture1D)
{
maxWidth = MTLFormats.GetMaxTexture1DWidth(maxFeatureSet);
Expand All @@ -320,7 +314,6 @@ private protected override bool GetPixelFormatSupportCore(
else if (type == TextureType.Texture2D)
{
uint maxDimensions;

if ((usage & TextureUsage.Cubemap) != 0)
{
maxDimensions = MTLFormats.GetMaxTextureCubeDimensions(maxFeatureSet);
Expand Down Expand Up @@ -360,7 +353,6 @@ private protected override void SwapBuffersCore(Swapchain swapchain)
{
MTLSwapchain mtlSC = Util.AssertSubtype<Swapchain, MTLSwapchain>(swapchain);
IntPtr currentDrawablePtr = mtlSC.CurrentDrawable.NativePtr;

if (currentDrawablePtr != IntPtr.Zero)
{
using (NSAutoreleasePool.Begin())
Expand Down Expand Up @@ -402,7 +394,6 @@ private protected override void UpdateTextureCore(
uint arrayLayer)
{
MTLTexture mtlTex = Util.AssertSubtype<Texture, MTLTexture>(texture);

if (mtlTex.StagingBuffer.IsNull)
{
Texture stagingTex = ResourceFactory.CreateTexture(new TextureDescription(
Expand Down Expand Up @@ -441,7 +432,6 @@ private protected override void UpdateTextureCore(
private protected override void WaitForIdleCore()
{
MTLCommandBuffer lastCB = default(MTLCommandBuffer);

lock (_submittedCommandsLock)
{
lastCB = _latestSubmittedCB;
Expand Down Expand Up @@ -497,13 +487,11 @@ private MappedResource MapTexture(MTLTexture texture, MapMode mode, uint subreso
protected override void PlatformDispose()
{
WaitForIdle();

if (!_unalignedBufferCopyPipeline.IsNull)
{
_unalignedBufferCopyShader.Dispose();
ObjectiveCRuntime.release(_unalignedBufferCopyPipeline.NativePtr);
}

_mainSwapchain?.Dispose();
ObjectiveCRuntime.release(_commandQueue.NativePtr);
ObjectiveCRuntime.release(_device.NativePtr);
Expand All @@ -530,13 +518,70 @@ protected override void UnmapCore(MappableResource resource, uint subresource)
{
}

public override bool WaitForFence(Fence fence, ulong nanosecondTimeout) =>
// this can be supported by setting up a MTLSharedEventListener and waiting for a signal by the GPU.
throw new NotImplementedException("Waiting for fences on Metal is not implemented yet.");
public override bool WaitForFence(Fence fence, ulong nanosecondTimeout)
{
return Util.AssertSubtype<Fence, MTLFence>(fence).Wait(nanosecondTimeout);
}

public override bool WaitForFences(Fence[] fences, bool waitAll, ulong nanosecondTimeout)
{
int msTimeout;
if (nanosecondTimeout == ulong.MaxValue)
{
msTimeout = -1;
}
else
{
msTimeout = (int)Math.Min(nanosecondTimeout / 1_000_000, int.MaxValue);
}

ManualResetEvent[] events = GetResetEventArray(fences.Length);
for (int i = 0; i < fences.Length; i++)
{
events[i] = Util.AssertSubtype<Fence, MTLFence>(fences[i]).ResetEvent;
}
bool result;
if (waitAll)
{
result = WaitHandle.WaitAll(events, msTimeout);
}
else
{
int index = WaitHandle.WaitAny(events, msTimeout);
result = index != WaitHandle.WaitTimeout;
}

ReturnResetEventArray(events);

return result;
}

private ManualResetEvent[] GetResetEventArray(int length)
{
lock (_resetEventsLock)
{
for (int i = _resetEvents.Count - 1; i > 0; i--)
{
ManualResetEvent[] array = _resetEvents[i];
if (array.Length == length)
{
_resetEvents.RemoveAt(i);
return array;
}
}
}

ManualResetEvent[] newArray = new ManualResetEvent[length];
return newArray;
}

public override bool WaitForFences(Fence[] fences, bool waitAll, ulong nanosecondTimeout) =>
// this can be supported by setting up a MTLSharedEventListener and waiting for a signal by the GPU.
throw new NotImplementedException("Waiting for fences on Metal is not implemented yet.");
private void ReturnResetEventArray(ManualResetEvent[] array)
{
lock (_resetEventsLock)
{
_resetEvents.Add(array);
}
}

public override void ResetFence(Fence fence)
{
Expand All @@ -548,7 +593,6 @@ public override void ResetFence(Fence fence)
private static bool GetIsSupported()
{
bool result = false;

try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
Expand All @@ -562,7 +606,6 @@ private static bool GetIsSupported()
else
{
MTLDevice defaultDevice = MTLDevice.MTLCreateSystemDefaultDevice();

if (defaultDevice.NativePtr != IntPtr.Zero)
{
result = true;
Expand All @@ -586,19 +629,17 @@ internal MTLComputePipelineState GetUnalignedBufferCopyPipeline()
if (_unalignedBufferCopyPipeline.IsNull)
{
MTLComputePipelineDescriptor descriptor = MTLUtil.AllocInit<MTLComputePipelineDescriptor>(
nameof(MTLComputePipelineDescriptor));
nameof(MTLComputePipelineDescriptor));
MTLPipelineBufferDescriptor buffer0 = descriptor.buffers[0];
buffer0.mutability = MTLMutability.Mutable;
MTLPipelineBufferDescriptor buffer1 = descriptor.buffers[1];
buffer0.mutability = MTLMutability.Mutable;

Debug.Assert(_unalignedBufferCopyShader == null);
string name = MetalFeatures.IsMacOS ? UnalignedBufferCopyPipelineMacOSName : UnalignedBufferCopyPipelineiOSName;

using (Stream resourceStream = typeof(MTLGraphicsDevice).Assembly.GetManifestResourceStream(name))
{
byte[] data = new byte[resourceStream.Length];

using (MemoryStream ms = new MemoryStream(data))
{
resourceStream.CopyTo(ms);
Expand All @@ -622,8 +663,6 @@ internal MTLComputePipelineState GetUnalignedBufferCopyPipeline()

internal sealed class MonoPInvokeCallbackAttribute : Attribute
{
public MonoPInvokeCallbackAttribute(Type t)
{
}
public MonoPInvokeCallbackAttribute(Type t) { }
}
}
2 changes: 1 addition & 1 deletion src/Veldrid/MTL/MTLResourceFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ protected override TextureView CreateTextureViewCore(ref TextureViewDescription

public override Fence CreateFence(bool signaled)
{
return new MTLFence(signaled, _gd);
return new MTLFence(signaled);
}

public override Swapchain CreateSwapchain(ref SwapchainDescription description)
Expand Down

0 comments on commit 9166e43

Please sign in to comment.