Skip to content

Commit

Permalink
Apply manual cleanups to OpenGL backend
Browse files Browse the repository at this point in the history
  • Loading branch information
smoogipoo committed Apr 30, 2024
1 parent b1d2c50 commit 2f73c98
Show file tree
Hide file tree
Showing 15 changed files with 86 additions and 112 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -623,7 +623,7 @@ private struct EntryStorageBlock : IEquatable<EntryStorageBlock>
{
private const int default_storage_block_size = 40000;
private readonly byte[] bytes;
private readonly GCHandle gcHandle;
private GCHandle gcHandle;
public readonly byte* BasePtr;

private uint unusedStart;
Expand Down Expand Up @@ -683,7 +683,7 @@ internal struct Tracked<T> where T : class
{
private readonly int index;

public T Get(List<object> list)
public readonly T Get(List<object> list)
{
return (T)list[index];
}
Expand Down
13 changes: 7 additions & 6 deletions src/Veldrid/OpenGL/OpenGLBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,14 @@ public void CreateGLResources()

if (gd.Extensions.ArbDirectStateAccess)
{
uint buffer;
glCreateBuffers(1, &buffer);
uint b;
glCreateBuffers(1, &b);
CheckLastError();
this.buffer = buffer;

buffer = b;

glNamedBufferData(
this.buffer,
buffer,
SizeInBytes,
null,
dynamic ? BufferUsageHint.DynamicDraw : BufferUsageHint.StaticDraw);
Expand All @@ -104,8 +105,8 @@ public void CreateGLResources()

public void DestroyGLResources()
{
uint buffer = this.buffer;
glDeleteBuffers(1, ref buffer);
uint b = buffer;
glDeleteBuffers(1, ref b);
CheckLastError();
}
}
Expand Down
9 changes: 4 additions & 5 deletions src/Veldrid/OpenGL/OpenGLCommandExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -580,11 +580,10 @@ public void UpdateBuffer(DeviceBuffer buffer, uint bufferOffsetInBytes, IntPtr d
}
else
{
var bufferTarget = BufferTarget.CopyWriteBuffer;
glBindBuffer(bufferTarget, glBuffer.Buffer);
glBindBuffer(BufferTarget.CopyWriteBuffer, glBuffer.Buffer);
CheckLastError();
glBufferSubData(
bufferTarget,
BufferTarget.CopyWriteBuffer,
(IntPtr)bufferOffsetInBytes,
sizeInBytes,
dataPtr.ToPointer());
Expand Down Expand Up @@ -625,7 +624,7 @@ public void UpdateTexture(

// Compressed textures can specify regions that are larger than the dimensions.
// We should only pass up to the dimensions to OpenGL, though.
Util.GetMipDimensions(glTex, mipLevel, out uint mipWidth, out uint mipHeight, out uint mipDepth);
Util.GetMipDimensions(glTex, mipLevel, out uint mipWidth, out uint mipHeight, out uint _);
width = Math.Min(width, mipWidth);
height = Math.Min(height, mipHeight);

Expand Down Expand Up @@ -1705,7 +1704,7 @@ private void copyRoundabout(
textureSamplerManager.SetTextureTransient(dstTarget, dstGLTexture.Texture);
CheckLastError();

Util.GetMipDimensions(srcGLTexture, srcMipLevel, out uint mipWidth, out uint mipHeight, out uint mipDepth);
Util.GetMipDimensions(srcGLTexture, srcMipLevel, out uint mipWidth, out uint mipHeight, out uint _);
uint fullRowPitch = FormatHelpers.GetRowPitch(mipWidth, srcGLTexture.Format);
uint fullDepthPitch = FormatHelpers.GetDepthPitch(
fullRowPitch,
Expand Down
2 changes: 1 addition & 1 deletion src/Veldrid/OpenGL/OpenGLCommandList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ private IOpenGLCommandEntryList getFreeCommandList()
{
if (availableLists.Count > 0)
{
var ret = availableLists[availableLists.Count - 1];
var ret = availableLists[^1];
availableLists.RemoveAt(availableLists.Count - 1);
return ret;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Veldrid/OpenGL/OpenGLExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ internal OpenGLExtensions(HashSet<string> extensions, GraphicsBackend backend, i
ArbDirectStateAccess = IsExtensionSupported("GL_ARB_direct_state_access");
ArbMultiBind = IsExtensionSupported("GL_ARB_multi_bind");
ArbTextureView = GLVersion(4, 3) || IsExtensionSupported("GL_ARB_texture_view") // OpenGL 4.3
|| IsExtensionSupported("GL_OES_texture_view");
|| IsExtensionSupported("GL_OES_texture_view");
CopyImage = IsExtensionSupported("GL_ARB_copy_image")
|| GLESVersion(3, 2)
|| IsExtensionSupported("GL_OES_copy_image")
Expand Down
12 changes: 5 additions & 7 deletions src/Veldrid/OpenGL/OpenGLFramebuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,16 +110,13 @@ public void CreateGLResources()
CheckLastError();
}

uint depthTextureID = 0;
var depthTarget = TextureTarget.Texture2D;

if (DepthTarget != null)
{
var glDepthTex = Util.AssertSubtype<Texture, OpenGLTexture>(DepthTarget.Value.Target);
glDepthTex.EnsureResourcesCreated();
depthTarget = glDepthTex.TextureTarget;

depthTextureID = glDepthTex.Texture;
var depthTarget = glDepthTex.TextureTarget;
uint depthTextureID = glDepthTex.Texture;

gd.TextureSamplerManager.SetTextureTransient(depthTarget, glDepthTex.Texture);
CheckLastError();
Expand Down Expand Up @@ -163,8 +160,9 @@ public void DestroyGLResources()
if (!disposed)
{
disposed = true;
uint framebuffer = this.framebuffer;
glDeleteFramebuffers(1, ref framebuffer);

uint f = framebuffer;
glDeleteFramebuffers(1, ref f);
CheckLastError();
}
}
Expand Down
77 changes: 37 additions & 40 deletions src/Veldrid/OpenGL/OpenGLGraphicsDevice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
Expand Down Expand Up @@ -89,7 +90,6 @@ private readonly Dictionary<MappedResourceCacheKey, MappedResourceInfoWithStagin
private uint vao;
private IntPtr glContext;
private Action<IntPtr> makeCurrent;
private Func<IntPtr> getCurrentContext;
private Action<IntPtr> deleteContext;
private Action swapBuffers;
private Action<bool> setSyncToVBlank;
Expand All @@ -101,8 +101,8 @@ private readonly Dictionary<MappedResourceCacheKey, MappedResourceInfoWithStagin

private TextureSampleCount maxColorTextureSamples;
private uint maxTextureSize;
private uint maxTexDepth;
private uint maxTexArrayLayers;
private uint maxTextureDepth;
private uint maxTextureArrayLayers;
private uint minUboOffsetAlignment;
private uint minSsboOffsetAlignment;
private BlockingCollection<ExecutionThreadWorkItem> workItems;
Expand Down Expand Up @@ -167,10 +167,10 @@ public override bool WaitForFences(Fence[] fences, bool waitAll, ulong nanosecon
bool result;

if (waitAll)
result = WaitHandle.WaitAll(events, msTimeout);
result = WaitHandle.WaitAll(events.Cast<WaitHandle>().ToArray(), msTimeout);
else
{
int index = WaitHandle.WaitAny(events, msTimeout);
int index = WaitHandle.WaitAny(events.Cast<WaitHandle>().ToArray(), msTimeout);
result = index != WaitHandle.WaitTimeout;
}

Expand Down Expand Up @@ -327,7 +327,6 @@ private void init(
syncToVBlank = options.SyncToVerticalBlank;
glContext = platformInfo.OpenGLContextHandle;
makeCurrent = platformInfo.MakeCurrent;
getCurrentContext = platformInfo.GetCurrentContext;
deleteContext = platformInfo.DeleteContext;
swapBuffers = platformInfo.SwapBuffers;
setSyncToVBlank = platformInfo.SetSyncToVerticalBlank;
Expand All @@ -336,7 +335,7 @@ private void init(
ShadingLanguageVersion = Util.GetString(glGetString(StringName.ShadingLanguageVersion));
vendorName = Util.GetString(glGetString(StringName.Vendor));
deviceName = Util.GetString(glGetString(StringName.Renderer));
backendType = Version.StartsWith("OpenGL ES") ? GraphicsBackend.OpenGLES : GraphicsBackend.OpenGL;
backendType = Version.StartsWith("OpenGL ES", StringComparison.Ordinal) ? GraphicsBackend.OpenGLES : GraphicsBackend.OpenGL;

LoadAllFunctions(glContext, platformInfo.GetProcAddress, backendType == GraphicsBackend.OpenGLES);

Expand Down Expand Up @@ -445,34 +444,30 @@ private void init(
TextureSamplerManager = new OpenGLTextureSamplerManager(Extensions);
commandExecutor = new OpenGLCommandExecutor(this, platformInfo);

int maxColorTextureSamples;
int maxColorTextureSamplesInt;

if (backendType == GraphicsBackend.OpenGL)
{
glGetIntegerv(GetPName.MaxColorTextureSamples, &maxColorTextureSamples);
glGetIntegerv(GetPName.MaxColorTextureSamples, &maxColorTextureSamplesInt);
CheckLastError();
}
else
{
glGetIntegerv(GetPName.MaxSamples, &maxColorTextureSamples);
glGetIntegerv(GetPName.MaxSamples, &maxColorTextureSamplesInt);
CheckLastError();
}

if (maxColorTextureSamples >= 32)
this.maxColorTextureSamples = TextureSampleCount.Count32;
else if (maxColorTextureSamples >= 16)
this.maxColorTextureSamples = TextureSampleCount.Count16;
else if (maxColorTextureSamples >= 8)
this.maxColorTextureSamples = TextureSampleCount.Count8;
else if (maxColorTextureSamples >= 4)
this.maxColorTextureSamples = TextureSampleCount.Count4;
else if (maxColorTextureSamples >= 2)
this.maxColorTextureSamples = TextureSampleCount.Count2;
else
this.maxColorTextureSamples = TextureSampleCount.Count1;
maxColorTextureSamples = maxColorTextureSamplesInt switch
{
>= 32 => TextureSampleCount.Count32,
>= 16 => TextureSampleCount.Count16,
>= 8 => TextureSampleCount.Count8,
>= 4 => TextureSampleCount.Count4,
>= 2 => TextureSampleCount.Count2,
_ => TextureSampleCount.Count1
};

int maxTexSize;

glGetIntegerv(GetPName.MaxTextureSize, &maxTexSize);
CheckLastError();

Expand All @@ -492,8 +487,8 @@ private void init(
}

maxTextureSize = (uint)maxTexSize;
this.maxTexDepth = (uint)maxTexDepth;
this.maxTexArrayLayers = (uint)maxTexArrayLayers;
maxTextureDepth = (uint)maxTexDepth;
maxTextureArrayLayers = (uint)maxTexArrayLayers;

mainSwapchain = new OpenGLSwapchain(
this,
Expand Down Expand Up @@ -633,9 +628,9 @@ private void initializeUIView(GraphicsDeviceOptions options, IntPtr uIViewPtr)
CheckLastError();

uint depthRb = 0;
bool hasDepth = options.SwapchainDepthFormat != null;
PixelFormat? depthFormat = options.SwapchainDepthFormat;

if (hasDepth)
if (depthFormat != null)
{
glGenRenderbuffers(1, out depthRb);
CheckLastError();
Expand All @@ -645,7 +640,7 @@ private void initializeUIView(GraphicsDeviceOptions options, IntPtr uIViewPtr)

glRenderbufferStorage(
RenderbufferTarget.Renderbuffer,
(uint)OpenGLFormats.VdToGLSizedInternalFormat(options.SwapchainDepthFormat.Value, true),
(uint)OpenGLFormats.VdToGLSizedInternalFormat(depthFormat.Value, true),
(uint)fbWidth,
(uint)fbHeight);
CheckLastError();
Expand All @@ -670,7 +665,7 @@ private void initializeUIView(GraphicsDeviceOptions options, IntPtr uIViewPtr)
if (!EaglContext.SetCurrentContext(ctx)) throw new VeldridException("Unable to set the thread's current GL context.");
};

Action swapBuffers = () =>
Action swapBuffersFunc = () =>
{
glBindRenderbuffer(RenderbufferTarget.Renderbuffer, colorRb);
CheckLastError();
Expand Down Expand Up @@ -712,15 +707,15 @@ private void initializeUIView(GraphicsDeviceOptions options, IntPtr uIViewPtr)
out int newHeight);
CheckLastError();

if (hasDepth)
if (depthFormat != null)
{
Debug.Assert(depthRb != 0);
glBindRenderbuffer(RenderbufferTarget.Renderbuffer, depthRb);
CheckLastError();

glRenderbufferStorage(
RenderbufferTarget.Renderbuffer,
(uint)OpenGLFormats.VdToGLSizedInternalFormat(options.SwapchainDepthFormat.Value, true),
(uint)OpenGLFormats.VdToGLSizedInternalFormat(depthFormat.Value, true),
(uint)newWidth,
(uint)newHeight);
CheckLastError();
Expand All @@ -743,7 +738,7 @@ private void initializeUIView(GraphicsDeviceOptions options, IntPtr uIViewPtr)
() => EaglContext.CurrentContext.NativePtr,
() => setCurrentContext(IntPtr.Zero),
destroyContext,
swapBuffers,
swapBuffersFunc,
syncInterval => { },
setSwapchainFramebuffer,
resizeSwapchain);
Expand Down Expand Up @@ -807,19 +802,19 @@ private void initializeANativeWindow(
IntPtr context = eglCreateContext(display, bestConfig, IntPtr.Zero, contextAttribs);
if (context == IntPtr.Zero) throw new VeldridException("Failed to create an EGLContext: " + eglGetError());

Action<IntPtr> makeCurrent = ctx =>
Action<IntPtr> makeCurrentFunc = ctx =>
{
if (eglMakeCurrent(display, eglWindowSurface, eglWindowSurface, ctx) == 0) throw new VeldridException($"Failed to make the EGLContext {ctx} current: {eglGetError()}");
};

makeCurrent(context);
makeCurrentFunc(context);

Action clearContext = () =>
{
if (eglMakeCurrent(display, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) == 0) throw new VeldridException("Failed to clear the current EGLContext: " + eglGetError());
};

Action swapBuffers = () =>
Action swapBuffersFunc = () =>
{
if (eglSwapBuffers(display, eglWindowSurface) == 0) throw new VeldridException("Failed to swap buffers: " + eglGetError());
};
Expand All @@ -840,11 +835,11 @@ private void initializeANativeWindow(
var platformInfo = new OpenGLPlatformInfo(
context,
eglGetProcAddress,
makeCurrent,
makeCurrentFunc,
eglGetCurrentContext,
clearContext,
destroyContext,
swapBuffers,
swapBuffersFunc,
setSync);

init(options, platformInfo, swapchainDescription.Width, swapchainDescription.Height, true);
Expand Down Expand Up @@ -975,9 +970,9 @@ private protected override bool GetPixelFormatSupportCore(
properties = new PixelFormatProperties(
maxTextureSize,
type == TextureType.Texture1D ? 1 : maxTextureSize,
type != TextureType.Texture3D ? 1 : maxTexDepth,
type != TextureType.Texture3D ? 1 : maxTextureDepth,
uint.MaxValue,
type == TextureType.Texture3D ? 1 : maxTexArrayLayers,
type == TextureType.Texture3D ? 1 : maxTextureArrayLayers,
sampleCounts);
return true;
}
Expand Down Expand Up @@ -1280,7 +1275,7 @@ private void executeWorkItem(ExecutionThreadWorkItem workItem)

case WorkItemType.SetSyncToVerticalBlank:
{
bool value = workItem.UInt0 == 1 ? true : false;
bool value = workItem.UInt0 == 1;
gd.setSyncToVBlank(value);
}
break;
Expand Down Expand Up @@ -1695,6 +1690,8 @@ private struct ExecutionThreadWorkItem
public readonly object Object1;
public readonly uint UInt0;
public readonly uint UInt1;

// ReSharper disable once NotAccessedField.Local
public readonly uint UInt2;

public ExecutionThreadWorkItem(
Expand Down
2 changes: 0 additions & 2 deletions src/Veldrid/OpenGL/OpenGLPipeline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,6 @@ private void processResourceSetLayouts(ResourceLayout[] layouts)
{
int resourceLayoutCount = layouts.Length;
setInfos = new SetBindingsInfo[resourceLayoutCount];
int lastTextureLocation = -1;
int relativeTextureIndex = -1;
int relativeImageIndex = -1;
uint storageBlockIndex = 0; // Tracks OpenGL ES storage buffers.
Expand Down Expand Up @@ -239,7 +238,6 @@ private void processResourceSetLayouts(ResourceLayout[] layouts)
int location = getUniformLocation(resource.Name);
relativeTextureIndex += 1;
textureBindings[i] = new OpenGLTextureBindingSlotInfo { RelativeIndex = relativeTextureIndex, UniformLocation = location };
lastTextureLocation = location;
samplerTrackedRelativeTextureIndices.Add(relativeTextureIndex);
}
else if (resource.Kind == ResourceKind.TextureReadWrite)
Expand Down
4 changes: 2 additions & 2 deletions src/Veldrid/OpenGL/OpenGLSampler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ public void EnsureResourcesCreated()

if (gd.Extensions.KhrDebug)
{
SetObjectLabel(ObjectLabelIdentifier.Sampler, noMipmapState.Sampler, string.Format("{0}_WithoutMipmapping", name));
SetObjectLabel(ObjectLabelIdentifier.Sampler, mipmapState.Sampler, string.Format("{0}_WithMipmapping", name));
SetObjectLabel(ObjectLabelIdentifier.Sampler, noMipmapState.Sampler, $"{name}_WithoutMipmapping");
SetObjectLabel(ObjectLabelIdentifier.Sampler, mipmapState.Sampler, $"{name}_WithMipmapping");
}
}
}
Expand Down
Loading

0 comments on commit 2f73c98

Please sign in to comment.