daily update on 20240828 by nitload youmu, autotexture added

This commit is contained in:
Nitload
2024-08-28 10:58:31 +08:00
parent d082071f2d
commit 1ee4e4a42f
586 changed files with 60910 additions and 123106 deletions
@@ -0,0 +1,161 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="AutoTexture.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// 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.
//
// 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.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using StgSharp.Collections;
namespace StgSharp.Graphics.OpenGL
{
public sealed class AutoTextureGL
{
private BidirectionalDictionary<Image, int> imageIndexMap = new BidirectionalDictionary<Image, int>();
private Dictionary<Image, int> imageUpdateIndex = new Dictionary<Image, int>();
private int _size, _currentIndex;
private LinkedList<int> usedTextureIndex;
private Queue<int> unusedTextureUnitIndex;
private TextureProperty[] propertyCache;
private TextureGL texturePackage;
private TextureProperty _textureProperty;
private OpenGLFunction GL
{
get => texturePackage.GL;
}
private AutoTextureGL(TextureGL texture)
{
texturePackage = texture;
_size = texture.Count;
imageIndexMap = new BidirectionalDictionary<Image, int>();
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range(0, _size));
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
public AutoTextureGL(int textureObjectSize, [NotNull]glRenderStream binding)
{
this._size = textureObjectSize;
imageIndexMap = new BidirectionalDictionary<Image, int>();
texturePackage = new TextureGL(textureObjectSize, binding);
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range(0, _size));
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
public TextureProperty DefaultTextureProperty
{
get => _textureProperty;
set => _textureProperty = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SelectTextureAndBind(Image i)
{
TextureProperty property = _textureProperty;
SelectTextureAndBind(i, property);
}
public void SelectTextureAndBind([NotNull]Image i, TextureProperty property)
{
//usable texture with image match
if (imageIndexMap.TryGetValue(i, out int index))
{
//prop setting match
if (propertyCache[index] == property)
{
_currentIndex = index; //GL.Assert(true);
texturePackage.Bind2D(index); //GL.Assert(true);
if (i.PixelUpdateCount != imageUpdateIndex[i])
{
texturePackage.LoadTexture(index, i); //GL.Assert(true);
}
}
else
{
_currentIndex = index; //GL.Assert(true);
texturePackage.Bind2D(index); //GL.Assert(true);
texturePackage.Set2dProperty(index, property); //GL.Assert(true);
if (i.PixelUpdateCount != imageUpdateIndex[i])
{
texturePackage.LoadTexture(index, i); //GL.Assert(true);
}
}
}
else
{
if (unusedTextureUnitIndex.TryDequeue(out int newIndex))
{
//has extra unused texture object
imageIndexMap.Add(i, index);
texturePackage.Bind2D(index);
texturePackage.Set2dProperty(index, property);
texturePackage.LoadTexture(index, i);
usedTextureIndex.AddLast(newIndex);
propertyCache[newIndex] = property;
imageUpdateIndex[i] = i.PixelUpdateCount;
}
else
{
//recycle from current
int reusedIndex = usedTextureIndex.First!.Value;
usedTextureIndex.RemoveFirst();
usedTextureIndex.AddLast(reusedIndex);
imageIndexMap[i] = reusedIndex;
propertyCache[newIndex] = property;
imageUpdateIndex[i] = i.PixelUpdateCount;
}
}
}
public static AutoTextureGL ToAuto([NotNull]TextureGL texture)
{
if (texture.IndexOfCurrentTexture != -1)
{
throw new InvalidOperationException("Texture to be converted has been editted.");
}
return new AutoTextureGL(texture);
}
}
}
@@ -45,10 +45,10 @@ namespace StgSharp.Graphics.OpenGL
/// Each <see langword="uint"/> value indexed from instance of this class this
/// is the only handle to one Element Buffer Object.
/// </summary>
public unsafe class ElementBuffer : GlBufferObjectBase
public sealed unsafe class ElementBuffer : GlBufferObjectBase
{
internal ElementBuffer(int n, glRenderStream binding):base(binding)
internal ElementBuffer(int n, glRenderStream binding) : base(binding)
{
_bufferHandle = GL.GenBuffers(n);
}
@@ -1,4 +1,34 @@
using StgSharp.Graphics.OpenGL;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="FBO.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// 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.
//
// 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.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -12,7 +42,7 @@ namespace StgSharp.Graphics.OpenGL
{
#pragma warning disable CA1008
#pragma warning disable CA1028
public enum FrameBufferTarget:uint
public enum FrameBufferTarget : uint
#pragma warning restore CA1028
#pragma warning restore CA1008
{
@@ -21,9 +51,10 @@ namespace StgSharp.Graphics.OpenGL
Draw = GLconst.DRAW_FRAMEBUFFER,
}
public class FrameBuffer : GlBufferObjectBase
public sealed class FrameBuffer : GlBufferObjectBase
{
internal unsafe FrameBuffer(int count, glRenderStream binding):base(binding)
internal unsafe FrameBuffer(int count, glRenderStream binding) : base(binding)
{
_bufferHandle = GL.GenFrameBuffers(count);
}
@@ -34,15 +65,9 @@ namespace StgSharp.Graphics.OpenGL
/// </summary>
/// <param name="index">Index of object to be binded in handle set</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe override void Bind(int index)
public override unsafe void Bind(int index)
{
GL.BindFrameBuffer(FrameBufferTarget.All,_bufferHandle[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindNull()
{
GlFunction.CurrentGL.BindFrameBuffer(FrameBufferTarget.All,GlHandle.Zero);
GL.BindFrameBuffer(FrameBufferTarget.All, _bufferHandle[index]);
}
/// <summary>
@@ -57,9 +82,16 @@ namespace StgSharp.Graphics.OpenGL
GL.BindFrameBuffer(target, _bufferHandle[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindNull()
{
OpenGLFunction.CurrentGL.BindFrameBuffer(FrameBufferTarget.All, GlHandle.Zero);
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
}
}
@@ -1,4 +1,34 @@
using StgSharp.Graphics.OpenGL;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLBufferObjectBase.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// 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.
//
// 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.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -8,6 +38,7 @@ namespace StgSharp.Graphics.OpenGL
{
public abstract class GlBufferObjectBase : BufferObjectBase
{
private readonly glRenderStream _contextBinding;
protected GlBufferObjectBase(glRenderStream contextBinding)
@@ -16,7 +47,7 @@ namespace StgSharp.Graphics.OpenGL
_contextBinding = contextBinding;
}
protected GlFunction GL => _contextBinding.GL;
protected OpenGLFunction GL => _contextBinding.GL;
}
}
@@ -1,4 +1,34 @@
using StgSharp.Graphics.OpenGL;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="RBO.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// 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.
//
// 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.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -11,9 +41,10 @@ namespace StgSharp.Graphics.OpenGL
public class RenderBuffer : GlBufferObjectBase
public sealed class RenderBuffer : GlBufferObjectBase
{
public RenderBuffer(int count, glRenderStream binding):base(binding)
public RenderBuffer(int count, glRenderStream binding) : base(binding)
{
_bufferHandle = GL.GenRenderBuffer(count);
}
@@ -23,17 +54,18 @@ namespace StgSharp.Graphics.OpenGL
GL.BindRenderBuffer(this[index]);
}
public void Store(RenderBufferInternalFormat format, (int width, int height) size)
{
if ((size.width > binding.Width) || (size.height > binding.Height))
{
StgSharp.LogWarning("FrameBuffer is larger than current canvas binding");
}
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
public void Store(RenderBufferInternalFormat format, (int width,int height) size)
{
if (size.width > binding.Width || size.height>binding.Height)
{
StgSharp.LogWarning("FrameBuffer is larger than current canvas binding");
}
}
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="texture.cs"
// file="TextureGL.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -28,104 +28,230 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
public unsafe class TextureGL
public sealed unsafe class TextureGL
{
private GlFunction GL;
internal static bool[] unitActivated = new bool[16];
private int currentEditingTextureIndex;
private OpenGLFunction _gl;
internal GlHandle[] _textureHandle;
internal Image[] sourceList;
public GlHandle this[int index]
internal TextureGL( int count, glRenderStream binding )
{
get => _textureHandle[index];
//sourceList = new Image[count];
this._gl = binding.GL;
_textureHandle = _gl.GenTextures( count );
}
internal TextureGL(int n, glRenderStream binding)
internal OpenGLFunction GL => _gl;
public GlHandle this[ int index ]
{
sourceList = new Image[n];
this.GL = binding.GL;
_textureHandle = GL.GenTextures(n);
get => _textureHandle[ index ];
}
public void ActivateAs(TextureUnit unit)
public int Count
{
GL.ActiveTexture((uint)unit);
get => _textureHandle.Length;
}
public void Bind2D(int index)
//internal Image[] sourceList;
public int IndexOfCurrentTexture
{
GL.BindTexture(GLconst.TEXTURE_2D, _textureHandle[index]);
get => currentEditingTextureIndex;
}
public void ActivateAs( TextureUnit unit ) { _gl.ActiveTextureUnit( ( uint )unit ); }
public void Bind2D( int index )
{
currentEditingTextureIndex = index;
_gl.BindTexture( GLconst.TEXTURE_2D, _textureHandle[ index ] );
}
/// <summary>
/// Load an <see cref="Image"/> to certain texture.
/// Load an <see cref="Image" /> to certain texture.
/// </summary>
/// <param name="index"> </param>
/// <param name="i"> </param>
public unsafe void LoadTexture(int index, Image i)
public unsafe void LoadTexture( int index, Image i )
{
sourceList[index] = i;
var handle = sourceList[index].PixelBuffer;
GL.TextureImage2d(
Texture2DTarget.Texture2D, 0, (uint)i.Channel,
(uint)sourceList[index].Width, (uint)sourceList[index].Height,
(uint)i.Channel, i.PixelLayout,
pixels: handle
);
GL.GenerateMipmap(Texture2DTarget.Texture2D);
byte[] handle = i.PixelBuffer;
_gl.TextureImage2d(
Texture2DTarget.Texture2D, 0, ( uint )i.Channel, ( uint )i.Width, ( uint )i.Height,
( uint )i.Channel, i.PixelLayout, pixels: handle );
_gl.GenerateMipmap( Texture2DTarget.Texture2D );
}
#region texture setting
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dFilterProperty(
Filter onMinify, Filter onMagnify)
int index,
TextureFilter onMinify,
TextureFilter onMagnify )
{
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MIN_FILTER, (int)onMinify);
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MAG_FILTER, (int)onMagnify);
#if DEBUG
if( index != currentEditingTextureIndex )
{
throw new InvalidOperationException(
"Texture to be editted is not the one being activated." );
}
#endif
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_MIN_FILTER, ( int )onMinify );
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_MAG_FILTER, ( int )onMagnify );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dWrapProperty(
Wrap onHorizontial, Wrap onVertical)
int index,
TextureWrap onHorizontial,
TextureWrap onVertical )
{
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_S, (int)onHorizontial);
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_T, (int)onVertical);
#if DEBUG
if( index != currentEditingTextureIndex )
{
throw new InvalidOperationException(
"Texture to be editted is not the one being activated." );
}
#endif
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_S, ( int )onHorizontial );
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_T, ( int )onVertical );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dProperty( int index, TextureProperty property )
{
Set2dFilterProperty( index, property.FilterOnMinify, property.FilterOnMagnify );
Set2dWrapProperty( index, property.WrapOnHorizontial, property.WrapOnVertical );
}
#endregion texture setting
}
#pragma warning disable CA1008
public enum Filter
#pragma warning restore CA1008
[StructLayout( LayoutKind.Explicit )]
public struct TextureProperty
{
[FieldOffset( 0 )] private M128 mask;
[FieldOffset( 0 )] private TextureFilter mag;
[FieldOffset( 4 )] private TextureFilter min;
[FieldOffset( 8 )] private TextureWrap hori;
[FieldOffset( 12 )] private TextureWrap vert;
public TextureProperty(
TextureFilter onMagnify,
TextureFilter onMinify,
TextureWrap onHorizontial,
TextureWrap onVertical )
{
FilterOnMagnify = onMagnify;
FilterOnMinify = onMinify;
WrapOnHorizontial = onHorizontial;
WrapOnVertical = onVertical;
}
public TextureFilter FilterOnMagnify
{
get => mag;
set => mag = value;
}
public TextureFilter FilterOnMinify
{
get => min;
set => min = value;
}
public TextureWrap WrapOnHorizontial
{
get => hori;
set => hori = value;
}
public TextureWrap WrapOnVertical
{
get => vert;
set => vert = value;
}
public override int GetHashCode()
{
return HashCode.Combine(
FilterOnMagnify, FilterOnMagnify, WrapOnHorizontial, WrapOnVertical );
}
public override bool Equals([NotNullWhen(true)] object obj)
{
return base.Equals(obj);
}
public override string ToString()
{
return $"FilterOnMagnify:{FilterOnMagnify}, " +
$"FilterOnMagnify:{FilterOnMagnify}, " +
$"WrapOnHorizontial:{WrapOnHorizontial}, " +
$"WrapOnVertical:{WrapOnVertical}";
}
public static implicit operator TextureProperty(
(
TextureFilter onMagnify, TextureFilter onMinify,
TextureWrap onHorizontial, TextureWrap onVertical
) propertyValueTuple )
{
return new TextureProperty(
propertyValueTuple.onMagnify, propertyValueTuple.onMinify,
propertyValueTuple.onHorizontial, propertyValueTuple.onVertical );
}
public static bool operator ==(TextureProperty left, TextureProperty right)
{
return left.mask == right.mask;
}
public static bool operator !=(TextureProperty left, TextureProperty right)
{
return left.mask != right.mask;
}
}
#pragma warning disable CA1008
public enum TextureFilter
#pragma warning restore CA1008
{
Nearest = GLconst.NEAREST,
Linear = GLconst.LINEAR,
NearestLinearMipmap = GLconst.NEAREST_MIPMAP_LINEAR,
LinearLinearMipmap = GLconst.LINEAR_MIPMAP_LINEAR,
NearestNearestMipmap = GLconst.NEAREST_MIPMAP_NEAREST,
LinearNearestMipmap = GLconst.LINEAR_MIPMAP_NEAREST,
}
#pragma warning disable CA1008
#pragma warning disable CA1008
public enum TextureUnit
#pragma warning restore CA1008
#pragma warning restore CA1008
{
Unit0 = GLconst.TEXTURE0,
Unit1 = GLconst.TEXTURE1,
Unit2 = GLconst.TEXTURE2,
@@ -142,15 +268,18 @@ namespace StgSharp.Graphics.OpenGL
Unit13 = GLconst.TEXTURE13,
Unit14 = GLconst.TEXTURE14,
Unit15 = GLconst.TEXTURE15,
}
#pragma warning disable CA1008
public enum Wrap
#pragma warning restore CA1008
#pragma warning disable CA1008
public enum TextureWrap
#pragma warning restore CA1008
{
Repeat = GLconst.REPEAT,
MirroredRepeat = GLconst.MIRRORED_REPEAT,
ClampToEdge = GLconst.CLAMP_TO_EDGE,
ClampToBorder = GLconst.CLAMP_TO_BORDER,
}
}
@@ -37,10 +37,10 @@ using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public unsafe class VertexArray : GlBufferObjectBase
public sealed unsafe class VertexArray : GlBufferObjectBase
{
internal VertexArray(int n, glRenderStream binding):base(binding)
internal VertexArray(int n, glRenderStream binding) : base(binding)
{
_bufferHandle = GL.GenVertexArrays(n);
}
@@ -54,7 +54,7 @@ namespace StgSharp.Graphics.OpenGL
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindNull()
{
GlFunction.CurrentGL.BindVertexArray(GlHandle.Zero);
OpenGLFunction.CurrentGL.BindVertexArray(GlHandle.Zero);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -40,10 +40,10 @@ using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public unsafe class VertexBuffer : GlBufferObjectBase
public sealed unsafe class VertexBuffer : GlBufferObjectBase
{
internal VertexBuffer(int n, glRenderStream binding):base(binding)
internal VertexBuffer(int n, glRenderStream binding) : base(binding)
{
_bufferHandle = GL.GenBuffers(n);
}
@@ -54,13 +54,22 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set data to current vertex buffer object
///
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Unbind()
{
GL.BindBuffer(BufferType.ArrayBuffer, GlHandle.Zero);
}
/// <summary>
/// Set _data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="bufferData">Data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void WriteMatrixData<T>(int index, T bufferData, BufferUsage usage)
/// <param name="usage">How OpenGL use these _data, defined by <see cref="BufferUsage"/></param>
public void WriteMatrixData<T>(int index, T bufferData, BufferUsage usage)
where T : struct, IMat
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
@@ -68,12 +77,12 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set data to current vertex buffer object
/// Set _data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="bufferArray">Data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
/// <param name="usage">How OpenGL use these _data, defined by <see cref="BufferUsage"/></param>
public void WriteScalerData<T>(int index, T[] bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
@@ -87,12 +96,12 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set data to current vertex buffer object
/// Set _data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="scalerSpan">A <see cref="Span{T}"/> of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
/// <param name="scalerSpan">A <see cref="Span{T}"/> of _data to write in</param>
/// <param name="usage">How OpenGL use these _data, defined by <see cref="BufferUsage"/></param>
public void WriteScalerData<T>(int index, ReadOnlySpan<T> scalerSpan, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
@@ -106,12 +115,12 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set data to current vertex buffer object
/// Set _data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="vectorSpan">A <see cref="Span{T}"/> of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
/// <param name="vectorSpan">A <see cref="Span{T}"/> of _data to write in</param>
/// <param name="usage">How OpenGL use these _data, defined by <see cref="BufferUsage"/></param>
public void WriteVectorData<T>(int index, ReadOnlySpan<T> vectorSpan, BufferUsage usage) where T : struct, IVector
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
@@ -119,27 +128,18 @@ namespace StgSharp.Graphics.OpenGL
}
/// <summary>
/// Set data to current vertex buffer object
/// Set _data to current vertex buffer object
/// </summary>
/// <typeparam name="T">Type of bufferData</typeparam>
/// <param name="index">Index to find certain VBO in this instance</param>
/// <param name="vectorArray">A array of data to write in</param>
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
/// <param name="vectorArray">A array of _data to write in</param>
/// <param name="usage">How OpenGL use these _data, defined by <see cref="BufferUsage"/></param>
public void WriteVectorData<T>(int index, T[] vectorArray, BufferUsage usage) where T : struct, IVector
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferVectorData(BufferType.ArrayBuffer, vectorArray, usage);
}
/// <summary>
///
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Unbind()
{
GL.BindBuffer(BufferType.ArrayBuffer, GlHandle.Zero);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLresourceGenrator.cs"
// file="glResourceGenrator.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -51,6 +51,12 @@ namespace StgSharp.Graphics.OpenGL
return new ElementBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected FrameBuffer CreateFrameBuffer(int count)
{
return new FrameBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected RenderBuffer CreateRenderBuffer(int count)
@@ -58,12 +64,6 @@ namespace StgSharp.Graphics.OpenGL
return new RenderBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected FrameBuffer CreateFrameBuffer(int count)
{
return new FrameBuffer(count, this);
}
/// <summary>
/// Create a sets of <see cref="TextureGL"/>
/// </summary>
@@ -75,6 +75,13 @@ namespace StgSharp.Graphics.OpenGL
return new TextureGL(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected AutoTextureGL CreateAutoTexture(int count)
{
return new AutoTextureGL(count, this);
}
/// <summary>
/// Create a set of <see cref="VertexArray"/>.
/// </summary>
@@ -97,6 +104,6 @@ namespace StgSharp.Graphics.OpenGL
return new VertexBuffer(count, this);
}
}
}
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glException.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// 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.
//
// 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.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
@@ -9,6 +39,7 @@ namespace StgSharp.Graphics.OpenGL
{
public sealed class GlExecutionException : Exception
{
public GlExecutionException()
{
}
@@ -21,10 +52,6 @@ namespace StgSharp.Graphics.OpenGL
public sealed class GlArrayFormatException : Exception
{
public GlArrayFormatException(PixelChannelLayout layout, string arrayname):
base($"{arrayname} cannot be used as layout of {layout}")
{
}
internal GlArrayFormatException(string message) : base(message)
{
@@ -37,22 +64,28 @@ namespace StgSharp.Graphics.OpenGL
internal GlArrayFormatException(string message, Exception innerException) : base(message, innerException)
{
}
public GlArrayFormatException(PixelChannelLayout layout, string arrayname) :
base($"{arrayname} cannot be used as layout of {layout}")
{
}
}
public static partial class GlHelper
{
public static bool CheckArrayFormat(this Array array, PixelChannelLayout layout)
{
return layout switch
{
PixelChannelLayout.Byte or PixelChannelLayout.UByte332 or PixelChannelLayout.UByte233Rev
=> array is byte[] || array is sbyte[],
=> (array is byte[]) || (array is sbyte[]),
PixelChannelLayout.Short => array is short[],
PixelChannelLayout.UShort => array is ushort[],
PixelChannelLayout.Int => array is int[],
PixelChannelLayout.Float => array is float[],
PixelChannelLayout.UShort4444 => array is ushort[] || array is byte[],
PixelChannelLayout.UByte => array is byte[] || array is sbyte[],
PixelChannelLayout.UShort4444 => (array is ushort[]) || (array is byte[]),
PixelChannelLayout.UByte => (array is byte[]) || (array is sbyte[]),
PixelChannelLayout.UInt => array is uint[],
PixelChannelLayout.UShort565 or
PixelChannelLayout.UShort565Rev or
+10 -9
View File
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLhandle.cs"
// file="GlHandle.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -49,24 +49,25 @@ namespace StgSharp.Graphics.OpenGL
[StructLayout(LayoutKind.Explicit, Size = 4)]
public struct GlHandle
{
[FieldOffset(0)] public uint Value;
[FieldOffset(0)] public int SignedValue;
[FieldOffset(0)] public uint Value;
public static GlHandle Zero
{
get => new GlHandle { Value = 0 };
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GlHandle Alloc(uint value)
{
return new GlHandle() { Value = value };
return new GlHandle { Value = value };
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GlHandle SignedAlloc(int value)
{
return new GlHandle() { SignedValue = value };
}
public static GlHandle Zero
{
get => new GlHandle() { Value = 0 };
return new GlHandle { SignedValue = value };
}
}
@@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class OpenGLAPICallingAttribute:Attribute
{
public OpenGLAPICallingAttribute()
{
}
}
}
@@ -1,4 +1,34 @@
using StgSharp.Graphics.OpenGL;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IglConvertable.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// 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.
//
// 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.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -10,26 +40,26 @@ namespace StgSharp.Graphics.ShaderEdit
{
public interface IglConvertable
{
/// <summary>
///
/// </summary>
public void SetAllUniforms();
/// <summary>
///
/// </summary>
public void GainAllUniforms(ShaderProgram source, params string[] uniformName);
/// <summary>
///
/// </summary>
public void DisplayGLtypeDefinition();
/// <summary>
///
/// </summary>
public void GainAllUniforms(ShaderProgram source, params string[] uniformName);
/// <summary>
///
/// </summary>
/// <returns></returns>
public ShaderStruct GetConvertedGLtype();
/// <summary>
///
/// </summary>
public void SetAllUniforms();
}
}
@@ -44,30 +44,31 @@ namespace StgSharp.Graphics.OpenGL
public abstract partial class glRenderStream : RenderStream
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected sealed override Shader CreateShaderSegment(ShaderType type, int count)
{
return new Shader( GL.CreateShaderSet(count, type), type, this);
}
/// <summary>
/// Create an instance of <see cref="Shader"/> program
/// </summary>
/// <returns>New instance of <see cref="Shader"/> instance. </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected sealed override ShaderProgram CreateShaderProgram()
protected override sealed ShaderProgram CreateShaderProgram()
{
return new ShaderProgram(this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override sealed Shader CreateShaderSegment(ShaderType type, int count)
{
return new Shader(GL.CreateShaderSet(count, type), type, this);
}
}
public class Shader : ISSDSerializable
{
private readonly GlFunction GL;
private readonly OpenGLFunction GL;
internal readonly GlHandle[] handle;
public readonly ShaderType type;
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.Shader;
internal unsafe Shader(GlHandle[] handle, ShaderType usage, glRenderStream stream)
{
this.handle = handle;
@@ -75,6 +76,8 @@ namespace StgSharp.Graphics.OpenGL
type = usage;
}
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.Shader;
/// <summary>
/// Attach one shader code to a shader program.
/// </summary>
@@ -86,14 +89,13 @@ namespace StgSharp.Graphics.OpenGL
GL.AttachShader(target.handle, handle[index]);
}
public static byte[] FromCodeFile(string fileRoute)
public void CheckStatus(int index, ShaderStatus status)
{
string str = File.ReadAllText(fileRoute);
if (string.IsNullOrEmpty(str))
string log = GL.GetShaderStatus(this, index, (int)status);
if (!string.IsNullOrEmpty(log))
{
throw new InvalidOperationException($"Cannot load and GLSL code from {fileRoute}");
throw new Exception($"{$"Shader Error \t{status}\n"}{log}");
}
return Encoding.UTF8.GetBytes(str);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -105,7 +107,7 @@ namespace StgSharp.Graphics.OpenGL
}
GL.LoadShaderSource(handle[index], codeStream);
GL.CompileShader(handle[index]);
CheckStatus(index,ShaderStatus.CompileStatus);
CheckStatus(index, ShaderStatus.CompileStatus);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -115,14 +117,24 @@ namespace StgSharp.Graphics.OpenGL
{
throw new ArgumentNullException(nameof(codeStream));
}
GL.LoadShaderSource(handle[index],Encoding.ASCII.GetBytes( codeStream));
GL.LoadShaderSource(handle[index], Encoding.ASCII.GetBytes(codeStream));
GL.CompileShader(handle[index]);
CheckStatus(index, ShaderStatus.CompileStatus);
}
public override string ToString()
public void FromBytes(byte[] stream)
{
return $"This is a {type} shader, its shader handles are {handle.ToString()}.";
throw new NotImplementedException();
}
public static byte[] FromCodeFile(string fileRoute)
{
string str = File.ReadAllText(fileRoute);
if (string.IsNullOrEmpty(str))
{
throw new InvalidOperationException($"Cannot load and GLSL code from {fileRoute}");
}
return Encoding.UTF8.GetBytes(str);
}
public byte[] GetBytes()
@@ -130,24 +142,16 @@ namespace StgSharp.Graphics.OpenGL
return Array.Empty<byte>();
}
public void CheckStatus(int index, ShaderStatus status)
{
string log = GL.GetShaderStatus(this,index, (int)status);
if (!string.IsNullOrEmpty(log))
{
throw new Exception($"Shader Error \t{status}\n" + log);
}
}
public byte[] GetBytes(out int length)
{
throw new NotImplementedException();
}
public void FromBytes(byte[] stream)
public override string ToString()
{
throw new NotImplementedException();
return $"This is a {type} shader, its shader handles are {handle.ToString()}.";
}
}
public enum ShaderStatus : int
@@ -157,7 +161,8 @@ namespace StgSharp.Graphics.OpenGL
public class ShaderProgram
{
private readonly GlFunction GL;
private readonly OpenGLFunction GL;
internal readonly GlHandle handle;
/// <summary>
@@ -191,7 +196,7 @@ namespace StgSharp.Graphics.OpenGL
where T : struct
where U : struct
{
return new Uniform<T, U>(GL.GetUniformLocation(this.handle,name));
return new Uniform<T, U>(GL.GetUniformLocation(this.handle, name));
}
/// <summary>
@@ -42,109 +42,112 @@ namespace StgSharp.Graphics.OpenGL
{
public class Uniform
{
internal GlHandle id;
public GlHandle Handle
{
get => id;
}
}
public sealed class Uniform<T> : Uniform
where T : struct
{
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal static Uniform<T> FromHandle(GlHandle handle)
{
return new Uniform<T>() { id = handle };
return new Uniform<T> { id = handle };
}
}
public sealed class Uniform<T, U>: Uniform
public sealed class Uniform<T, U> : Uniform
where T : struct
where U : struct
{
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
internal static Uniform<T,U> FromHandle(GlHandle handle)
internal unsafe Uniform(GlHandle id)
{
return new Uniform<T, U>() { id = handle };
this.id = id;
}
internal static Uniform<T, U> FromHandle(GlHandle handle)
{
return new Uniform<T, U> { id = handle };
}
}
public sealed class Uniform<T, U, V>:Uniform
public sealed class Uniform<T, U, V> : Uniform
where T : struct
where U : struct
where V : struct
{
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
internal static Uniform<T,U,V> FromHandle(GlHandle handle)
internal unsafe Uniform(GlHandle id)
{
return new Uniform<T, U, V>() { id = handle };
this.id = id;
}
internal static Uniform<T, U, V> FromHandle(GlHandle handle)
{
return new Uniform<T, U, V> { id = handle };
}
}
public sealed class Uniform<T, U, V, W>:Uniform
public sealed class Uniform<T, U, V, W> : Uniform
where T : struct
where U : struct
where V : struct
where W : struct
{
internal Uniform()
{
}
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
internal static Uniform<T, U, V, W> FromHandle(GlHandle handle)
{
return new Uniform<T, U, V, W>() { id = handle };
return new Uniform<T, U, V, W> { id = handle };
}
}
public unsafe partial class GlFunction
public unsafe partial class OpenGLFunction
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue
(Uniform<Matrix44> uniform, Matrix44 mat)
@@ -157,7 +160,7 @@ namespace StgSharp.Graphics.OpenGL
public void SetUniformValue(Uniform<float, float, float, float> uniform, vec4d vec)
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.SignedValue , 4, &temp);
Context.glUniform1fv(uniform.id.SignedValue, 4, &temp);
}
@@ -165,37 +168,37 @@ namespace StgSharp.Graphics.OpenGL
public void SetUniformValue(Uniform<vec4d> uniform, vec4d vec)
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.SignedValue , 4, &temp);
Context.glUniform1fv(uniform.id.SignedValue, 4, &temp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float> uniform, float v0)
{
Context.glUniform1f(uniform.id.SignedValue , v0);
Context.glUniform1f(uniform.id.SignedValue, v0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<int> uniform, int i0)
{
Context.glUniform1i(uniform.id.SignedValue , i0);
Context.glUniform1i(uniform.id.SignedValue, i0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float, float> uniform, float v0, float v1)
{
Context.glUniform2f(uniform.id.SignedValue , v0, v1);
Context.glUniform2f(uniform.id.SignedValue, v0, v1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float, float, float> uniform, float v0, float v1, float v2)
{
Context.glUniform3f(uniform.id.SignedValue , v0, v1, v2);
Context.glUniform3f(uniform.id.SignedValue, v0, v1, v2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float, float, float, float> uniform, float v0, float v1, float v2, float v3)
{
Context.glUniform4f(uniform.id.SignedValue , v0, v1, v2, v3);
Context.glUniform4f(uniform.id.SignedValue, v0, v1, v2, v3);
}
}
@@ -0,0 +1,47 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glAPICalling.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// 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.
//
// 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.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class OpenGLAPICallingAttribute : Attribute
{
public OpenGLAPICallingAttribute()
{
}
}
}
@@ -57,6 +57,25 @@ namespace StgSharp.Graphics.OpenGL
private static string glExtensionList;
//--------------------------------------------------------------------------------
/// <summary>
/// Get the function pointer of given OpenGL api name
/// </summary>
/// <param name="name">ContextName of the OpenGL api</param>
/// <returns>The funtion pointer of the api in stream of <see cref="IntPtr"/></returns>
public static IntPtr LoadGLfunc(string name)
{
IntPtr ret = InternalIO.glfwGetProcAddress(name);
if (ret == default)
{
InternalIO.InternalAppendLog(
$"Cannot load OpenGL api called {name}, this api may not exist or supported.");
return ret;
}
return ret;
}
/// <summary>
/// Load all supported OpenGL APIs and bind them to given <see cref="ViewPort"/>.
/// </summary>
@@ -64,7 +83,7 @@ namespace StgSharp.Graphics.OpenGL
public static unsafe void LoadOpenGLApiTo(IntPtr contextHandle)
{
OpenglContext* context = (OpenglContext*)contextHandle;
delegate*<string,IntPtr> loader = &InternalIO.glfwGetProcAddress;
delegate*<string, IntPtr> loader = &InternalIO.glfwGetProcAddress;
if ((IntPtr)context->glGetString != IntPtr.Zero)
{
return;
@@ -84,7 +103,7 @@ namespace StgSharp.Graphics.OpenGL
{
InternalIO.InternalWriteLog("Failed to call glGetString", LogType.Error);
}
coreVersion = Marshal.PtrToStringAnsi(context->glGetString(glVersion))??string.Empty;
coreVersion = Marshal.PtrToStringAnsi(context->glGetString(glVersion)) ?? string.Empty;
foreach (string branch in glBranch)
{
@@ -140,7 +159,7 @@ namespace StgSharp.Graphics.OpenGL
}
int extensionCount;
context->glGetIntegerv(GLconst.NUM_EXTENSIONS,&extensionCount);
context->glGetIntegerv(GLconst.NUM_EXTENSIONS, &extensionCount);
if (extensionCount == 0)
{
InternalIO.InternalWriteLog("No supported OpenGL extensions are found.", LogType.Info);
@@ -151,12 +170,11 @@ namespace StgSharp.Graphics.OpenGL
for (uint i = 0; i < extensionCount; i++)
{
byte* strPtr = context->glGetStringi(GLconst.EXTENSIONS,i);
byte* strPtr = context->glGetStringi(GLconst.EXTENSIONS, i);
extensions.Add(Marshal.PtrToStringAnsi((IntPtr)strPtr));
}
InternalIO.InternalWriteLog($"Find OpenGL extensions:" + Environment.NewLine +
$"{string.Join(';', extensions)}",
InternalIO.InternalWriteLog($"{$"Find OpenGL extensions:"}{Environment.NewLine}{($"{string.Join(';', extensions)}")}",
LogType.Info);
#region checkGLextensions
@@ -786,25 +804,6 @@ namespace StgSharp.Graphics.OpenGL
}
//--------------------------------------------------------------------------------
/// <summary>
/// Get the function pointer of given OpenGL api name
/// </summary>
/// <param name="name">ContextName of the OpenGL api</param>
/// <returns>The funtion pointer of the api in stream of <see cref="IntPtr"/></returns>
public static IntPtr LoadGLfunc(string name)
{
IntPtr ret = InternalIO.glfwGetProcAddress(name);
if (ret == default)
{
InternalIO.InternalAppendLog(
$"Cannot load OpenGL api called {name}, this api may not exist or supported.");
return ret;
}
return ret;
}
internal static void CheckCoreVersion(int majorVersion, int minorVersion)
{
if (majorVersion < 3)
@@ -1017,7 +1016,7 @@ namespace StgSharp.Graphics.OpenGL
}
}
internal static unsafe void LoadGLcore10(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore10(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core10)
{
@@ -1081,7 +1080,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.0 APIs");
}
internal static unsafe void LoadGLcore11(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore11(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core11)
{
@@ -1111,7 +1110,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.1 APIs");
}
internal static unsafe void LoadGLcore12(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore12(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core12)
{
@@ -1131,7 +1130,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.2 APIs");
}
internal static unsafe void LoadGLcore13(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore13(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core13)
{
@@ -1156,7 +1155,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.3 APIs");
}
internal static unsafe void LoadGLcore14(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore14(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core14)
{
@@ -1181,7 +1180,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.4 APIs");
}
internal static unsafe void LoadGLcore15(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore15(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core15)
{
@@ -1216,7 +1215,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.5 APIs");
}
internal static unsafe void LoadGLcore20(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore20(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core20)
{
@@ -1325,7 +1324,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 2.0 APIs");
}
internal static unsafe void LoadGLcore21(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore21(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core21)
{
@@ -1347,7 +1346,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 2.1 APIs");
}
internal static unsafe void LoadGLcore30(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore30(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core30)
{
@@ -1447,7 +1446,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.0 APIs");
}
internal static unsafe void LoadGLcore31(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore31(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core31)
{
@@ -1478,7 +1477,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.1 APIs");
}
internal static unsafe void LoadGLcore32(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore32(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core32)
{
@@ -1513,7 +1512,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.2 APIs");
}
internal static unsafe void LoadGLcore33(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore33(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core33)
{
@@ -1557,7 +1556,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.3 APIs");
}
internal static unsafe void LoadGLcore40(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore40(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core40)
{
@@ -1619,7 +1618,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.0 APIs");
}
internal static unsafe void LoadGLcore41(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore41(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core41)
{
@@ -1723,7 +1722,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.1 APIs");
}
internal static unsafe void LoadGLcore42(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore42(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core42)
{
@@ -1751,7 +1750,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.2 APIs");
}
internal static unsafe void LoadGLcore43(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore43(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core43)
{
@@ -1811,7 +1810,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.3 APIs");
}
internal static unsafe void LoadGLcore44(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore44(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core44)
{
@@ -1836,7 +1835,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.4 APIs");
}
internal static unsafe void LoadGLcore45(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore45(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core45)
{
@@ -1962,7 +1961,7 @@ namespace StgSharp.Graphics.OpenGL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.5 APIs");
}
internal static unsafe void LoadGLcore46(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore46(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core46)
{
@@ -29,7 +29,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharp.Math;
using System;
@@ -58,22 +58,24 @@ namespace StgSharp
namespace StgSharp.Graphics.OpenGL
{
public unsafe partial class GlFunction
public unsafe partial class OpenGLFunction
{
private static Dictionary<IntPtr, GlFunction> contextToGLMap = new Dictionary<IntPtr, GlFunction>();
private static Dictionary<IntPtr, OpenGLFunction> contextToGLMap = new Dictionary<IntPtr, OpenGLFunction>();
private OpenglContext* _context;
private GlFunction()
private OpenGLFunction()
{
textureUnitCountGetter = new Lazy<int>(() => GetMaskInteger(GLconst.MAX_TEXTURE_IMAGE_UNITS));
unusedTextureImageUintInitilizing = new Lazy<ConcurrentQueue<TextureUnit>>(InitializeUnusedTextureImageUint);
}
internal static GlFunction CurrentGL { get; set; }
internal IntPtr ContextHandle => (IntPtr)_context;
internal static OpenGLFunction CurrentGL { get; set; }
protected ref OpenglContext Context
{
get
@@ -89,11 +91,32 @@ namespace StgSharp.Graphics.OpenGL
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ActiveTexture(uint type)
public void ActiveTextureUnit(uint type)
{
Context.glActiveTexture(type);
}
[Conditional("DEBUG")]
public void Assert(bool shouldReportWhenNormal)
{
try
{
uint code = Context.glGetError();
if (code != GLconst.NO_ERROR)
{
throw new GlExecutionException(code);
}
if (shouldReportWhenNormal)
{
Console.WriteLine("OpenGL runs normally");
}
}
catch (GlExecutionException ex)
{
throw ex;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AttachShader(GlHandle program, GlHandle shader)
{
@@ -108,7 +131,7 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// Bind a frame buffer to a frame buffer target
/// Same function as <see href="https://docs.GL/gl3/glBindFramebuffer">glBindFramebuffer</see>.
/// Same function as <see href="https://docs._gl/gl3/glBindFramebuffer">glBindFramebuffer</see>.
/// </summary>
/// <param name="target"> The frame buffer target of the binding operation.</param>
/// <param name="handle"> The handle of the frame buffer object to bind.</param>
@@ -160,33 +183,6 @@ namespace StgSharp.Graphics.OpenGL
while (Context.glGetError() != 0) { }
}
[Conditional("DEBUG")]
public void Assert(bool shouldReportWhenNormal)
{
try
{
uint code = Context.glGetError();
if (code != GLconst.NO_ERROR)
{
throw new GlExecutionException(code);
}
if (shouldReportWhenNormal)
{
Console.WriteLine("OpenGL runs normally");
}
}
catch (GlExecutionException ex)
{
throw ex;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GenerateMipmap(Texture2DTarget target)
{
Context.glGenerateMipmap((uint)target);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void ClearGraphicError()
{
@@ -292,7 +288,7 @@ namespace StgSharp.Graphics.OpenGL
TypeCode.UInt16 => GLconst.UNSIGNED_SHORT,
TypeCode.Byte => GLconst.UNSIGNED_BYTE,
_ => throw new ArgumentException(
$"{($"{$"Parameter error in parameter {nameof(type)} method DrawElements. "}")}{($"{$"Only {typeof(uint).Name},{typeof(ushort).Name},{typeof(byte).Name} types are supported."}")}")
$"{$"{$"Parameter error in parameter {nameof(type)} method DrawElements. "}"}{$"{$"Only {typeof(uint).Name},{typeof(ushort).Name},{typeof(byte).Name} types are supported."}"}")
};
Context.glDrawElements((uint)mode, count, a, (void*)ptr);
}
@@ -354,6 +350,12 @@ namespace StgSharp.Graphics.OpenGL
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GenerateMipmap(Texture2DTarget target)
{
Context.glGenerateMipmap((uint)target);
}
public unsafe GlHandle[] GenFrameBuffers(int count)
{
GlHandle[] h = new GlHandle[count];
@@ -498,6 +500,7 @@ namespace StgSharp.Graphics.OpenGL
Context.glReadPixels(
beginPosition.X, beginPosition.Y, i.Width, i.Height, (uint)format, (uint)dataType, bptr);
}
i.PixelUpdateCount++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -665,7 +668,7 @@ namespace StgSharp.Graphics.OpenGL
#endif
{
#pragma warning disable CS8500
fixed (T* tptr = ((pixels == null) || (pixels.Length == 0)) ? pixels : null)
fixed (T* tptr = ((pixels == null) || (pixels.Length == 0)) ? null : pixels)
{
Context.glTexImage2D(
(uint)target, level, internalformat, width, height, 0, format, (uint)type, tptr);
@@ -697,7 +700,7 @@ namespace StgSharp.Graphics.OpenGL
Context.glTexParameteri((uint)target, pname, param);
}
public static bool TryGetFunctionPackage(IntPtr handle, out GlFunction functionPackage)
public static bool TryGetFunctionPackage(IntPtr handle, out OpenGLFunction functionPackage)
{
return contextToGLMap.TryGetValue(handle, out functionPackage);
}
@@ -726,19 +729,19 @@ namespace StgSharp.Graphics.OpenGL
Context.glFinish();
}
internal static GlFunction BuildGlFunctionPackage(IntPtr handle)
internal static OpenGLFunction BuildGlFunctionPackage(IntPtr handle)
{
GlFunction pack;
OpenGLFunction pack;
if (contextToGLMap.TryGetValue(handle, out pack))
{
return pack;
}
pack = new GlFunction { _context = (OpenglContext*)handle };
pack = new OpenGLFunction { _context = (OpenglContext*)handle };
contextToGLMap.Add(handle, pack);
return pack;
}
~GlFunction()
~OpenGLFunction()
{
contextToGLMap.Remove(ContextHandle);
}
@@ -28,7 +28,7 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Logic;
using StgSharp.Math;
using System;
@@ -45,9 +45,10 @@ namespace StgSharp.Graphics.OpenGL
public abstract partial class glRenderStream : RenderStream
{
private GlFunction _context;
internal protected GlFunction GL
private OpenGLFunction _context;
protected internal OpenGLFunction GL
{
get { return _context; }
}
@@ -69,11 +70,11 @@ namespace StgSharp.Graphics.OpenGL
}
if (GL == null)
{
_context = GlFunction.BuildGlFunctionPackage(ContextHandle);
_context = OpenGLFunction.BuildGlFunctionPackage(ContextHandle);
}
if (GlFunction.CurrentGL != GL)
if (OpenGLFunction.CurrentGL != GL)
{
GlFunction.CurrentGL = GL;
OpenGLFunction.CurrentGL = GL;
InternalIO.glfwMakeContextCurrent(CanvasHandle);
}
}
@@ -0,0 +1,99 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glResourceManager.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// 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.
//
// 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.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace StgSharp.Graphics.OpenGL
{
public partial class OpenGLFunction
{
private Lazy<int> textureUnitCountGetter;
private Lazy<ConcurrentQueue<TextureUnit>> unusedTextureImageUintInitilizing;
public int TextureUnitCount
{
get => textureUnitCountGetter.Value;
}
private ConcurrentQueue<TextureUnit> UnusedTextureImageUint
{
get => unusedTextureImageUintInitilizing.Value;
}
internal void ReturnAvailableUnit(IEnumerable<TextureUnit> source)
{
int v = GLconst.TEXTURE0 + TextureUnitCount;
foreach (TextureUnit unit in source)
{
if ((int)unit > v)
{
throw new InvalidOperationException("Source contains texture unit beyond context support.");
}
}
}
internal int TryGetAvailableTextureUnit(int count, out IEnumerable<TextureUnit> result)
{
result = new Queue<TextureUnit>();
for (int i = 0; i < count; i++)
{
if (UnusedTextureImageUint.TryDequeue(out TextureUnit unit))
{
(result as Queue<TextureUnit>)!.Enqueue(unit);
}
else
{
return i;
}
}
return count;
}
private ConcurrentQueue<TextureUnit> InitializeUnusedTextureImageUint()
{
ConcurrentQueue<TextureUnit> result = new ConcurrentQueue<TextureUnit>();
for (int index = 0; index < TextureUnitCount; index++)
{
result.Enqueue((TextureUnit)(GLconst.TEXTURE0 + index));
}
return result;
}
}
}