daily update on 20241002 by nitload youmu, intrinsic function rebuild, syntax style arrange

This commit is contained in:
Nitload
2024-10-03 04:03:06 +08:00
parent 0979123ac0
commit 6e2f93b053
265 changed files with 26732 additions and 19058 deletions
@@ -45,12 +45,23 @@ namespace StgSharp.Controls
{
public bool IsEntity => true;
public ReadOnlySpan<vec4d> TextureBox
public ReadOnlySpan<Vec4> TextureBox
{
get => throw new NotImplementedException();
}
public Rectangle BoundingBox { get; set; }
public vec2d Position { get; set; }
public Rectangle BoundingBox
{
get;
set;
}
public Vec2 Position
{
get;
set;
}
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
@@ -53,38 +53,48 @@ namespace StgSharp.Controls
buttonList = new List<TriggerButton>();
}
public bool IsEntity { get => false; }
public bool IsEntity
{
get => false;
}
public ReadOnlySpan<vec4d> TextureBox
public ReadOnlySpan<Vec4> TextureBox
{
get => throw new NotSupportedException();
}
public Rectangle BoundingBox { get; set; }
public Rectangle BoundingBox
{
get;
set;
}
public TriggerButton CurrentButton
{
get => current;
}
public vec2d Position { get; set; }
public Vec2 Position
{
get;
set;
}
protected List<TriggerButton> AllButton
{
get => buttonList;
}
public void AddButton(TriggerButton button)
public void AddButton( TriggerButton button )
{
buttonList.Add(button);
buttonList.Add( button );
}
public abstract void Confirm();
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
foreach (TriggerButton item in buttonList)
{
foreach( TriggerButton item in buttonList ) {
yield return item.Single();
}
}
@@ -92,12 +102,10 @@ namespace StgSharp.Controls
public void MoveDown()
{
TriggerButton button = current;
while ((button.Down != null) && button.Down.IsDisabled)
{
while( ( button.Down != null ) && button.Down.IsDisabled ) {
button = button.Right;
}
if (current == button)
{
if( current == button ) {
return;
}
current.DeHighlight();
@@ -108,12 +116,10 @@ namespace StgSharp.Controls
public void MoveLeft()
{
TriggerButton button = current;
while ((button.Left != null) && button.Left.IsDisabled)
{
while( ( button.Left != null ) && button.Left.IsDisabled ) {
button = button.Left;
}
if (current == button)
{
if( current == button ) {
return;
}
current.DeHighlight();
@@ -124,12 +130,10 @@ namespace StgSharp.Controls
public void MoveRight()
{
TriggerButton button = current;
while ((button.Right != null) && button.Right.IsDisabled)
{
while( ( button.Right != null ) && button.Right.IsDisabled ) {
button = button.Right;
}
if (current == button)
{
if( current == button ) {
return;
}
current.DeHighlight();
@@ -140,12 +144,10 @@ namespace StgSharp.Controls
public void MoveUp()
{
TriggerButton button = current;
while ((button.Up != null) && button.Up.IsDisabled)
{
while( ( button.Up != null ) && button.Up.IsDisabled ) {
button = button.Right;
}
if (current == button)
{
if( current == button ) {
return;
}
current.DeHighlight();
@@ -47,18 +47,21 @@ namespace StgSharp.Controls
private char[] displayIndex;
private char defaultChar;
Dictionary<char, PlainGeometryMesh> texIndex;
private Dictionary<char, PlainGeometryMesh> texIndex;
private int length;
PlainGeometryMesh _tittleMesh;
private PlainGeometryMesh _tittleMesh;
public CharacterLineIndexImage(
int length, char defaultChar, PlainGeometryMesh tittleMesh,
IEnumerable<(char, PlainGeometryMesh)> indexEnumeration)
int length,
char defaultChar,
PlainGeometryMesh tittleMesh,
IEnumerable<(char, PlainGeometryMesh)> indexEnumeration )
{
this.length = length;
displayIndex = new char[length];
_tittleMesh = tittleMesh;
texIndex = indexEnumeration.ToDictionary(item => item.Item1, item => item.Item2);
texIndex = indexEnumeration.ToDictionary(
item => item.Item1, item => item.Item2 );
}
public bool IsEntity
@@ -66,23 +69,32 @@ namespace StgSharp.Controls
get => true;
}
public ReadOnlySpan<vec4d> TextureBox
public ReadOnlySpan<Vec4> TextureBox
{
get => throw new NotSupportedException();
}
public Rectangle BoundingBox { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public vec2d Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public void Display(string message)
public Rectangle BoundingBox
{
if (string.IsNullOrEmpty(message))
{
get => throw new NotImplementedException();
set => throw new NotImplementedException();
}
public Vec2 Position
{
get => throw new NotImplementedException();
set => throw new NotImplementedException();
}
public void Display( string message )
{
if( string.IsNullOrEmpty( message ) ) {
message = string.Empty;
}
string result = (message.Length >= length) ?
message.Substring(message.Length - displayIndex.Length) :
message.PadLeft(length, defaultChar);
string result = ( message.Length >= length ) ?
message.Substring( message.Length - displayIndex.Length ) : message.PadLeft(
length, defaultChar );
displayIndex = result.ToCharArray();
}
@@ -90,9 +102,8 @@ namespace StgSharp.Controls
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
yield return _tittleMesh;
foreach (char item in displayIndex)
{
yield return texIndex[item];
foreach( char item in displayIndex ) {
yield return texIndex[ item ];
}
}
@@ -42,12 +42,27 @@ namespace StgSharp.Controls
public interface ControllingItem : IEnumerable<PlainGeometryMesh>
{
public abstract bool IsEntity { get; }
public abstract bool IsEntity
{
get;
}
public abstract ReadOnlySpan<vec4d> TextureBox { get; }
public abstract Rectangle BoundingBox { get; set; }
public abstract vec2d Position { get; set; }
public abstract ReadOnlySpan<Vec4> TextureBox
{
get;
}
public abstract Rectangle BoundingBox
{
get;
set;
}
public abstract Vec2 Position
{
get;
set;
}
IEnumerator IEnumerable.GetEnumerator()
{
@@ -44,20 +44,30 @@ namespace StgSharp.Controls
private PlainGeometryMesh renderMesh;
public DecorationBox(Rectangle bound, Image texture, vec2d[] texCoord)
public DecorationBox( Rectangle bound, Image texture, Vec2[] texCoord )
{
renderMesh = new PlainGeometryMesh(BoundingBox, new TextureProvider(texture, texCoord));
renderMesh = new PlainGeometryMesh(
BoundingBox, new TextureProvider( texture, texCoord ) );
}
public bool IsEntity => true;
public ReadOnlySpan<vec4d> TextureBox
public ReadOnlySpan<Vec4> TextureBox
{
get => renderMesh.TextureCoord;
}
public Rectangle BoundingBox { get; set; }
public vec2d Position { get; set; }
public Rectangle BoundingBox
{
get;
set;
}
public Vec2 Position
{
get;
set;
}
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
@@ -48,40 +48,49 @@ namespace StgSharp.Controls
private TimeFunction _movement;
private vec2d _currentPosition, _movementVec;
private Vec2 _currentPosition, _movementVec;
public MarkingLabel(PlainGeometryMesh marker, TimeFunction movement)
public MarkingLabel( PlainGeometryMesh marker, TimeFunction movement )
{
this.marker = marker;
_movement = movement;
}
public bool IsEntity => true;
public ReadOnlySpan<vec4d> TextureBox
public ReadOnlySpan<Vec4> TextureBox
{
get => marker.TextureCoord;
}
public Rectangle BoundingBox { get; set; }
public vec2d Position { get; set; }
public Rectangle BoundingBox
{
get;
set;
}
public Vec2 Position
{
get;
set;
}
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
yield return marker;
}
public void Move(vec2d movement)
public void Move( Vec2 movement )
{
if (!_movement.IsComplete)
{
Position = _currentPosition + (_movement.Calculate() * _movementVec);
if( !_movement.IsComplete ) {
Position = _currentPosition + ( _movement.Calculate() * _movementVec );
}
}
public void MoveTo(vec2d target)
public void MoveTo( Vec2 target )
{
Move(target - Position);
Move( target - Position );
}
}
}
@@ -40,11 +40,14 @@ using System.Text;
namespace StgSharp.Controls
{
public delegate void RenderButtonTextureCallback(ButtonStatus status, float beginTime, in TextureProvider texture);
public delegate void RenderButtonTextureCallback(
ButtonStatus status,
float beginTime,
in TextureProvider texture );
public enum ButtonStatus
{
Error = 0b0,
Disable = 0b1,
Enable = 0b10,
@@ -52,12 +55,13 @@ namespace StgSharp.Controls
Confirm = 0b1000,
DisableToEnable = Disable | Enable,
EnableToDisable = -(Enable | DisableToEnable),
EnableToDisable = -( Enable | DisableToEnable ),
EnableToHighlight = Enable | Highlight,
HighlightToEnable = -(Enable | Highlight),
HighlightToEnable = -( Enable | Highlight ),
HighlightToDisable = -( Highlight | Disable ),
HighlightToDisable = -(Highlight | Disable),
}
public class TriggerButton : ControllingItem
@@ -66,14 +70,14 @@ namespace StgSharp.Controls
private Action? confirmCallback;
private Action? disableCallback;
#nullable enable
#nullable enable
private Action? enableCallback;
private float _statusBeginTime;
private RenderButtonTextureCallback _renderButton;
private TextureProvider _texture;
#nullable restore
#nullable restore
public TriggerButton()
{
@@ -102,41 +106,74 @@ namespace StgSharp.Controls
{
add
{
if (_renderButton == null)
{
if( _renderButton == null ) {
_renderButton = value;
}
else
{
} else {
_renderButton += value;
}
}
remove
{
if (_renderButton != null)
{
if( _renderButton != null ) {
_renderButton -= value;
}
}
}
public bool IsHighLighted { get; internal set; }
public bool IsHighLighted
{
get;
internal set;
}
public bool IsDisabled { get; internal set; }
public bool IsDisabled
{
get;
internal set;
}
public bool IsEntity => true;
public ReadOnlySpan<vec4d> TextureBox
public ReadOnlySpan<Vec4> TextureBox
{
get => MemoryMarshal.Cast<vec2d, vec4d>(_texture.TextureCoordinate);
get => MemoryMarshal.Cast<Vec2, Vec4>( _texture.TextureCoordinate );
}
public Rectangle BoundingBox { get; set; }
public TriggerButton Left { get; internal set; }
public TriggerButton Right { get; internal set; }
public TriggerButton Up { get; internal set; }
public TriggerButton Down { get; internal set; }
public vec2d Position { get; set; }
public Rectangle BoundingBox
{
get;
set;
}
public TriggerButton Left
{
get;
internal set;
}
public TriggerButton Right
{
get;
internal set;
}
public TriggerButton Up
{
get;
internal set;
}
public TriggerButton Down
{
get;
internal set;
}
public Vec2 Position
{
get;
set;
}
internal TextureProvider Texture
{
@@ -144,12 +181,15 @@ namespace StgSharp.Controls
set => _texture = value;
}
protected ButtonStatus CurrentStatus { get; set; }
protected ButtonStatus CurrentStatus
{
get;
set;
}
public void DeHighlight()
{
if (CurrentStatus == ButtonStatus.Highlight)
{
if( CurrentStatus == ButtonStatus.Highlight ) {
CurrentStatus = ButtonStatus.HighlightToEnable;
}
}
@@ -162,54 +202,44 @@ namespace StgSharp.Controls
ButtonStatus.Highlight => ButtonStatus.HighlightToDisable,
_ => CurrentStatus,
};
if (disableCallback != null)
{
if( disableCallback != null ) {
disableCallback();
}
}
public void Enable()
{
if (CurrentStatus == ButtonStatus.Disable)
{
if( CurrentStatus == ButtonStatus.Disable ) {
CurrentStatus = ButtonStatus.DisableToEnable;
}
else
{
} else {
return;
}
if (enableCallback != null)
{
if( enableCallback != null ) {
enableCallback();
}
}
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
_renderButton(CurrentStatus, _statusBeginTime, in _texture);
yield return new PlainGeometryMesh(this.BoundingBox, _texture);
_renderButton( CurrentStatus, _statusBeginTime, in _texture );
yield return new PlainGeometryMesh( this.BoundingBox, _texture );
}
public void Highlight()
{
if (CurrentStatus == ButtonStatus.Enable)
{
if( CurrentStatus == ButtonStatus.Enable ) {
CurrentStatus |= ButtonStatus.EnableToHighlight;
}
else
{
} else {
return;
}
if (confirmCallback != null)
{
if( confirmCallback != null ) {
confirmCallback();
}
}
internal void Init(ButtonStatus status)
internal void Init( ButtonStatus status )
{
if (CurrentStatus == ButtonStatus.Error)
{
if( CurrentStatus == ButtonStatus.Error ) {
CurrentStatus = status;
}
}
+63 -33
View File
@@ -40,31 +40,55 @@ namespace StgSharp
{
internal static partial class InternalIO
{
#region ssgc api define
[DllImport(SSC_libName, EntryPoint = "initGL",
CallingConvention = CallingConvention.Cdecl)]
internal static extern void InternalInitGL(int majorVersion, int minorVersion);
[DllImport(
SSC_libName,
EntryPoint = "initGL",
CallingConvention = CallingConvention.Cdecl )]
internal static extern void InternalInitGL(
int majorVersion,
int minorVersion );
[DllImport(SSC_libName, EntryPoint = "loadGlfuncDefault",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
internal static extern IntPtr InternalLoadGlfuncDefault(string name);
[DllImport(
SSC_libName,
EntryPoint = "loadGlfuncDefault",
CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Ansi )]
internal static extern IntPtr InternalLoadGlfuncDefault( string name );
[DllImport(SSC_libName, EntryPoint = "linkShaderProgram",
CallingConvention = CallingConvention.Cdecl)]
internal static extern unsafe uint InternalLinkShaderProgram(OpenglContext* context, uint shaderProgram);
[DllImport(
SSC_libName,
EntryPoint = "linkShaderProgram",
CallingConvention = CallingConvention.Cdecl )]
internal static extern unsafe uint InternalLinkShaderProgram(
OpenglContext* context,
uint shaderProgram );
[DllImport(SSC_libName, EntryPoint = "readLog",
CallingConvention = CallingConvention.Cdecl)]
[DllImport(
SSC_libName,
EntryPoint = "readLog",
CallingConvention = CallingConvention.Cdecl )]
internal static extern unsafe IntPtr InternalReadSSCLog();
[DllImport(SSC_libName, EntryPoint = "loadImageData",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
internal static extern unsafe void InternalLoadImage(string fileName, ImageInfo* output, ImageLoader loader);
[DllImport(
SSC_libName,
EntryPoint = "loadImageData",
CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Ansi )]
internal static extern unsafe void InternalLoadImage(
string fileName,
ImageInfo* output,
ImageLoader loader );
[DllImport(SSC_libName, EntryPoint = "unloadImageData",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
internal static extern unsafe void InternalUnloadImage(ImageInfo* output);
[DllImport(
SSC_libName,
EntryPoint = "unloadImageData",
CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Ansi )]
internal static extern unsafe void InternalUnloadImage(
ImageInfo* output );
#endregion ssgc api define
}
@@ -72,34 +96,42 @@ namespace StgSharp
namespace StgSharp.Graphics
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public delegate IntPtr ImageLoader(string name, ref int width, ref int height, ref int definedChannel, int desiredChannel);
[UnmanagedFunctionPointer( CallingConvention.Cdecl, CharSet = CharSet.Ansi )]
public delegate IntPtr ImageLoader(
string name,
ref int width,
ref int height,
ref int definedChannel,
int desiredChannel );
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public struct OpenglContext
{
public override bool Equals(object obj)
public override bool Equals( object obj )
{
return false;
}
public override unsafe int GetHashCode()
{
fixed (OpenglContext* sptr = &this)
{
fixed( OpenglContext* sptr = &this ) {
return sptr->GetHashCode();
}
}
public static bool operator !=(OpenglContext left, OpenglContext right)
public static bool operator !=(
OpenglContext left,
OpenglContext right )
{
return !(left == right);
return !( left == right );
}
public static bool operator ==(OpenglContext left, OpenglContext right)
public static bool operator ==(
OpenglContext left,
OpenglContext right )
{
return left.Equals(right);
return left.Equals( right );
}
#region glapi
@@ -244,7 +276,7 @@ namespace StgSharp.Graphics
internal unsafe delegate*<uint, IntPtr, UIntPtr, uint, ulong, bool, void> glBufferPageCommitmentMemNV;
internal unsafe delegate*<uint, uint, int, void> glBufferParameteriAPPLE;
internal unsafe delegate*<uint, UIntPtr, void*, uint, void> glBufferStorage;
[Obsolete("Param type uncertain", true)] internal unsafe delegate*<uint, IntPtr, UIntPtr, int, uint, void> glBufferStorageExternalEXT;
[Obsolete( "Param type uncertain", true )] internal unsafe delegate*<uint, IntPtr, UIntPtr, int, uint, void> glBufferStorageExternalEXT;
internal unsafe delegate*<uint, UIntPtr, uint, ulong, void> glBufferStorageMemEXT;
internal unsafe delegate*<uint, IntPtr, UIntPtr, void*, void> glBufferSubData;
internal unsafe delegate*<uint, IntPtr, UIntPtr, void*, void> glBufferSubDataARB;
@@ -1425,7 +1457,7 @@ namespace StgSharp.Graphics
internal unsafe delegate*<uint, IntPtr, UIntPtr, uint, ulong, bool, void> glNamedBufferPageCommitmentMemNV;
internal unsafe delegate*<uint, UIntPtr, void*, uint, void> glNamedBufferStorage;
internal unsafe delegate*<uint, UIntPtr, void*, uint, void> glNamedBufferStorageEXT;
[Obsolete("Param type uncertain", true)] internal unsafe delegate*<uint, IntPtr, UIntPtr, int, uint, void> glNamedBufferStorageExternalEXT;
[Obsolete( "Param type uncertain", true )] internal unsafe delegate*<uint, IntPtr, UIntPtr, int, uint, void> glNamedBufferStorageExternalEXT;
internal unsafe delegate*<uint, UIntPtr, uint, ulong, void> glNamedBufferStorageMemEXT;
internal unsafe delegate*<uint, IntPtr, UIntPtr, void*, void> glNamedBufferSubData;
internal unsafe delegate*<uint, IntPtr, UIntPtr, void*, void> glNamedBufferSubDataEXT;
@@ -2103,7 +2135,7 @@ namespace StgSharp.Graphics
internal unsafe delegate*<int, uint, double*, void> glUniform1dv;
internal unsafe delegate*<int, float, void> glUniform1f;
internal unsafe delegate*<int, float, void> glUniform1fARB;
internal unsafe delegate*<int, uint, vec4d*, void> glUniform1fv;
internal unsafe delegate*<int, uint, Vec4*, void> glUniform1fv;
internal unsafe delegate*<int, uint, float*, void> glUniform1fvARB;
internal unsafe delegate*<int, int, void> glUniform1i;
internal unsafe delegate*<int, long, void> glUniform1i64ARB;
@@ -2637,8 +2669,6 @@ namespace StgSharp.Graphics
internal unsafe delegate*<uint, uint, int*, void> glWindowRectanglesEXT;
internal unsafe delegate*<uint, uint, uint, uint, uint, uint, void> glWriteMaskEXT;
#endregion glapi
#endregion glapi
}
}
+48 -41
View File
@@ -28,12 +28,14 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data.Intrinsic;
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
@@ -47,11 +49,13 @@ namespace StgSharp
{
public enum LogType
{
Error,
Warning,
Info,
InfoError,
InfoWarning,
}
internal static unsafe partial class InternalIO
@@ -67,42 +71,45 @@ namespace StgSharp
new Dictionary<TypeCode, uint>();
internal static readonly GCHandle ssc_logHandle =
GCHandle.Alloc(new byte[512], GCHandleType.Pinned);
GCHandle.Alloc( new byte[512], GCHandleType.Pinned );
internal static IntPtr SSClibPtr = IntPtr.Zero;
internal static SemaphoreSlim logSyncSemaphore = new SemaphoreSlim(1, 1);
internal static SemaphoreSlim logSyncSemaphore = new SemaphoreSlim(
1, 1 );
static InternalIO()
{
GLtype.Add(TypeCode.Single, GLconst.FLOAT);
GLtype.Add(TypeCode.Int32, GLconst.INT);
GLtype.Add(TypeCode.UInt32, GLconst.UNSIGNED_INT);
GLtype.Add(TypeCode.Int16, GLconst.SHORT);
GLtype.Add(TypeCode.UInt16, GLconst.UNSIGNED_SHORT);
GLtype.Add(TypeCode.SByte, GLconst.BYTE);
GLtype.Add(TypeCode.Byte, GLconst.UNSIGNED_BYTE);
GLtype.Add( TypeCode.Single, GLconst.FLOAT );
GLtype.Add( TypeCode.Int32, GLconst.INT );
GLtype.Add( TypeCode.UInt32, GLconst.UNSIGNED_INT );
GLtype.Add( TypeCode.Int16, GLconst.SHORT );
GLtype.Add( TypeCode.UInt16, GLconst.UNSIGNED_SHORT );
GLtype.Add( TypeCode.SByte, GLconst.BYTE );
GLtype.Add( TypeCode.Byte, GLconst.UNSIGNED_BYTE );
fixed( IntrinsicContext* cptr = &_intrinsicContext ) {
LoadIntrinsicFunction( cptr );
}
}
internal static void InternalAppendLog(string log)
internal static void InternalAppendLog( string log )
{
if (!File.Exists(SS_errorLog))
{
FileStream stream = File.Create(SS_errorLog);
if( !File.Exists( SS_errorLog ) ) {
FileStream stream = File.Create( SS_errorLog );
stream.Close();
}
using (StreamWriter logStream = File.AppendText(SS_errorLog))
{
logStream.WriteLine(log);
using( StreamWriter logStream = File.AppendText( SS_errorLog ) ) {
logStream.WriteLine( log );
}
}
[Obsolete("Not completed", true)]
internal static IntPtr InternalLoadProc<T>(IntPtr lib, string name) where T : Delegate
[Obsolete( "Not completed", true )]
internal static IntPtr InternalLoadProc<T>( IntPtr lib, string name )
where T: Delegate
{
try
{
try {
IntPtr procPtr =
#if WINDOWS
IntPtr.Zero;
@@ -110,48 +117,48 @@ namespace StgSharp
#else
IntPtr.Zero;
#endif
#endif
return procPtr;
}
catch (Exception)
{
catch( Exception ) {
throw;
}
}
internal static void InternalWriteLog(string logLine, LogType logType)
internal static void InternalWriteLog( string logLine, LogType logType )
{
logSyncSemaphore.Wait();
if (!File.Exists(SS_errorLog))
{
FileStream stream = File.Create(SS_errorLog);
if( !File.Exists( SS_errorLog ) ) {
FileStream stream = File.Create( SS_errorLog );
stream.Close();
}
using (StreamWriter logStream = File.AppendText(SS_errorLog))
{
logStream.WriteLine($"{logType}\t{DateTime.Now.ToString("o")}");
logStream.WriteLine(logLine);
using( StreamWriter logStream = File.AppendText( SS_errorLog ) ) {
logStream.WriteLine(
$"{logType}\t{DateTime.Now.ToString("o")}" );
logStream.WriteLine( logLine );
}
logSyncSemaphore.Release();
}
internal static void InternalWriteLog(string beforeTime, string logLine, LogType logType)
internal static void InternalWriteLog(
string beforeTime,
string logLine,
LogType logType )
{
logSyncSemaphore.Wait();
if (!File.Exists(InternalIO.SS_errorLog))
{
FileStream stream = File.Create(InternalIO.SS_errorLog);
if( !File.Exists( InternalIO.SS_errorLog ) ) {
FileStream stream = File.Create( InternalIO.SS_errorLog );
stream.Close();
}
using (StreamWriter logStream = File.AppendText(SS_errorLog))
{
logStream.WriteLine(beforeTime);
logStream.WriteLine($"{logType}\t@\t{DateTime.Now.ToString("o")}");
logStream.WriteLine(logLine);
using( StreamWriter logStream = File.AppendText( SS_errorLog ) ) {
logStream.WriteLine( beforeTime );
logStream.WriteLine(
$"{logType}\t@\t{DateTime.Now.ToString("o")}" );
logStream.WriteLine( logLine );
}
logSyncSemaphore.Release(1);
logSyncSemaphore.Release( 1 );
}
}
+237
View File
@@ -0,0 +1,237 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="KeyEnum.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;
using StgSharp.Graphics.OpenGL;
using System;
namespace StgSharp
{
public enum KeyboardKey : int
{
UNKNOWN = -1,
None = 0,
Space = 32,
Apostrophe = 39/*'*/,
Comma = 44/*,*/,
Minus = 45/*-*/,
Period = 46/*.*/,
Slash = 47/*/*/,
Zero = 48,
One = 49,
Two = 50,
Three = 51,
Four = 52,
Five = 53,
Six = 54,
Seven = 55,
Eight = 56,
Nine = 57,
Semicolon = 59/*,*/,
Equal = 61/*=*/,
A = 65,
B = 66,
C = 67,
D = 68,
E = 69,
F = 70,
G = 71,
H = 72,
I = 73,
J = 74,
K = 75,
L = 76,
M = 77,
N = 78,
O = 79,
P = 80,
Q = 81,
R = 82,
S = 83,
T = 84,
U = 85,
V = 86,
W = 87,
X = 88,
Y = 89,
Z = 90,
LeftBracket = 91/*[*/,
BACKSLASH = 92/*\*/,
RightBracket = 93/*]*/,
GraveAccent = 96/*`*/,
World1 = 161/*non-US#1*/,
World2 = 162/*non-US#2*/,
Esc = 256,
Enter = 257,
Tab = 258,
Backspace = 259,
Insert = 260,
Delete = 261,
Right = 262,
Left = 263,
Down = 264,
Up = 265,
PgUp = 266,
PgDown = 267,
Home = 268,
End = 269,
CapsLock = 280,
ScrollLock = 281,
NumLock = 282,
PrintScreen = 283,
Pause = 284,
F1 = 290,
F2 = 291,
F3 = 292,
F4 = 293,
F5 = 294,
F6 = 295,
F7 = 296,
F8 = 297,
F9 = 298,
F10 = 299,
F11 = 300,
F12 = 301,
F13 = 302,
F14 = 303,
F15 = 304,
F16 = 305,
F17 = 306,
F18 = 307,
F19 = 308,
F20 = 309,
F21 = 310,
F22 = 311,
F23 = 312,
F24 = 313,
F25 = 314,
NumPad0 = 320,
NumPad1 = 321,
NumPad2 = 322,
NumPad3 = 323,
NumPad4 = 324,
NumPad5 = 325,
NumPad6 = 326,
NumPad7 = 327,
NumPad8 = 328,
NumPad9 = 329,
NumPadDec = 330,
NumPadDiv = 331,
NumPadMul = 332,
NumPadSub = 333,
NumPadAdd = 334,
NumPadAnter = 335,
NumPadEqual = 336,
LeftShift = 340,
LeftControl = 341,
LeftAlt = 342,
LeftSuper = 343,
RightShift = 344,
RightControl = 345,
RightAlt = 346,
RightSuper = 347,
Menu = 348,
First = Space,
Last = Menu,
}
#pragma warning disable CA1707
#pragma warning disable CA1712
#pragma warning disable CA1008
#pragma warning disable CA1027
public enum Joystick : int
#pragma warning restore CA1027
{
Joystick_1 = GLconst.GLFW_JOYSTICK_1,
Joystick_2 = GLconst.GLFW_JOYSTICK_2,
Joystick_3 = GLconst.GLFW_JOYSTICK_3,
Joystick_4 = GLconst.GLFW_JOYSTICK_4,
Joystick_5 = GLconst.GLFW_JOYSTICK_5,
Joystick_6 = GLconst.GLFW_JOYSTICK_6,
Joystick_7 = GLconst.GLFW_JOYSTICK_7,
Joystick_8 = GLconst.GLFW_JOYSTICK_8,
Joystick_9 = GLconst.GLFW_JOYSTICK_9,
Joystick_10 = GLconst.GLFW_JOYSTICK_10,
Joystick_11 = GLconst.GLFW_JOYSTICK_11,
Joystick_12 = GLconst.GLFW_JOYSTICK_12,
Joystick_13 = GLconst.GLFW_JOYSTICK_13,
Joystick_14 = GLconst.GLFW_JOYSTICK_14,
Joystick_15 = GLconst.GLFW_JOYSTICK_15,
Joystick_16 = GLconst.GLFW_JOYSTICK_16,
First = Joystick_1,
Last = Joystick_16
}
[System.Flags]
public enum Mouse : int
{
Button1 = 0,
Button2 = 1,
Button3 = 2,
Button4 = 3,
Button5 = 4,
Button6 = 5,
Button7 = 6,
Button8 = 7,
First = Button1,
Last = Button8,
Left = Button1,
Right = Button2,
Middle = Button3
}
#pragma warning restore CA1707
#pragma warning restore CA1712
#pragma warning restore CA7008
internal enum InputEquipment
{
Keyboard,
Mouse,
Joystick
}
public enum KeyStatus : int
{
RELEASE = 0,
PRESS = 1
}
}
@@ -36,7 +36,7 @@ using System.Threading.Tasks;
namespace StgSharp
{
[AttributeUsage(AttributeTargets.Method)]
[AttributeUsage( AttributeTargets.Method )]
public class KeyEventAttribute : Attribute
{
@@ -44,27 +44,26 @@ namespace StgSharp
internal int _keyStat;
internal int _keyTarget;
public KeyEventAttribute(KeyboardKey key, KeyStatus status)
public KeyEventAttribute( KeyboardKey key, KeyStatus status )
{
_equipment = (int)InputEquipment.Keyboard;
_keyTarget = (int)key;
_keyStat = (int)status;
_equipment = ( int )InputEquipment.Keyboard;
_keyTarget = ( int )key;
_keyStat = ( int )status;
}
public KeyEventAttribute(Joystick joystick, KeyStatus status)
public KeyEventAttribute( Joystick joystick, KeyStatus status )
{
_equipment = (int)InputEquipment.Keyboard;
_keyTarget = (int)joystick;
_keyStat = (int)status;
_equipment = ( int )InputEquipment.Keyboard;
_keyTarget = ( int )joystick;
_keyStat = ( int )status;
}
public KeyEventAttribute(Mouse mouse, KeyStatus status)
public KeyEventAttribute( Mouse mouse, KeyStatus status )
{
_equipment = (int)InputEquipment.Keyboard;
_keyTarget = (int)mouse;
_keyStat = (int)status;
_equipment = ( int )InputEquipment.Keyboard;
_keyTarget = ( int )mouse;
_keyStat = ( int )status;
}
}
}
@@ -0,0 +1,51 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IClickTrigger.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.Controlling.UsrActivity
{
public interface IClickTrigger
{
public int TargetKeyOrButtonID
{
get;
}
public KeyStatus TriggeredStatus
{
get;
}
}
}
@@ -34,47 +34,57 @@ using System.Text;
namespace StgSharp.Controlling.UsrActivity
{
public struct JoystickTrigger : ITrigger, IEquatable<JoystickTrigger>
public readonly struct JoystickTrigger : IClickTrigger, IEquatable<JoystickTrigger>
{
private KeyStatus _triggeredStat;
public Joystick Stick;
private readonly Joystick _stick;
private readonly KeyStatus _status;
public JoystickTrigger(Joystick targetKey)
public JoystickTrigger( Joystick targetKey, KeyStatus status )
{
this.Stick = targetKey;
this._stick = targetKey;
_status = status;
}
public int TargetKeyOrButtonID => (int)Stick;
public int TargetKeyOrButtonID => ( int )_stick;
public KeyStatus TriggeredStatus => _triggeredStat;
public override bool Equals(object obj)
public Joystick Stick
{
return base.Equals(obj);
get => _stick;
}
public KeyStatus TriggeredStatus => _status;
public override bool Equals( object obj )
{
return base.Equals( obj );
}
public override int GetHashCode()
{
return ((int)Stick) + (17 * ((int)_triggeredStat));
return ( ( int )_stick ) + ( 17 * ( ( int )_status ) );
}
public override string ToString()
{
return $"Key {Stick} triggered when {_triggeredStat}";
return $"Key {_stick} triggered when {_status}";
}
public static bool operator !=(JoystickTrigger left, JoystickTrigger right)
public static bool operator !=(
JoystickTrigger left,
JoystickTrigger right )
{
return !(left == right);
return !( left == right );
}
public static bool operator ==(JoystickTrigger left, JoystickTrigger right)
public static bool operator ==(
JoystickTrigger left,
JoystickTrigger right )
{
return (left._triggeredStat == right._triggeredStat) && (left.Stick == right.Stick);
return ( left._status == right._status ) && ( left._stick == right._stick );
}
bool IEquatable<JoystickTrigger>.Equals(JoystickTrigger other)
bool IEquatable<JoystickTrigger>.Equals( JoystickTrigger other )
{
return other == this;
}
@@ -35,31 +35,30 @@ using System.Text;
namespace StgSharp.Controlling.UsrActivity
{
public struct KeyTrigger : ITrigger, IEquatable<KeyTrigger>
public readonly struct KeyTrigger : IClickTrigger, IEquatable<KeyTrigger>
{
private KeyboardKey _targetKey;
private KeyStatus _triggerStat;
private readonly KeyboardKey _targetKey;
private readonly KeyStatus _triggerStat;
public KeyTrigger(KeyboardKey targetKey, KeyStatus targetStat)
public KeyTrigger( KeyboardKey targetKey, KeyStatus targetStat )
{
this._targetKey = targetKey;
this._triggerStat = targetStat;
}
public int TargetKeyOrButtonID => (int)_targetKey;
public int TargetKeyOrButtonID => ( int )_targetKey;
public KeyStatus TriggeredStatus => _triggerStat;
public override bool Equals(object obj)
public override bool Equals( object obj )
{
return base.Equals(obj);
return base.Equals( obj );
}
public override int GetHashCode()
{
return ((int)_targetKey) + (17 * ((int)_triggerStat));
return ( ( int )_targetKey ) + ( 17 * ( ( int )_triggerStat ) );
}
public override string ToString()
@@ -67,17 +66,17 @@ namespace StgSharp.Controlling.UsrActivity
return $"Key {_targetKey} triggered when {_triggerStat}";
}
public static bool operator !=(KeyTrigger left, KeyTrigger right)
public static bool operator !=( KeyTrigger left, KeyTrigger right )
{
return !(left == right);
return !( left == right );
}
public static bool operator ==(KeyTrigger left, KeyTrigger right)
public static bool operator ==( KeyTrigger left, KeyTrigger right )
{
return (left._triggerStat == right._triggerStat) && (left._targetKey == right._targetKey);
return ( left._triggerStat == right._triggerStat ) && ( left._targetKey == right._targetKey );
}
bool IEquatable<KeyTrigger>.Equals(KeyTrigger other)
bool IEquatable<KeyTrigger>.Equals( KeyTrigger other )
{
return other == this;
}
@@ -0,0 +1,72 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="MouseTrigger.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.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics.SymbolStore;
using System.Text;
namespace StgSharp.Controlling.UsrActivity
{
public readonly struct MouseTrigger : IClickTrigger, IEquatable<MouseTrigger>
{
private readonly KeyStatus _status;
private readonly Mouse _mouse;
public MouseTrigger( Mouse mouse, KeyStatus status )
{
_mouse = mouse;
_status = status;
}
public int TargetKeyOrButtonID => ( int )_mouse;
public KeyStatus TriggeredStatus => _status;
public bool Equals( MouseTrigger other )
{
return this == other;
}
public static bool operator !=( MouseTrigger left, MouseTrigger right )
{
return left._mouse != right._mouse || left._status != right._status;
}
public static bool operator ==( MouseTrigger left, MouseTrigger right )
{
return left._mouse == right._mouse && left._status == right._status;
}
}
}
@@ -0,0 +1,102 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TriggetFactory.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.Math;
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Controlling.UsrActivity
{
public static class TriggetBuilder
{
private const int JoystickMax = ( int )Joystick.Last + 1;
private const int JoystickMin = ( int )Joystick.First - 1;
private const int KeyboardMax = ( int )KeyboardKey.Last + 1;
private const int KeyboardMin = ( int )KeyboardKey.First - 1;
private const int MouseMax = ( int )Mouse.Last + 1;
private const int MouseMin = ( int )Mouse.First - 1;
private static KeyTrigger keyboardtemp;
private static MouseTrigger mousetemp;
public static JoystickTrigger BuildJoystickClickTrigger(
int keyCode,
KeyStatus status )
{
if( keyCode > MouseMin && keyCode < MouseMax ) {
return new JoystickTrigger( ( Joystick )keyCode, status );
}
throw new InvalidOperationException(
"Known key code or key is not on joystick." );
}
public static KeyTrigger BuildKeyboardClickTrigger(
int keyCode,
KeyStatus status )
{
if( keyCode > KeyboardMin && keyCode < KeyboardMax ) {
return new KeyTrigger( ( KeyboardKey )keyCode, status );
}
throw new InvalidOperationException(
"Known key code or kay is not on keyboard." );
}
public static MouseTrigger BuildMouseClickTrigger(
int keyCode,
KeyStatus status )
{
if( keyCode >= MouseMin && keyCode <= MouseMax ) {
return new MouseTrigger( ( Mouse )keyCode, status );
}
throw new InvalidOperationException(
"Known key code or key is not on mouse." );
}
public static IClickTrigger BuildTrigger(
int keyCode,
KeyStatus status )
{
if( keyCode > KeyboardMin && keyCode < KeyboardMax ) {
return new KeyTrigger( ( KeyboardKey )keyCode, status );
}
if( keyCode > JoystickMin && keyCode < JoystickMax ) {
return new JoystickTrigger( ( Joystick )keyCode, status );
}
if( keyCode >= MouseMin && keyCode <= MouseMax ) {
return new MouseTrigger( ( Mouse )keyCode, status );
}
throw new InvalidOperationException( "Known key code." );
}
}
}
@@ -52,6 +52,5 @@ namespace StgSharp
return ret;
}
}//------------------ end of class ---------------------
}
+1 -3
View File
@@ -96,8 +96,6 @@ namespace StgSharp
}
""";
#endregion
#endregion
}
}
@@ -0,0 +1,90 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ColumnSet2.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.Data.Intrinsic;
using StgSharp.Math;
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Data.Intrinsic
{
[StructLayout( LayoutKind.Explicit, Size = 12 * sizeof( float ), Pack = 16 )]
internal struct ColumnSet2 : IEquatable<ColumnSet2>
{
[FieldOffset( 0 * sizeof( float ) )] internal float m00;
[FieldOffset( 4 * sizeof( float ) )] internal float m01;
[FieldOffset( 1 * sizeof( float ) )] internal float m10;
[FieldOffset( 5 * sizeof( float ) )] internal float m11;
[FieldOffset( 2 * sizeof( float ) )] internal float m20;
[FieldOffset( 6 * sizeof( float ) )] internal float m21;
[FieldOffset( 3 * sizeof( float ) )] internal float m30;
[FieldOffset( 7 * sizeof( float ) )] internal float m31;
[FieldOffset( 0 )] internal Vector4 colum0;
[FieldOffset( 4 * sizeof( float ) )] internal Vector4 colum1;
internal ColumnSet2( Vector4 c0, Vector4 c1 )
{
colum0 = c0;
colum1 = c1;
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public override bool Equals( object? obj )
{
return ( obj is ColumnSet2 mat ) && Equals( mat );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public bool Equals( ColumnSet2 other )
{
return colum0.Equals( other.colum0 ) && colum1.Equals(
other.colum1 );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool operator !=( ColumnSet2 left, ColumnSet2 right )
{
return !( left == right );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool operator ==( ColumnSet2 left, ColumnSet2 right )
{
return left.Equals( right );
}
}
}
@@ -0,0 +1,87 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ColumnSet3.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.Data.Intrinsic;
using StgSharp.Math;
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace StgSharp.Data.Intrinsic
{
[StructLayout( LayoutKind.Explicit, Size = 12 * sizeof( float ), Pack = 16 )]
internal struct ColumnSet3 : IEquatable<ColumnSet3>, IMat
{
[FieldOffset( 0 * sizeof( float ) )] internal float m00;
[FieldOffset( 4 * sizeof( float ) )] internal float m01;
[FieldOffset( 8 * sizeof( float ) )] internal float m02;
[FieldOffset( 1 * sizeof( float ) )] internal float m10;
[FieldOffset( 5 * sizeof( float ) )] internal float m11;
[FieldOffset( 9 * sizeof( float ) )] internal float m12;
[FieldOffset( 2 * sizeof( float ) )] internal float m20;
[FieldOffset( 6 * sizeof( float ) )] internal float m21;
[FieldOffset( 10 * sizeof( float ) )] internal float m22;
[FieldOffset( 3 * sizeof( float ) )] internal float m30;
[FieldOffset( 7 * sizeof( float ) )] internal float m31;
[FieldOffset( 11 * sizeof( float ) )] internal float m32;
[FieldOffset( 0 )] internal Vector4 colum0;
[FieldOffset( 4 * sizeof( float ) )] internal Vector4 colum1;
[FieldOffset( 8 * sizeof( float ) )] internal Vector4 colum2;
public override bool Equals( object? obj )
{
return ( obj is ColumnSet3 mat ) && Equals( mat );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public bool Equals( ColumnSet3 other )
{
return colum0.Equals( other.colum0 ) && colum1.Equals(
other.colum1 ) && colum2.Equals( other.colum2 );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool operator !=( ColumnSet3 left, ColumnSet3 right )
{
return !( left == right );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool operator ==( ColumnSet3 left, ColumnSet3 right )
{
return left.Equals( right );
}
}
}
@@ -0,0 +1,110 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ColumnSet4.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 StgSharp.Data.Intrinsic;
using StgSharp.Math;
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace StgSharp.Data.Intrinsic
{
[StructLayout( LayoutKind.Explicit, Size = 16 * sizeof( float ) )]
internal struct ColumnSet4 : IEquatable<ColumnSet4>, IMat
{
[FieldOffset( 0 )] internal Vector4 colum0;
[FieldOffset( 16 )] internal Vector4 colum1;
[FieldOffset( 32 )] internal Vector4 colum2;
[FieldOffset( 48 )] internal Vector4 colum3;
[FieldOffset( 0 )] public float m00;
[FieldOffset( 16 )] public float m01;
[FieldOffset( 32 )] public float m02;
[FieldOffset( 48 )] public float m03;
[FieldOffset( 4 )] public float m10;
[FieldOffset( 20 )] public float m11;
[FieldOffset( 36 )] public float m12;
[FieldOffset( 52 )] public float m13;
[FieldOffset( 8 )] public float m20;
[FieldOffset( 24 )] public float m21;
[FieldOffset( 40 )] public float m22;
[FieldOffset( 56 )] public float m23;
[FieldOffset( 12 )] public float m30;
[FieldOffset( 28 )] public float m31;
[FieldOffset( 44 )] public float m32;
[FieldOffset( 60 )] public float m33;
[MethodImpl( MethodImplOptions.AggressiveInlining )]
internal ColumnSet4(
Vector4 colum0,
Vector4 colum1,
Vector4 colum2,
Vector4 colum3 )
{
this.colum0 = colum0;
this.colum1 = colum1;
this.colum2 = colum2;
this.colum3 = colum3;
}
public override bool Equals( object? obj )
{
return ( obj is ColumnSet4 mat ) && Equals( mat );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public bool Equals( ColumnSet4 other )
{
return colum0.Equals( other.colum0 ) && colum1.Equals(
other.colum1 ) && colum2.Equals( other.colum2 ) && colum3.Equals(
other.colum3 );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool operator !=( ColumnSet4 left, ColumnSet4 right )
{
return !( left == right );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool operator ==( ColumnSet4 left, ColumnSet4 right )
{
return left.Equals( right );
}
}
}
@@ -0,0 +1,61 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IRegisterType.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.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Data.Intrinsic
{
public interface IRegisterType
{
public T Read<T>( int index )
where T: struct
#if NET8_0_OR_GREATER
, INumber
#else
, IConvertible
#endif
;
public void Write<T>( int index, T value )
where T: struct
#if NET8_0_OR_GREATER
, INumber
#else
, IConvertible
#endif
;
}
}
@@ -0,0 +1,59 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IntrinsicContext.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.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Data.Intrinsic
{
[StructLayout( LayoutKind.Sequential )]
internal unsafe struct IntrinsicContext
{
public delegate* unmanaged[Cdecl]<ColumnSet2*, ColumnSet3*, void> transpose23;
public delegate* unmanaged[Cdecl]<ColumnSet2*, ColumnSet4*, void> transpose24;
public delegate* unmanaged[Cdecl]<ColumnSet3*, ColumnSet2*, void> transpose32;
public delegate* unmanaged[Cdecl]<ColumnSet3*, ColumnSet3*, void> transpose33;
public delegate* unmanaged[Cdecl]<ColumnSet3*, ColumnSet4*, void> transpose34;
public delegate* unmanaged[Cdecl]<ColumnSet4*, ColumnSet2*, void> transpose42;
public delegate* unmanaged[Cdecl]<ColumnSet4*, ColumnSet3*, void> transpose43;
public delegate* unmanaged[Cdecl]<ColumnSet4*, ColumnSet4*, void> transpose44;
public delegate* unmanaged[Cdecl]<ColumnSet3*, ColumnSet3*, float> det_mat_3;
public delegate* unmanaged[Cdecl]<ColumnSet4*, ColumnSet4*, float> det_mat_4;
public delegate* unmanaged[Cdecl]<M128*, M128*, void> normalize_v3;
public delegate* unmanaged[Cdecl]<char*, int, int> string_quickHash;
}
}
+193
View File
@@ -0,0 +1,193 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="M128.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.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if NET5_0_OR_GREATER
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
#endif
using System.Text;
namespace StgSharp.Data.Intrinsic
{
[StructLayout( LayoutKind.Explicit, Pack = 16 )]
public unsafe struct M128 : IRegisterType
{
[FieldOffset( 0 )] internal Vector4 vec;
internal M128( Vector4 v )
{
vec = v;
}
public override bool Equals( [NotNullWhen( true )] object obj )
{
if( obj is not M128 other ) {
return false;
}
return this == other;
}
public override int GetHashCode()
{
return vec.GetHashCode();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public T Read<T>( int index )
where T: struct
#if NET8_0_OR_GREATER
, INumber
#else
, IConvertible
#endif
{
fixed( Vector4* p = &vec ) {
#pragma warning disable CS8500
return *( ( T* )p + index );
#pragma warning restore CS8500
}
}
public override string ToString()
{
return string.Empty;
}
public string ToString( int sample )
{
string str = string.Empty;
for( int i = 15; i >= 0; i-- ) {
str += $"{Convert.ToString(Read<byte>(i), sample)} ";
}
return str;
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Write<T>( int index, T value )
where T: struct
#if NET8_0_OR_GREATER
, INumber
#else
, IConvertible
#endif
{
fixed( Vector4* p = &vec ) {
#pragma warning disable CS8500
*( ( T* )p + index ) = value;
#pragma warning restore CS8500
}
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool operator !=( M128 left, M128 right )
{
return left.vec != right.vec;
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool operator ==( M128 left, M128 right )
{
return left.vec == right.vec;
}
#if NET5_0_OR_GREATER
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static explicit operator Vector128<byte>( M128 m )
{
return m.vec.AsVector128().As<float, byte>();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static explicit operator Vector128<sbyte>( M128 m )
{
return m.vec.AsVector128().As<float, sbyte>();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static explicit operator Vector128<short>( M128 m )
{
return m.vec.AsVector128().As<float, short>();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static explicit operator Vector128<ushort>( M128 m )
{
return m.vec.AsVector128().As<float, ushort>();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static explicit operator Vector128<int>( M128 m )
{
return m.vec.AsVector128().As<float, int>();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static explicit operator Vector128<uint>( M128 m )
{
return m.vec.AsVector128().As<float, uint>();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static explicit operator Vector128<long>( M128 m )
{
return m.vec.AsVector128().As<float, long>();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static explicit operator Vector128<ulong>( M128 m )
{
return m.vec.AsVector128().As<float, ulong>();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static explicit operator Vector128<float>( M128 m )
{
return m.vec.AsVector128().As<float, float>();
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static explicit operator Vector128<double>( M128 m )
{
return m.vec.AsVector128().As<float, double>();
}
#endif
}
}
+63
View File
@@ -0,0 +1,63 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="M256.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.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Data.Intrinsic
{
[StructLayout( LayoutKind.Sequential )]
public unsafe struct M256 : IRegisterType
{
private M128 v0;
private M128 v1;
T IRegisterType.Read<T>( int index )
{
fixed( M128* mptr = &v0 ) {
return *( ( T* )mptr + index );
}
}
void IRegisterType.Write<T>( int index, T value )
{
fixed( M128* mptr = &v0 ) {
*( ( T* )mptr + index ) = value;
}
}
}
}
@@ -0,0 +1,57 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="intrinsicContextProvider.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.Data.Intrinsic;
using System;
using System.Runtime.InteropServices;
namespace StgSharp
{
internal static unsafe partial class InternalIO
{
private static readonly IntrinsicContext _intrinsicContext = new IntrinsicContext(
);
internal static IntrinsicContext Intrinsic
{
get => _intrinsicContext;
}
[DllImport(
InternalIO.SSC_libName,
CallingConvention = CallingConvention.Cdecl,
EntryPoint = "load_intrinsic_function" )]
private static extern void LoadIntrinsicFunction(
IntrinsicContext* context );
}
}
+70
View File
@@ -0,0 +1,70 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Lable.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.Runtime.CompilerServices;
namespace StgSharp.Data
{
public class DataLabel
{
private readonly string _name;
public DataLabel( string lableName )
{
_name = lableName;
}
public string Name
{
get => _name;
}
public override unsafe int GetHashCode()
{
ReadOnlySpan<char> nameSpan = _name.AsSpan();
fixed( char* cptr = nameSpan ) {
return InternalIO.Intrinsic
.string_quickHash( cptr, _name.Length );
}
}
}
public static class DataLabelBuilder
{
public static DataLabel AsLabel(this string name)
{
return new DataLabel(name);
}
}
}
+37 -52
View File
@@ -28,7 +28,7 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data;
using StgSharp.Data.Intrinsic;
using System;
using System.IO;
@@ -46,38 +46,30 @@ namespace StgSharp.Data
private byte[] currentKey;
private readonly byte[] originKey;
private int cycleCount;
private SHA512 hash;
public RandomGenerator() : this(DateTime.UtcNow.ToBinary())
{
public RandomGenerator() : this( DateTime.UtcNow.ToBinary() ) { }
}
public RandomGenerator(object source)
public RandomGenerator( object source )
{
try
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
try {
if( source == null ) {
throw new ArgumentNullException( nameof( source ) );
}
XmlSerializer s = new XmlSerializer(source.GetType());
using (StringWriter sw = new StringWriter())
{
s.Serialize(sw, source);
XmlSerializer s = new XmlSerializer( source.GetType() );
using( StringWriter sw = new StringWriter() ) {
s.Serialize( sw, source );
string data = sw.ToString();
originKey = Encoding.UTF8.GetBytes(data);
originKey = Encoding.UTF8.GetBytes( data );
}
}
catch (Exception)
{
catch( Exception ) {
throw;
}
hash = SHA512.Create();
originKey = hash.ComputeHash(originKey);
originKey = hash.ComputeHash( originKey );
currentKey = originKey;
cycleCount = 0;
}
@@ -105,54 +97,44 @@ namespace StgSharp.Data
/**/
return source.Read<int>(cycleCount % 4);
return source.Read<int>( cycleCount % 4 );
}
public byte GenRandomInt8()
{
cycleCount++;
if (cycleCount % 64 == 0)
{
if( cycleCount % 64 == 0 ) {
PrivateRand();
}
return currentKey[cycleCount % 64];
return currentKey[ cycleCount % 64 ];
}
public float GenRandomSingle()
{
cycleCount++;
while (true)
{
while( true ) {
M128 source = PrivateRand();
uint
temp0 = source.Read<uint>(0),
temp1 = source.Read<uint>(2);
temp0 = source.Read<uint>( 0 ),
temp1 = source.Read<uint>( 2 );
if (temp0 * temp1 != 0)
{
float ret = ((temp0 % temp1) * 1.0f) / temp1;
if (ret < 0.335f)
{
ret = ret * ((ret * (-0.7811934f)) + 1.4489113f);
if( temp0 * temp1 != 0 ) {
float ret = ( ( temp0 % temp1 ) * 1.0f ) / temp1;
if( ret < 0.335f ) {
ret = ret * ( ( ret * ( -0.7811934f ) ) + 1.4489113f );
} else {
ret = ( ret * ( ( ret * ( -0.1158368f ) ) + 1.0580600f ) ) + 0.0590584f;
}
else
{
ret = (ret * ((ret * (-0.1158368f)) + 1.0580600f)) + 0.0590584f;
}
if (ret > 1)
{
if( ret > 1 ) {
continue;
}
return ret;
}
}
}
public void Reset()
{
currentKey = originKey;
@@ -161,24 +143,27 @@ namespace StgSharp.Data
private unsafe M128 PrivateRand()
{
currentKey = hash.ComputeHash(currentKey);
currentKey = hash.ComputeHash( currentKey );
M128 ret;
fixed (byte* bptr = currentKey)
{
switch ((cycleCount % 16) / 4)
{
fixed( byte* bptr = currentKey ) {
switch( ( cycleCount % 16 ) / 4 ) {
case 0:
ret = *(((M128*)bptr) + 0); break;
ret = *( ( ( M128* )bptr ) + 0 );
break;
case 1:
ret = *(((M128*)bptr) + 1); break;
ret = *( ( ( M128* )bptr ) + 1 );
break;
case 2:
ret = *(((M128*)bptr) + 2); break;
ret = *( ( ( M128* )bptr ) + 2 );
break;
case 3:
ret = *(((M128*)bptr) + 3); break;
ret = *( ( ( M128* )bptr ) + 3 );
break;
default:
throw new InvalidOperationException();
}
}
//Console.WriteLine(ret.ToString(16));
return ret;
}
+4 -7
View File
@@ -39,12 +39,9 @@ using System.Threading.Tasks;
namespace StgSharp.Data
{
/// <summary>
/// An independent storage area, used as the only folder type in root folder.
/// Contains several <see cref="SSD"/> files reference as virtual disc.
/// Data is actually stored in <see cref="SSD"/>s in certain RAID mode.
/// An independent storage area, used as the only folder type in root folder. Contains several
/// <see cref="SSD" /> files reference as virtual disc. Data is actually stored in <see
/// cref="SSD" />s in certain RAID mode.
/// </summary>
public partial class Area
{
}
public partial class Area { }
}
+18 -24
View File
@@ -28,6 +28,8 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data.Intrinsic;
using System;
using System.Collections;
using System.Collections.Generic;
@@ -38,52 +40,44 @@ using System.Text;
namespace StgSharp.Data
{
[StructLayout(LayoutKind.Explicit, Size = 16)]
[StructLayout( LayoutKind.Explicit, Size = 16 )]
public struct SSDSegmentHead
{
[FieldOffset( 12 )] internal byte size;
[FieldOffset(12)] internal byte size;
[FieldOffset(0)] internal M128 data;
[FieldOffset(13)] public byte selfDefine_1;
[FieldOffset(14)] public byte selfDefine_2;
[FieldOffset(15)] public byte selfDefine_3;
[FieldOffset(0)] public int globalID;
[FieldOffset(4)] public int nextID;
[FieldOffset(8)] public int previousHash;
[FieldOffset( 0 )] internal M128 data;
[FieldOffset( 13 )] public byte selfDefine_1;
[FieldOffset( 14 )] public byte selfDefine_2;
[FieldOffset( 15 )] public byte selfDefine_3;
[FieldOffset( 0 )] public int globalID;
[FieldOffset( 4 )] public int nextID;
[FieldOffset( 8 )] public int previousHash;
public int Size
{
get => ((int)size) + 1;
get => ( ( int )size ) + 1;
set
{
if ((value > 256) || (value < 0))
{
if( ( value > 256 ) || ( value < 0 ) ) {
throw new ArgumentOutOfRangeException();
}
size = (byte)(value - 1);
size = ( byte )( value - 1 );
}
}
public unsafe byte[] GetBytes()
{
byte[] ret = new byte[16];
fixed (Vector4* vptr = &data.vec)
{
byte* bptr = (byte*)vptr;
for (int i = 0; i < 15; i++)
{
ret[i] = *bptr;
fixed( Vector4* vptr = &data.vec ) {
byte* bptr = ( byte* )vptr;
for( int i = 0; i < 15; i++ ) {
ret[ i ] = *bptr;
}
}
return ret;
}
}
}
+51 -65
View File
@@ -28,6 +28,7 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data.Intrinsic;
using StgSharp.Math;
using System;
@@ -40,38 +41,37 @@ using System.Threading.Tasks;
namespace StgSharp.Data
{
[StructLayout(LayoutKind.Explicit, Size = StgSharp.ssdSegmentLength * 16)]
[StructLayout( LayoutKind.Explicit, Size = StgSharp.ssdSegmentLength * 16 )]
public unsafe struct SSDSegment : IComparable<int>, IComparable<SSDSegment>
{
[FieldOffset(16)] public fixed byte Data[16 * (StgSharp.ssdSegmentLength - 1)];
[FieldOffset(12)] public int DataHash;
[FieldOffset(8)] public int PreviousHash;
[FieldOffset(0 * 16)] public SSDSegmentHead Head;
[FieldOffset( 16 )] public fixed byte Data[
16 * ( StgSharp.ssdSegmentLength - 1 ) ];
[FieldOffset( 12 )] public int DataHash;
[FieldOffset( 8 )] public int PreviousHash;
[FieldOffset( 0 * 16 )] public SSDSegmentHead Head;
public SSDSegment(int previousHash)
public SSDSegment( int previousHash )
{
this.PreviousHash = previousHash;
}
public byte this[int index]
public byte this[ int index ]
{
get
{
if (index > (16 * (StgSharp.ssdSegmentLength - 1)) - 1)
{
if( index > ( 16 * ( StgSharp.ssdSegmentLength - 1 ) ) - 1 ) {
throw new IndexOutOfRangeException();
}
return Data[index];
return Data[ index ];
}
set
{
if (index > (16 * (StgSharp.ssdSegmentLength - 1)) - 1)
{
if( index > ( 16 * ( StgSharp.ssdSegmentLength - 1 ) ) - 1 ) {
throw new IndexOutOfRangeException();
}
Data[index] = value;
Data[ index ] = value;
}
}
@@ -83,31 +83,27 @@ namespace StgSharp.Data
public short Size => Head.size;
public void FillRandomBytes(int begin)
public void FillRandomBytes( int begin )
{
if (begin > 255)
{
if( begin > 255 ) {
return;
}
for (int i = begin; i < 255; i++)
{
Data[i] = Scaler.Random<byte>(); //TODO: 使用STGSHARP内部随机数工具处理它
for( int i = begin; i < 255; i++ ) {
Data[ i ] = Scaler.Random<byte>(); //TODO: 使用STGSHARP内部随机数工具处理它
}
}
public static SSDSegment FromStream(byte[] stream)
public static SSDSegment FromStream( byte[] stream )
{
if (stream.Length != 16 * StgSharp.ssdSegmentLength)
{
if( stream.Length != 16 * StgSharp.ssdSegmentLength ) {
throw new ArgumentException();
}
SSDSegment ret = new SSDSegment();
fixed (byte* bptr = stream)
{
ret.Head.data = *(M128*)bptr;
for (int i = 1; i < StgSharp.ssdSegmentLength; i++)
{
ret.WriteData<M128>(i - 1, *(M128*)(bptr + (16 * i)));
fixed( byte* bptr = stream ) {
ret.Head.data = *( M128* )bptr;
for( int i = 1; i < StgSharp.ssdSegmentLength; i++ ) {
ret.WriteData<M128>(
i - 1, *( M128* )( bptr + ( 16 * i ) ) );
}
}
return ret;
@@ -116,15 +112,12 @@ namespace StgSharp.Data
public byte[] GetBytes()
{
byte[] ret = new byte[16 * StgSharp.ssdSegmentLength];
fixed (M128* mptr = &Head.data)
{
fixed (byte* aptr = ret)
{
Vector4* vsptr = (Vector4*)mptr;
Vector4* vtptr = (Vector4*)aptr;
for (int i = 0; i < 18; i++)
{
*(vtptr + i) = *(vsptr + i);
fixed( M128* mptr = &Head.data ) {
fixed( byte* aptr = ret ) {
Vector4* vsptr = ( Vector4* )mptr;
Vector4* vtptr = ( Vector4* )aptr;
for( int i = 0; i < 18; i++ ) {
*( vtptr + i ) = *( vsptr + i );
}
}
}
@@ -135,15 +128,13 @@ namespace StgSharp.Data
public int GetDataHash()
{
Vector4 v = Vector4.One;
fixed (M128* mptr = &Head.data)
{
Vector4* vptr = (Vector4*)mptr;
for (int i = 0; i < StgSharp.ssdSegmentLength - 1; i += 1)
{
v += (*vptr) * 31;
fixed( M128* mptr = &Head.data ) {
Vector4* vptr = ( Vector4* )mptr;
for( int i = 0; i < StgSharp.ssdSegmentLength - 1; i += 1 ) {
v += ( *vptr ) * 31;
}
}
M128 m = new M128(v);
M128 m = new M128( v );
DataHash = m.vec.GetHashCode();
return DataHash;
}
@@ -151,45 +142,40 @@ namespace StgSharp.Data
public override int GetHashCode()
{
int ret = 17;
fixed (M128* mptr = &Head.data)
{
Vector4* vptr = (Vector4*)mptr;
for (int i = 0; i < StgSharp.ssdSegmentLength; i++)
{
ret = (ret + (*vptr).GetHashCode()) * 31;
fixed( M128* mptr = &Head.data ) {
Vector4* vptr = ( Vector4* )mptr;
for( int i = 0; i < StgSharp.ssdSegmentLength; i++ ) {
ret = ( ret + ( *vptr ).GetHashCode() ) * 31;
}
}
return ret;
}
public unsafe T ReadData<T>(int index) where T : struct
public unsafe T ReadData<T>( int index ) where T: struct
{
fixed (byte* bptr = Data)
{
T* tptr = (T*)bptr;
return *(tptr + index);
fixed( byte* bptr = Data ) {
T* tptr = ( T* )bptr;
return *( tptr + index );
}
}
public unsafe void WriteData<T>(int index, T value) where T : struct
public unsafe void WriteData<T>( int index, T value ) where T: struct
{
fixed (byte* bptr = Data)
{
T* tptr = (T*)bptr;
*(tptr + index) = value;
fixed( byte* bptr = Data ) {
T* tptr = ( T* )bptr;
*( tptr + index ) = value;
}
}
int IComparable<int>.CompareTo(int other)
int IComparable<int>.CompareTo( int other )
{
return ID.CompareTo(other);
return ID.CompareTo( other );
}
int IComparable<SSDSegment>.CompareTo(SSDSegment other)
int IComparable<SSDSegment>.CompareTo( SSDSegment other )
{
return ID.CompareTo(other.ID);
return ID.CompareTo( other.ID );
}
}
}
+6 -4
View File
@@ -50,17 +50,19 @@ namespace StgSharp.Data
fileList = new Dictionary<string, SSDraw>();
}
public SSD(FileStream fileStream)
public SSD( FileStream fileStream )
{
fileList = new Dictionary<string, SSDraw>();
file = fileStream;
}
public static SSD FromFile(string fileRoute)
public static SSD FromFile( string fileRoute )
{
return new SSD(new FileStream(fileRoute, FileMode.Open, FileAccess.Read)) { };
return new SSD(
new FileStream( fileRoute, FileMode.Open, FileAccess.Read ) )
{
};
}
}
}
@@ -49,19 +49,15 @@ namespace StgSharp.Data
folders = new Dictionary<string, SSDFolder>();
}
internal SSDFolder(string name)
internal SSDFolder( string name )
{
if (name == "root")
{
if( name == "root" ) {
throw new ArgumentException(
"Name cannot be root," +
"it is preserved for root file indexer.");
"Name cannot be root," + "it is preserved for root file indexer." );
}
if (name == "default")
{
if( name == "default" ) {
throw new ArgumentException(
"Name cannot be default," +
"it is preserved for default file id provider.");
"Name cannot be default," + "it is preserved for default file id provider." );
}
_name = name;
folders = new Dictionary<string, SSDFolder>();
@@ -69,12 +65,11 @@ namespace StgSharp.Data
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.VirtualFolder;
public void FromBytes(byte[] stream)
public void FromBytes( byte[] stream )
{
throw new NotImplementedException();
}
//TODO 虚拟文件夹的GetBytes好难写
public byte[] GetBytes()
{
+17 -15
View File
@@ -50,28 +50,30 @@ namespace StgSharp.Data.FileIO
private byte[] data;
public SSDraw(string name, Stream streamSource)
public SSDraw( string name, Stream streamSource )
{
if ((streamSource == null) || (streamSource.Length == 0))
{
throw new ArgumentNullException(nameof(streamSource));
if( ( streamSource == null ) || ( streamSource.Length == 0 ) ) {
throw new ArgumentNullException( nameof( streamSource ) );
}
Name = name;
data = new byte[streamSource.Length];
streamSource.Read(data.AsSpan());
streamSource.Read( data.AsSpan() );
}
public SSDrawHead Head { get; set; }
public string Name { get; set; }
public SSDrawHead Head
{
get;
set;
}
public string Name
{
get;
set;
}
}
[StructLayout(LayoutKind.Explicit, Size = 32 * 16)]
public unsafe struct SSDrawHead
{
}
[StructLayout( LayoutKind.Explicit, Size = 32 * 16 )]
public unsafe struct SSDrawHead { }
}
+1 -6
View File
@@ -34,13 +34,8 @@ using System.Text;
namespace StgSharp.Data
{
/// <summary>
/// A class contains a sets of methods to serialize several types
/// </summary>
public static partial class Serializer
{
}
public static partial class Serializer { }
}
@@ -36,20 +36,23 @@ using System.Threading.Tasks;
namespace StgSharp.Data
{
public interface ISSDSerializable
{
public SerializableTypeCode SSDTypeCode { get; }
public SerializableTypeCode SSDTypeCode
{
get;
}
public byte[] GetBytes();
internal void FromBytes(byte[] stream);
internal void FromBytes( byte[] stream );
}
public enum SerializableTypeCode
{
Unknown = 0,
IndexTable = 1,
PixelImage = 2,
@@ -59,22 +62,23 @@ namespace StgSharp.Data
Text = 6,
RawData = 7,
VirtualFolder = int.MaxValue,
}
public static partial class Serializer
{
public static T Deserialize<T>(byte[] stream) where T : ISSDSerializable
public static T Deserialize<T>( byte[] stream )
where T: ISSDSerializable
{
T serializableObject = Activator.CreateInstance<T>();
serializableObject.FromBytes(stream);
serializableObject.FromBytes( stream );
return serializableObject;
}
public static string GetNameTail(SerializableTypeCode typeCode)
public static string GetNameTail( SerializableTypeCode typeCode )
{
switch (typeCode)
{
switch( typeCode ) {
case SerializableTypeCode.IndexTable:
return "_idt";
case SerializableTypeCode.PixelImage:
@@ -92,10 +96,11 @@ namespace StgSharp.Data
case SerializableTypeCode.VirtualFolder:
return "_fod";
default:
throw new ArgumentException("Unknown file type");
throw new ArgumentException( "Unknown file type" );
}
}
public static byte[] Serialize(ISSDSerializable serializableObject)
public static byte[] Serialize( ISSDSerializable serializableObject )
{
return serializableObject.GetBytes();
}
+1 -4
View File
@@ -30,8 +30,5 @@
//-----------------------------------------------------------------------
namespace StgSharp.Entities
{
public abstract class BehaviorArgs
{
}
public abstract class BehaviorArgs { }
}
+18 -7
View File
@@ -29,7 +29,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
@@ -43,9 +42,23 @@ namespace StgSharp.Entities
internal LinkedList<Launcher<EntityPartical>> _commonBulletLauncher;
public bool _selectalbe;
public Launcher<EntityPartical> AwardLauncher { get; set; }
public Launcher<EntityPartical> DieBulletLauncher { get; set; }
public LinkedList<Launcher<EntityPartical>> CommonBulletLauncher { get; set; }
public Launcher<EntityPartical> AwardLauncher
{
get;
set;
}
public Launcher<EntityPartical> DieBulletLauncher
{
get;
set;
}
public LinkedList<Launcher<EntityPartical>> CommonBulletLauncher
{
get;
set;
}
public virtual void OnRender()
{
@@ -55,8 +68,7 @@ namespace StgSharp.Entities
public override void OnRenderFrame()
{
this.OnUpdate();
foreach (Launcher<EntityPartical> launcher in CommonBulletLauncher)
{
foreach( Launcher<EntityPartical> launcher in CommonBulletLauncher ) {
launcher.Launch();
}
this.OnRender();
@@ -67,6 +79,5 @@ namespace StgSharp.Entities
new NotImplementedException();
}
}
}
+17 -5
View File
@@ -29,7 +29,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
namespace StgSharp.Entities
{
public class Enemy : IEntity
@@ -40,15 +39,28 @@ namespace StgSharp.Entities
internal Launcher<EntityPartical> _dieBulletLauncher;
public bool _selectalbe;
public Launcher<EntityPartical> AwardLauncher { get; set; }
public Launcher<EntityPartical> CommonBulletLauncher { get; set; }
public Launcher<EntityPartical> DieBulletLauncher { get; set; }
public Launcher<EntityPartical> AwardLauncher
{
get;
set;
}
public Launcher<EntityPartical> CommonBulletLauncher
{
get;
set;
}
public Launcher<EntityPartical> DieBulletLauncher
{
get;
set;
}
public override void OnRenderFrame()
{
CommonBulletLauncher.Launch();
}
}
}
@@ -30,8 +30,5 @@
//-----------------------------------------------------------------------
namespace StgSharp.Entities
{
public abstract class EntityPartical : IEntity
{
}
public abstract class EntityPartical : IEntity { }
}
+23 -7
View File
@@ -40,7 +40,7 @@ namespace StgSharp
{
protected uint _bornTick;
internal Func<int, vec3d> _movHandler;
internal Func<int, Vec3> _movHandler;
internal LinkedList<PlainGeometry> _collisionBox;
internal Point _basePoint;
internal Point _pos;
@@ -51,12 +51,20 @@ namespace StgSharp
/// <summary>
/// X position of an enenmy entity
/// </summary>
public float X { get; set; }
public float X
{
get;
set;
}
/// <summary>
/// Y position of an enemy entity
/// </summary>
public float Y { get; set; }
public float Y
{
get;
set;
}
public LinkedList<PlainGeometry> CollisionBox
{
@@ -73,16 +81,24 @@ namespace StgSharp
set => _collisionSensor = value;
}
public string TextureGL { get; set; }
public string TextureGL
{
get;
set;
}
/// <summary>
/// A 2D vector presenting the position of an enemy entity, position can also be visited by X, Y
/// A 2D vector presenting the position of an enemy entity, position can also be visited by
/// X, Y
/// </summary>
public vec2d Location { get; }
public Vec2 Location
{
get;
}
public abstract void OnRenderFrame();
public void SetLocation(Point p)
public void SetLocation( Point p )
{
_pos = p;
}
+3 -8
View File
@@ -33,7 +33,7 @@ using StgSharp.Math;
namespace StgSharp
{
public class Launcher<T> where T : IEntity
public class Launcher<T> where T: IEntity
{
internal uint[] launchtick; //发射子弹的内部计时
@@ -44,7 +44,7 @@ namespace StgSharp
*用于发射其他的实体,主要是子弹 和 掉落物
*/
internal vec2d _center; //发射器的参考位置,运动轨迹的方程应当基于这个参考点构建
internal Vec2 _center; //发射器的参考位置,运动轨迹的方程应当基于这个参考点构建
public EntityPartical Bullet
{
@@ -52,12 +52,7 @@ namespace StgSharp
set => _bulletSample = value;
}
internal virtual void Launch()
{
}
internal virtual void Launch() { }
}
}
-2
View File
@@ -37,7 +37,5 @@ namespace StgSharp
public float Velocity => _velocity;
}
}
@@ -39,11 +39,9 @@ namespace StgSharp
public class UniformEmptyReferenceException : Exception
{
public UniformEmptyReferenceException(string program, string name) :
base($"Location -1 returned when trying to find uniform {name} in shader program {program}")
{
}
public UniformEmptyReferenceException( string program, string name )
: base(
$"Location -1 returned when trying to find uniform {name} in shader program {program}" ) { }
}
}
+15 -19
View File
@@ -44,7 +44,7 @@ namespace StgSharp
internal const int ssdSegmentLength = 16;
static byte[] _currentHash;
private static byte[] _currentHash;
private static bool _inited;
private static int _mainThreadID = -1;
@@ -53,14 +53,12 @@ namespace StgSharp
{
get
{
if (_currentHash == null)
{
if( _currentHash == null ) {
string route = Assembly.GetExecutingAssembly().Location;
string time = DateTime.UtcNow.ToString();
using (SHA256 sh = SHA256.Create())
{
byte[] bytes = Encoding.UTF8.GetBytes(route);
_currentHash = sh.ComputeHash(bytes);
using( SHA256 sh = SHA256.Create() ) {
byte[] bytes = Encoding.UTF8.GetBytes( route );
_currentHash = sh.ComputeHash( bytes );
}
}
return _currentHash;
@@ -69,26 +67,24 @@ namespace StgSharp
public static int MainThreadID
{
get => (_mainThreadID == -1) ?
throw new InvalidOperationException("StgSharp environment is not inited. " +
"Main thread id is not available") : _mainThreadID;
get => ( _mainThreadID == -1 ) ?
throw new InvalidOperationException(
"StgSharp environment is not inited. " + "Main thread id is not available" ) : _mainThreadID;
}
/// <summary>
/// CustomizeInit an instance of OpenGL program,
/// This method should be called before any other StgSharp api.
/// CustomizeInit an instance of OpenGL program, This method should be called before any
/// other StgSharp api.
/// </summary>
public static void InitGL(int majorVersion, int minorVersion)
public static void InitGL( int majorVersion, int minorVersion )
{
if (API == default)
{
if( API == default ) {
API = GraphicAPI.GL;
}
if (API != GraphicAPI.GL)
{
if( API != GraphicAPI.GL ) {
return;
}
InternalIO.InternalInitGL(majorVersion, minorVersion);
InternalIO.InternalInitGL( majorVersion, minorVersion );
}
public static class GlobalSetting
@@ -101,7 +97,7 @@ namespace StgSharp
get => vsyncActivated;
set
{
InternalIO.glfwSwapInterval(value ? 1 : 0);
InternalIO.glfwSwapInterval( value ? 1 : 0 );
vsyncActivated = value;
}
}
+6 -8
View File
@@ -48,13 +48,13 @@ namespace StgSharp
{
get
{
if (monitorsArray == null)
{
if( monitorsArray == null ) {
int count = 0;
IntPtr* arrayhandle = InternalIO.glfwGetMonitors(&count);
IntPtr* arrayhandle = InternalIO.glfwGetMonitors( &count );
monitorsArray = new IntPtr[count];
Marshal.Copy((IntPtr)arrayhandle, monitorsArray, 0, count);
Marshal.FreeHGlobal((IntPtr)arrayhandle);
Marshal.Copy(
( IntPtr )arrayhandle, monitorsArray, 0, count );
Marshal.FreeHGlobal( ( IntPtr )arrayhandle );
}
return monitorsArray;
}
@@ -62,10 +62,8 @@ namespace StgSharp
public static IntPtr DefaultMonitor
{
get { return MonitorsHandleArray[0]; }
get { return MonitorsHandleArray[ 0 ]; }
}
}
}
+48 -54
View File
@@ -60,18 +60,19 @@ namespace StgSharp
{
internal enum GraphicAPI : byte
{
GL,
DX,
VK
}
public static partial class StgSharp
{
/// <summary>
/// Version of current StgSharp platform.
/// Main version represent in hundred's digit,
/// and sub version represent in ten's digit.
/// Version of current StgSharp platform. Main version represent in hundred's digit, and sub
/// version represent in ten's digit.
/// </summary>
public const long version = 430;
@@ -85,38 +86,39 @@ namespace StgSharp
mainTimeProvider = new StgSharpTime();
MainTimeProvider.StartProvidingTime();
InternalIO.glfwInit();
InternalIO.InternalAppendLog("\n\n\n");
InternalIO.InternalAppendLog( "\n\n\n" );
InternalIO.InternalWriteLog(
$"Program {Assembly.GetEntryAssembly()!.FullName} Started.",
LogType.Info);
LogType.Info );
_mainThreadID = Environment.CurrentManagedThreadId;
}
public static void LogError(Exception ex)
public static void LogError( Exception ex )
{
InternalIO.InternalWriteLog(ex.Message, LogType.Error);
InternalIO.InternalWriteLog( ex.Message, LogType.Error );
}
public static void LogInfo(string log)
public static void LogInfo( string log )
{
InternalIO.InternalWriteLog(log, LogType.Info);
InternalIO.InternalWriteLog( log, LogType.Info );
}
public static void LogWarning(string log)
public static void LogWarning( string log )
{
InternalIO.InternalWriteLog(log, LogType.Warning);
}
public static void LogWarning(Exception notVerySeriesException)
{
InternalIO.InternalWriteLog(notVerySeriesException.Message, LogType.Warning);
InternalIO.InternalWriteLog( log, LogType.Warning );
}
public static void Mark(bool needConsole)
public static void LogWarning( Exception notVerySeriesException )
{
InternalIO.InternalWriteLog(
notVerySeriesException.Message, LogType.Warning );
}
public static void Mark( bool needConsole )
{
markCount++;
if (needConsole)
{
Console.WriteLine(markCount);
if( needConsole ) {
Console.WriteLine( markCount );
}
}
@@ -132,68 +134,60 @@ namespace StgSharp
bool isConsole,
[CallerFilePath] string filePath = "",
[CallerMemberName] string callerName = "",
[CallerLineNumber] int lineNumber = 0
)
[CallerLineNumber] int lineNumber = 0 )
{
Type t = target.GetType();
string log = $"Tracked object: {nameof(target)}\t\tType:{t.Name}\n";
FieldInfo[] fieldInfo = t.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
FieldInfo[] fieldInfo = t.GetFields(
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance );
log += "|\tFieldName\t|\tFieldType\t|\tFieldValue\t|\n";
foreach (FieldInfo field in fieldInfo)
{
foreach( FieldInfo field in fieldInfo ) {
log += $"|{field.Name}\t\t|{field.FieldType}\t\t|{field.GetValue(target)}\t\t|\n";
}
log += $"Tracking at:\n{filePath}\t{callerName}\tline {lineNumber}\n";
log += $"Additional information:\n{message}\n";
if (isConsole)
{
Console.WriteLine(log);
}
else
{
InternalIO.InternalWriteLog(log, LogType.Info);
if( isConsole ) {
Console.WriteLine( log );
} else {
InternalIO.InternalWriteLog( log, LogType.Info );
}
}
/// <summary>
/// Write a log message to log file, and mark the _level of this message.
/// </summary>
/// <param name="message">A string contains information of how current evironment runs.</param>
/// <param name="logType">The severity of current message.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLog(string message, LogType logType)
/// <param name="message"> A string contains information of how current evironment runs. </param>
/// <param name="logType"> The severity of current message. </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static void WriteLog( string message, LogType logType )
{
InternalIO.InternalWriteLog(message, logType);
InternalIO.InternalWriteLog( message, logType );
}
internal static TDele ConvertAPI<TDele>(IntPtr funcPtr)
internal static TDele ConvertAPI<TDele>( IntPtr funcPtr )
{
if (funcPtr == IntPtr.Zero)
{
throw new Exception("Failed to convert api, the function pointer is zero.");
if( funcPtr == IntPtr.Zero ) {
throw new Exception(
"Failed to convert api, the function pointer is zero." );
}
try
{
return Marshal.GetDelegateForFunctionPointer<TDele>(funcPtr);
try {
return Marshal.GetDelegateForFunctionPointer<TDele>( funcPtr );
}
catch (Exception)
{
catch( Exception ) {
throw;
}
}
internal static Delegate ConvertAPI(IntPtr funcPtr, Type T)
internal static Delegate ConvertAPI( IntPtr funcPtr, Type T )
{
if (funcPtr == IntPtr.Zero)
{
throw new Exception("Failed to convert api, the function pointer is zero.");
if( funcPtr == IntPtr.Zero ) {
throw new Exception(
"Failed to convert api, the function pointer is zero." );
}
try
{
return Marshal.GetDelegateForFunctionPointer(funcPtr, T);
try {
return Marshal.GetDelegateForFunctionPointer( funcPtr, T );
}
catch (Exception)
{
catch( Exception ) {
throw;
}
}
@@ -37,18 +37,16 @@ using System.Threading.Tasks;
namespace StgSharp
{
public static partial class StgSharp
{
private static ConcurrentDictionary<int, KeyStatus> keyListener
= new ConcurrentDictionary<int, KeyStatus>();
public static KeyStatus CheckKey(KeyboardKey key)
public static KeyStatus CheckKey( KeyboardKey key )
{
return keyListener.GetOrAdd((int)key, KeyStatus.RELEASE);
return keyListener.GetOrAdd( ( int )key, KeyStatus.RELEASE );
}
}
}
@@ -45,9 +45,7 @@ namespace StgSharp.Geometries
private CoordinationBase localCoordination;
private Matrix44 coordMat;
public CoordinationBase(
CoordinationBase localCoordination)
public CoordinationBase( CoordinationBase localCoordination )
{
this.localCoordination = localCoordination;
coordMat = new Matrix44();
@@ -55,23 +53,23 @@ namespace StgSharp.Geometries
public virtual Point LocalOrigin
{
get => new Point(coordMat.colum3.XYZ);
get => new Point( coordMat.colum3.XYZ );
internal set => coordMat.colum3.XYZ = value.Coord;
}
public virtual vec3d LocalX
public virtual Vec3 LocalX
{
get => coordMat.colum0.XYZ;
internal set => coordMat.colum0.XYZ = value;
}
public virtual vec3d LocalY
public virtual Vec3 LocalY
{
get => coordMat.colum1.XYZ;
internal set => coordMat.colum1.XYZ = value;
}
public virtual vec3d LocalZ
public virtual Vec3 LocalZ
{
get => coordMat.colum2.XYZ;
set => coordMat.colum2.XYZ = value;
@@ -41,23 +41,22 @@ namespace StgSharp.Geometries
{
private static PlainCoordinate statndardPlainCoordination = new PlainCoordinate(
null, new Point(0, 0, 0),
new vec3d(1, 0, 0),
new vec3d(0, 1, 0)
);
null, new Point( 0, 0, 0 ), new Vec3( 1, 0, 0 ),
new Vec3( 0, 1, 0 ) );
public PlainCoordinate(
CoordinationBase local,
Point origin,
vec3d xAxis,
vec3d yAxis
) : base(local)
Vec3 xAxis,
Vec3 yAxis )
: base( local )
{
CoordMat = Matrix44.Unit;
CoordMat.colum0 = new vec4d(xAxis, 0);
CoordMat.colum1 = new vec4d(yAxis, 0);
CoordMat.colum2 = new vec4d(Linear.Normalize(Vec3d.Cross(xAxis, yAxis)), 0);
CoordMat.colum0 = new Vec4( xAxis, 0 );
CoordMat.colum1 = new Vec4( yAxis, 0 );
CoordMat.colum2 = new Vec4(
Linear.Normalize( Vec3.Cross( xAxis, yAxis ) ), 0 );
LocalOrigin = origin;
}
@@ -40,11 +40,12 @@ namespace StgSharp.Geometries
{
public SpaceCoordinate(
CoordinationBase localCoordination, Point origin,
vec3d xAxis, vec3d yAxis, vec3d zAxis
) : base(localCoordination)
{
}
CoordinationBase localCoordination,
Point origin,
Vec3 xAxis,
Vec3 yAxis,
Vec3 zAxis )
: base( localCoordination ) { }
}
}
@@ -36,20 +36,19 @@ namespace StgSharp.Geometries
public unsafe class ToUpperDimensionException : Exception
{
protected ToUpperDimensionException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public ToUpperDimensionException()
{
}
protected ToUpperDimensionException(
SerializationInfo info,
StreamingContext context )
: base( info, context ) { }
public ToUpperDimensionException(string message) : base(message)
{
}
public ToUpperDimensionException() { }
public ToUpperDimensionException(string message, Exception innerException) : base(message, innerException)
{
}
public ToUpperDimensionException( string message ) : base( message ) { }
public ToUpperDimensionException(
string message,
Exception innerException )
: base( message, innerException ) { }
}
@@ -59,20 +58,17 @@ namespace StgSharp.Geometries
public class UnusedVertexException : Exception
{
protected UnusedVertexException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
public UnusedVertexException()
{
}
protected UnusedVertexException(
SerializationInfo info,
StreamingContext context )
: base( info, context ) { }
public UnusedVertexException(string message) : base(message)
{
}
public UnusedVertexException() { }
public UnusedVertexException(string message, Exception innerException) : base(message, innerException)
{
}
public UnusedVertexException( string message ) : base( message ) { }
public UnusedVertexException( string message, Exception innerException )
: base( message, innerException ) { }
}
}
@@ -39,8 +39,10 @@ using System.Text;
namespace StgSharp.Geometries
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate vec3d GeometryMotionDelegate(TimeSpanProvider timeSource, out float rotation);
[UnmanagedFunctionPointer( CallingConvention.Cdecl )]
public delegate Vec3 GeometryMotionDelegate(
TimeSpanProvider timeSource,
out float rotation );
public class GeometryMotion
{
@@ -54,69 +56,60 @@ namespace StgSharp.Geometries
public unsafe GeometryMotion(
bool isIncreament,
TimeSpanProvider timeSource,
GeometryMotionDelegate motionDelegate
)
GeometryMotionDelegate motionDelegate )
{
isIncrementMode = isIncreament;
time = timeSource;
if (motionDelegate == null)
{
handle = (IntPtr)(delegate*<TimeSpanProvider, out float, vec3d>)&defaultMotion;
if( motionDelegate == null ) {
handle = ( IntPtr )( delegate*<TimeSpanProvider, out float, Vec3> )&defaultMotion;
movement = defaultMotion;
}
else if (motionDelegate.Method.IsStatic)
{
} else if( motionDelegate.Method.IsStatic ) {
sourceIsStatic = true;
handle = Marshal.GetFunctionPointerForDelegate(motionDelegate);
handle = Marshal.GetFunctionPointerForDelegate( motionDelegate );
movement = motionDelegate;
}
else
{
} else {
movement = motionDelegate;
}
//sourceIsStatic = false;
}
public bool IsIncrement
{
get => isIncrementMode;
}
public static GeometryMotion DefaultMotion
{
get => new GeometryMotion(true, null, null);
get => new GeometryMotion( true, null, null );
}
public unsafe void RunMotion(ref vec3d coord, ref float rotation)
public unsafe void RunMotion( ref Vec3 coord, ref float rotation )
{
float rot;
vec3d vec;
if (sourceIsStatic)
{
vec = ((delegate* unmanaged[Cdecl]<TimeSpanProvider, out float, vec3d>)handle)(time, out rot);
}
else
{
vec = movement(time, out rot);
Vec3 vec;
if( sourceIsStatic ) {
vec = ( ( delegate* unmanaged[Cdecl]<TimeSpanProvider, out float, Vec3> )handle )(
time, out rot );
} else {
vec = movement( time, out rot );
}
if (isIncrementMode)
{
if( isIncrementMode ) {
coord += vec;
rotation += rot;
}
else
{
} else {
coord = vec;
rotation = rot;
}
}
private static vec3d defaultMotion(TimeSpanProvider provider, out float rotation)
private static Vec3 defaultMotion(
TimeSpanProvider provider,
out float rotation )
{
rotation = 0;
return Vec3d.Zero;
return Vec3.Zero;
}
}//------------------------------- End of Class -------------------------------
@@ -42,46 +42,46 @@ namespace StgSharp.Math
internal const float DegToRad = 180 / Scaler.Pi;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Cos(Radius r)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static float Cos( Radius r )
{
return MathF.Cos(r._radius);
return MathF.Cos( r._radius );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Cos(Degree r)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static float Cos( Degree r )
{
return MathF.Cos(r._degree / DegToRad);
return MathF.Cos( r._degree / DegToRad );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sin(Radius r)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static float Sin( Radius r )
{
return MathF.Sin(r._radius);
return MathF.Sin( r._radius );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sin(Degree r)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static float Sin( Degree r )
{
return MathF.Sin(r._degree / DegToRad);
return MathF.Sin( r._degree / DegToRad );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Tan(Radius r)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static float Tan( Radius r )
{
return MathF.Tan(r._radius);
return MathF.Tan( r._radius );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Tan(Degree r)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static float Tan( Degree r )
{
return MathF.Tan(r._degree / DegToRad);
return MathF.Tan( r._degree / DegToRad );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Degree ToDegree(float value)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static Degree ToDegree( float value )
{
return new Degree(value);
return new Degree( value );
}
}
@@ -91,14 +91,14 @@ namespace StgSharp.Math
internal float _degree;
internal Degree(float dgree)
internal Degree( float dgree )
{
_degree = dgree;
}
public static implicit operator Radius(Degree d)
public static implicit operator Radius( Degree d )
{
return new Radius(d._degree / GeometryScaler.DegToRad);
return new Radius( d._degree / GeometryScaler.DegToRad );
}
}
@@ -108,70 +108,70 @@ namespace StgSharp.Math
internal float _radius;
[Obsolete("Unsafe, you may forget this is radius.", true)]
[Obsolete( "Unsafe, you may forget this is radius.", true )]
public Radius() { }
public Radius(float radius)
public Radius( float radius )
{
_radius = radius;
}
public static Radius Zero
{
get => new Radius(0);
get => new Radius( 0 );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator -(Radius r)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static Radius operator -( Radius r )
{
return new Radius(-r._radius);
return new Radius( -r._radius );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator -(Radius left, Radius Right)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static Radius operator -( Radius left, Radius Right )
{
return new Radius(left._radius - Right._radius);
return new Radius( left._radius - Right._radius );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Radius left, Radius right)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool operator !=( Radius left, Radius right )
{
return left._radius != right._radius;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator *(Radius left, float right)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static Radius operator *( Radius left, float right )
{
return new Radius(left._radius * right);
return new Radius( left._radius * right );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator /(Radius left, float right)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static Radius operator /( Radius left, float right )
{
return new Radius(left._radius / right);
return new Radius( left._radius / right );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float operator /(Radius left, Radius right)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static float operator /( Radius left, Radius right )
{
return left._radius / right._radius;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator +(Radius left, Radius Right)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static Radius operator +( Radius left, Radius Right )
{
return new Radius(left._radius + Right._radius);
return new Radius( left._radius + Right._radius );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Radius left, Radius right)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static bool operator ==( Radius left, Radius right )
{
return left._radius == right._radius;
}
public static implicit operator Degree(Radius r)
public static implicit operator Degree( Radius r )
{
return new Degree((r._radius * 180) / Scaler.Pi);
return new Degree( ( r._radius * 180 ) / Scaler.Pi );
}
}
+9 -5
View File
@@ -42,19 +42,23 @@ namespace StgSharp.Geometries
public interface IGeometry
{
public Point this[int index]
public Point this[ int index ]
{
get;
set;
}
#pragma warning disable CA1819
public vec4d[] VertexStream
#pragma warning restore CA1819
#pragma warning disable CA1819
public Vec4[] VertexStream
#pragma warning restore CA1819
{
get;
}
public CoordinationBase Coordination
{
get;
}
public CoordinationBase Coordination { get; }
public int VertexCount
{
@@ -36,9 +36,5 @@ using System.Threading.Tasks;
namespace StgSharp.Geometries
{
public interface IGeomtryBuffer
{
}
public interface IGeomtryBuffer { }
}
+14 -13
View File
@@ -45,24 +45,25 @@ namespace StgSharp.Geometries
public float Rotation
{
get { return GlobalBuffer.CoordAndRotationList[BufferId].W; }
get { return GlobalBuffer.CoordAndRotationList[ BufferId ].W; }
set
{
vec4d temp = GlobalBuffer.CoordAndRotationList[BufferId];
Vec4 temp = GlobalBuffer.CoordAndRotationList[ BufferId ];
temp.W = value;
GlobalBuffer.CoordAndRotationList[BufferId] = temp;
GlobalBuffer.CoordAndRotationList[ BufferId ] = temp;
}
}
public float Scale
{
get { return GlobalBuffer.ScalingList[BufferId]; }
set { GlobalBuffer.ScalingList[BufferId] = value; }
get { return GlobalBuffer.ScalingList[ BufferId ]; }
set { GlobalBuffer.ScalingList[ BufferId ] = value; }
}
public GeometryMotion Motion
{
get; set;
get;
set;
}
public IInstancingBuffer GlobalBuffer
@@ -77,25 +78,25 @@ namespace StgSharp.Geometries
internal set;
}
public vec3d CenterPositionGlobal
public Vec3 CenterPositionGlobal
{
get;
internal set;
}
public vec3d Coord
public Vec3 Coord
{
get { return GlobalBuffer.CoordAndRotationList[BufferId].XYZ; }
set { GlobalBuffer.CoordAndRotationList[BufferId] = new vec4d(value.vec); }
get { return GlobalBuffer.CoordAndRotationList[ BufferId ].XYZ; }
set { GlobalBuffer.CoordAndRotationList[ BufferId ] = new Vec4(
value.vec ); }
}
public void Move()
{
(vec3d coord, float rotation) = (Coord, Rotation);
Motion.RunMotion(ref coord, ref rotation);
(Vec3 coord, float rotation) = (Coord, Rotation);
Motion.RunMotion( ref coord, ref rotation );
(Coord, Rotation) = (coord, rotation);
}
}
}
@@ -39,19 +39,35 @@ namespace StgSharp.Geometries
public interface IInstancingBuffer
{
public Span<vec4d> CoordAndRotationSpan { get; }
public Span<Vec4> CoordAndRotationSpan
{
get;
}
public Span<float> ScalingSpan { get; }
public Span<float> ScalingSpan
{
get;
}
internal IGeometry TypicalShape { get; }
internal IGeometry TypicalShape
{
get;
}
internal List<IInstancing> InstanceList { get; }
internal List<IInstancing> InstanceList
{
get;
}
internal List<vec4d> CoordAndRotationList { get; }
internal List<float> ScalingList { get; }
internal List<Vec4> CoordAndRotationList
{
get;
}
internal List<float> ScalingList
{
get;
}
}
}
@@ -40,7 +40,7 @@ using System.Threading.Tasks;
namespace StgSharp.Geometries
{
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public struct PartialPlainCoordinate
{
@@ -49,40 +49,36 @@ namespace StgSharp.Geometries
/// <summary>
/// The origin of this coordinate.
/// </summary>
public vec3d origin;
public Vec3 origin;
public PartialPlainCoordinate
(
vec3d origin,
vec3d horiziontial,
vec3d vertical
)
public PartialPlainCoordinate(
Vec3 origin,
Vec3 horiziontial,
Vec3 vertical )
{
this.origin = origin;
axis = new Matrix32();
#if NET5_0_OR_GREATER
Unsafe.SkipInit(out axis.mat);
#endif
#if NET5_0_OR_GREATER
Unsafe.SkipInit( out axis.mat );
#endif
axis.colum0 = horiziontial;
axis.colum1 = vertical;
}
/// <summary>
/// The horizontial axis of the coordinate.
/// Point to the right direction.
/// The horizontial axis of the coordinate. Point to the right direction.
/// </summary>
public vec3d axis_H => axis.colum0;
public Vec3 axis_H => axis.colum0;
/// <summary>
/// The vertical axis of the coordinate.
/// Point to the top direction.
/// The vertical axis of the coordinate. Point to the top direction.
/// </summary>
public vec3d axis_V => axis.colum1;
public Vec3 axis_V => axis.colum1;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public vec3d GetRealLocate(vec2d raletiveLocation)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public Vec3 GetRealLocate( Vec2 raletiveLocation )
{
return origin + axis.VerticalVecMultiply(raletiveLocation);
return origin + axis.VerticalVecMultiply( raletiveLocation );
}
}
@@ -34,16 +34,14 @@ using System.Runtime.CompilerServices;
namespace StgSharp.Geometries
{
public static unsafe class GeometryOperation
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static vec3d DefaultMotion(int tick)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static Vec3 DefaultMotion( int tick )
{
return default(vec3d);
return default( Vec3 );
}
}
}
@@ -38,39 +38,39 @@ using System.Threading.Tasks;
namespace StgSharp.Geometries
{
public interface IPlainEntity
{
public vec2d CenterPosition { get; set; }
public Vec2 CenterPosition
{
get;
set;
}
public bool CollideWith(IPlainEntity entity);
public bool CollideWith( IPlainEntity entity );
}
public class PlainEntity : IPlainEntity
{
private PlainGeometry _shape;
public PlainEntity(PlainGeometry shape)
public PlainEntity( PlainGeometry shape )
{
_shape = shape;
}
bool IPlainEntity.CollideWith(IPlainEntity entity)
bool IPlainEntity.CollideWith( IPlainEntity entity )
{
throw new NotImplementedException();
}
vec2d IPlainEntity.CenterPosition
Vec2 IPlainEntity.CenterPosition
{
get => _shape.Coordination.LocalOrigin.Coord.XY;
set => throw new InvalidOperationException();
}
}
}
@@ -43,15 +43,14 @@ namespace StgSharp.Geometries
public class ParticleOnPlain : IInstancing, IPlainEntity
{
public ParticleOnPlain(PlainInstancingBuffer<ParticleOnPlain> buffer)
public ParticleOnPlain( PlainInstancingBuffer<ParticleOnPlain> buffer )
{
if (buffer == null)
{
throw new ArgumentNullException(paramName: nameof(buffer));
if( buffer == null ) {
throw new ArgumentNullException( paramName: nameof( buffer ) );
}
GlobalBuffer = buffer;
BufferId = buffer.CreateInstanceID();
((IInstancingBuffer)buffer).InstanceList.Add(this);
( ( IInstancingBuffer )buffer ).InstanceList.Add( this );
}
public GeometryMotion Motion
@@ -72,21 +71,20 @@ namespace StgSharp.Geometries
set;
}
vec3d IInstancing.CenterPositionGlobal
Vec3 IInstancing.CenterPositionGlobal
{
get;
set;
}
bool IPlainEntity.CollideWith(IPlainEntity entity)
bool IPlainEntity.CollideWith( IPlainEntity entity )
{
throw new NotImplementedException();
}
vec2d IPlainEntity.CenterPosition
Vec2 IPlainEntity.CenterPosition
{
get => GlobalBuffer.CoordAndRotationList[BufferId].XY;
get => GlobalBuffer.CoordAndRotationList[ BufferId ].XY;
set => throw new NotImplementedException();
}
@@ -42,33 +42,31 @@ namespace StgSharp.Geometries
public abstract class PlainGeometry : IGeometry
{
protected vec4d[] vertexMat;
protected Vec4[] vertexMat;
internal CoordinationBase coordinate;
internal PlainGeometry(CoordinationBase coordination)
internal PlainGeometry( CoordinationBase coordination )
{
coordinate = coordination;
}
public Point this[int index]
public Point this[ int index ]
{
get => new Point(vertexMat[index]);
set => vertexMat[index].vec = value.coordVec;
get => new Point( vertexMat[ index ] );
set => vertexMat[ index ].vec = value.coordVec;
}
public int VertexCount => this.vertexMat.Length;
public abstract ReadOnlySpan<int> VertexIndices { get; }
public abstract ReadOnlySpan<int> VertexIndices
{
get;
}
#pragma warning disable CA1819
public vec4d[] VertexStream => vertexMat;
#pragma warning disable CA1819
public Vec4[] VertexStream => vertexMat;
public CoordinationBase Coordination => this.coordinate;
#pragma warning restore CA1819
}
}
@@ -44,26 +44,24 @@ using System.Threading.Tasks;
namespace StgSharp.Geometries
{
public class PlainInstancingBuffer<T> :
IDisposable, IEnumerable<T>, IInstancingBuffer
where T :
IInstancing
public class PlainInstancingBuffer<T> : IDisposable, IEnumerable<T>, IInstancingBuffer
where T: IInstancing
{
private bool disposedValue;
private CoordinatePlain globalCorrdinnate;
private List<vec4d> coordList;
private List<Vec4> coordList;
private List<IInstancing> instanceList;
private List<float> scalingList;
private Mutex mutex;
public PlainInstancingBuffer()
{
coordList = new List<vec4d>(capacity: 100);
instanceList = new List<IInstancing>(capacity: 100);
scalingList = new List<float>(capacity: 100);
coordArray = Array.Empty<vec4d>();
coordList = new List<Vec4>( capacity: 100 );
instanceList = new List<IInstancing>( capacity: 100 );
scalingList = new List<float>( capacity: 100 );
coordArray = Array.Empty<Vec4>();
scaleArray = Array.Empty<float>();
mutex = new Mutex();
}
@@ -73,7 +71,7 @@ namespace StgSharp.Geometries
get => instanceList;
}
public List<vec4d> CoordAndRotationList
public List<Vec4> CoordAndRotationList
{
get => coordList;
}
@@ -83,25 +81,25 @@ namespace StgSharp.Geometries
get => scalingList;
}
public Span<vec4d> CoordAndRotationSpan
public Span<Vec4> CoordAndRotationSpan
{
get
{
if (coordArray.Length != coordList.Capacity)
{
FieldInfo fieldInfo = typeof(List<vec4d>).
GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo == null)
{
#pragma warning disable CA1065
#pragma warning disable CA2201
if( coordArray.Length != coordList.Capacity ) {
FieldInfo fieldInfo = typeof( List<Vec4> ).
GetField(
"_items",
BindingFlags.NonPublic | BindingFlags.Instance );
if( fieldInfo == null ) {
#pragma warning disable CA1065
#pragma warning disable CA2201
throw new NullReferenceException();
#pragma warning restore CA2201
#pragma warning restore CA1065
#pragma warning restore CA2201
#pragma warning restore CA1065
}
coordArray = (vec4d[])fieldInfo.GetValue(coordList);
coordArray = ( Vec4[] )fieldInfo.GetValue( coordList );
}
return new Span<vec4d>(coordArray, 0, coordList.Count);
return new Span<Vec4>( coordArray, 0, coordList.Count );
}
}
@@ -109,21 +107,21 @@ namespace StgSharp.Geometries
{
get
{
if (scaleArray.Length != coordList.Capacity)
{
FieldInfo fieldInfo = typeof(List<float>).
GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldInfo == null)
{
#pragma warning disable CA1065
#pragma warning disable CA2201
if( scaleArray.Length != coordList.Capacity ) {
FieldInfo fieldInfo = typeof( List<float> ).
GetField(
"_items",
BindingFlags.NonPublic | BindingFlags.Instance );
if( fieldInfo == null ) {
#pragma warning disable CA1065
#pragma warning disable CA2201
throw new NullReferenceException();
#pragma warning restore CA2201
#pragma warning restore CA1065
#pragma warning restore CA2201
#pragma warning restore CA1065
}
scaleArray = (float[])fieldInfo.GetValue(scalingList);
scaleArray = ( float[] )fieldInfo.GetValue( scalingList );
}
return new Span<float>(scaleArray, 0, coordList.Count);
return new Span<float>( scaleArray, 0, coordList.Count );
}
}
@@ -131,8 +129,8 @@ namespace StgSharp.Geometries
{
mutex.WaitOne();
int ret = instanceList.Count;
coordList.Add(new vec4d());
scalingList.Add(0);
coordList.Add( new Vec4() );
scalingList.Add( 0 );
mutex.ReleaseMutex();
return ret;
}
@@ -144,55 +142,51 @@ namespace StgSharp.Geometries
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
Dispose( disposing: true );
GC.SuppressFinalize( this );
}
public IEnumerator<T> GetEnumerator()
{
foreach (IInstancing item in instanceList)
{
yield return (T)item;
foreach( IInstancing item in instanceList ) {
yield return ( T )item;
}
}
public void Remove(T instance)
public void Remove( T instance )
{
mutex.WaitOne();
if (instance.GlobalBuffer != this)
{
if( instance.GlobalBuffer != this ) {
throw new ArgumentException(
message: "instance does not belong to current Particle Buffer",
paramName: nameof(instance));
paramName: nameof( instance ) );
}
int index = instance.BufferId;
IInstancing temp = instanceList[instanceList.Count - 1];
instanceList[instance.BufferId] = temp;
IInstancing temp = instanceList[ instanceList.Count - 1 ];
instanceList[ instance.BufferId ] = temp;
temp.BufferId = instance.BufferId;
coordList[instance.BufferId] = coordList[coordList.Count - 1];
scalingList[instance.BufferId] = scalingList[scalingList.Count - 1];
coordList[ instance.BufferId ] = coordList[ coordList.Count - 1 ];
scalingList[ instance.BufferId ] = scalingList[
scalingList.Count - 1 ];
instanceList.RemoveAt(instanceList.Count - 1);
coordList.RemoveAt(coordList.Count - 1);
scalingList.RemoveAt(scalingList.Count - 1);
instanceList.RemoveAt( instanceList.Count - 1 );
coordList.RemoveAt( coordList.Count - 1 );
scalingList.RemoveAt( scalingList.Count - 1 );
mutex.ReleaseMutex();
}
public void UpdateAllParticles()
{
foreach (IInstancing particle in instanceList)
{
foreach( IInstancing particle in instanceList ) {
particle.Move();
}
}
protected virtual void Dispose(bool disposing)
protected virtual void Dispose( bool disposing )
{
if (!disposedValue)
{
if (disposing)
{
if( !disposedValue ) {
if( disposing ) {
mutex.Dispose();
}
@@ -205,21 +199,19 @@ namespace StgSharp.Geometries
IEnumerator IEnumerable.GetEnumerator()
{
foreach (IInstancing item in instanceList)
{
yield return (T)item;
foreach( IInstancing item in instanceList ) {
yield return ( T )item;
}
}
IGeometry IInstancingBuffer.TypicalShape => throw new NotImplementedException();
IGeometry IInstancingBuffer.TypicalShape => throw new NotImplementedException(
);
#region field of mem opt
vec4d[] coordArray;
float[] scaleArray;
#endregion
private Vec4[] coordArray;
private float[] scaleArray;
#endregion
}
}
@@ -38,52 +38,50 @@ namespace StgSharp.Geometries
public class Parallelogram : Polygon4
{
internal readonly Func<int, vec3d> movCenterOperation =
new Func<int, vec3d>(GeometryOperation.DefaultMotion);
internal readonly Func<int, Vec3> movCenterOperation =
new Func<int, Vec3>( GeometryOperation.DefaultMotion );
internal Point center;
public Parallelogram(
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y,
float v3x, float v3y
) : base(
v0x, v0y, v1x, v1y,
v2x, v2y, v3x, v3y
)
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( v0x, v0y, v1x, v1y, v2x, v2y, v3x, v3y )
{
#if DEBUG
if (
this[0].Coord + this[2].Coord !=
this[1].Coord + this[3].Coord
)
{
InternalIO.InternalWriteLog("Init of geometry item failed, because four vertices cannot form a rectangle.", LogType.Warning);
#if DEBUG
if( this[ 0 ].Coord + this[ 2 ].Coord != this[ 1 ].Coord + this[ 3 ].Coord ) {
InternalIO.InternalWriteLog(
"Init of geometry item failed, because four vertices cannot form a rectangle.",
LogType.Warning );
}
#endif
#endif
}
public Parallelogram(
PlainCoordinate coordination,
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y,
float v3x, float v3y
) : base(coordination,
v0x, v0y, v1x, v1y,
v2x, v2y, v3x, v3y
)
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( coordination, v0x, v0y, v1x, v1y, v2x, v2y, v3x, v3y )
{
#if DEBUG
if (
this[0].Coord + this[2].Coord !=
this[1].Coord + this[3].Coord
)
{
InternalIO.InternalWriteLog("Init of geometry item failed, because four vertices cannot form a rectangle.", LogType.Warning);
#if DEBUG
if( this[ 0 ].Coord + this[ 2 ].Coord != this[ 1 ].Coord + this[ 3 ].Coord ) {
InternalIO.InternalWriteLog(
"Init of geometry item failed, because four vertices cannot form a rectangle.",
LogType.Warning );
}
#endif
#endif
}
}
@@ -38,52 +38,54 @@ namespace StgSharp.Geometries
{
internal readonly float d = -1;
internal vec3d origin;
internal Vec3 origin;
internal vec3d plainParameter;
internal vec3d vec1;
internal vec3d vec2;
internal Vec3 plainParameter;
internal Vec3 vec1;
internal Vec3 vec2;
internal Plain(Vector4 origin, Vector4 p1, Vector4 p2)
internal Plain( Vector4 origin, Vector4 p1, Vector4 p2 )
{
this.origin = new vec3d(origin);
this.origin = new Vec3( origin );
vec1 = new vec3d(p1 - origin);
vec2 = new vec3d(p2 - origin);
vec1 = new Vec3( p1 - origin );
vec2 = new Vec3( p2 - origin );
}
public Plain(vec3d o, vec3d v1, vec3d v2)
public Plain( Vec3 o, Vec3 v1, Vec3 v2 )
{
this.origin = o;
this.vec1 = v1 - (v2 * (v1.Y / v2.Y)); //计算平面在xz平面上的方向投影
this.vec2 = v2 - (vec1 * (v2.X / v1.X)); //计算平面在yz平面上的方向投影
this.vec1 = v1 - ( v2 * ( v1.Y / v2.Y ) ); //计算平面在xz平面上的方向投影
this.vec2 = v2 - ( vec1 * ( v2.X / v1.X ) ); //计算平面在yz平面上的方向投影
//|origin|-k1*|vec1|-k2*|vec2|计算plainParameter.Z;
plainParameter.Z = origin.Z - (vec1.Z * (origin.X / vec1.X)) - (vec2.Z * (origin.Y / vec2.Y));
plainParameter.Z = origin.Z - ( vec1.Z * ( origin.X / vec1.X ) ) - ( vec2.Z * ( origin.Y / vec2.Y ) );
//根据plainParameter.Z和对应的方向矢量计算plainParameter.X和plainParameter.Y
plainParameter.X = vec1.X * (vec1.Z / plainParameter.Z);
plainParameter.Y = vec2.Y * (vec2.Z / plainParameter.Z);
plainParameter.X = vec1.X * ( vec1.Z / plainParameter.Z );
plainParameter.Y = vec2.Y * ( vec2.Z / plainParameter.Z );
plainParameter.X = 1 / plainParameter.X;
plainParameter.Y = 1 / plainParameter.Y;
plainParameter.Z = 1 / plainParameter.Z;
}
public Plain(Point p1, Point p2, Point p3)
public Plain( Point p1, Point p2, Point p3 )
{
vec3d origin = p1.Coord;
vec3d v1 = p2.Coord - origin;
vec3d v2 = p3.Coord - origin;
Vec3 origin = p1.Coord;
Vec3 v1 = p2.Coord - origin;
Vec3 v2 = p3.Coord - origin;
vec1 = v1 - (v2 * (v1.Y / v2.Y)); //计算平面在xz平面上的方向投影
vec2 = v2 - (vec1 * (v2.X / v1.X)); //计算平面在yz平面上的方向投影
vec1 = v1 - ( v2 * ( v1.Y / v2.Y ) ); //计算平面在xz平面上的方向投影
vec2 = v2 - ( vec1 * ( v2.X / v1.X ) ); //计算平面在yz平面上的方向投影
//|origin|-k1*|vec1|-k2*|vec2|计算plainParameter.Z;
plainParameter.Z = origin.Z - (vec1.Z * (origin.X / vec1.X)) - (vec2.Z * (origin.Y / vec2.Y));
plainParameter.Z = origin.Z - ( vec1.Z * ( origin.X / vec1.X ) ) - ( vec2.Z * ( origin.Y / vec2.Y ) );
//根据plainParameter.Z和对应的方向矢量计算plainParameter.X和plainParameter.Y
plainParameter.X = vec1.X * (vec1.Z / plainParameter.Z);
plainParameter.Y = vec2.Y * (vec2.Z / plainParameter.Z);
plainParameter.X = vec1.X * ( vec1.Z / plainParameter.Z );
plainParameter.Y = vec2.Y * ( vec2.Z / plainParameter.Z );
plainParameter.X = 1 / plainParameter.X;
plainParameter.Y = 1 / plainParameter.Y;
@@ -41,17 +41,17 @@ namespace StgSharp.Geometries
protected static int[] Indices = [0, 1, 2, 0, 2, 3];
internal Polygon4() : base(PlainCoordinate.StandardPlainCoordination)
internal Polygon4()
: base( PlainCoordinate.StandardPlainCoordination )
{
vertexMat = new vec4d[4];
vertexMat = new Vec4[4];
}
internal Polygon4(vec4d[] rawCoord) :
base(PlainCoordinate.StandardPlainCoordination)
internal Polygon4( Vec4[] rawCoord )
: base( PlainCoordinate.StandardPlainCoordination )
{
if (rawCoord.Length != 4)
{
throw new ArgumentOutOfRangeException(nameof(rawCoord));
if( rawCoord.Length != 4 ) {
throw new ArgumentOutOfRangeException( nameof( rawCoord ) );
}
vertexMat = rawCoord;
}
@@ -60,61 +60,67 @@ namespace StgSharp.Geometries
Point topLeft,
Point topRight,
Point bottomRight,
Point bottomLeft
) : base(PlainCoordinate.StandardPlainCoordination)
Point bottomLeft )
: base( PlainCoordinate.StandardPlainCoordination )
{
this[0] = topLeft;
this[1] = topRight;
this[2] = bottomRight;
this[3] = bottomLeft;
this[ 0 ] = topLeft;
this[ 1 ] = topRight;
this[ 2 ] = bottomRight;
this[ 3 ] = bottomLeft;
}
public Polygon4(CoordinationBase coordinate,
public Polygon4(
CoordinationBase coordinate,
PlainCoordinate coordination,
Point topLeft,
Point topRight,
Point bottomRight,
Point bottomLeft
) : base(coordinate)
Point bottomLeft )
: base( coordinate )
{
this[0] = topLeft;
this[1] = topRight;
this[2] = bottomRight;
this[3] = bottomLeft;
this[ 0 ] = topLeft;
this[ 1 ] = topRight;
this[ 2 ] = bottomRight;
this[ 3 ] = bottomLeft;
}
public Polygon4(
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y,
float v3x, float v3y
) : base(PlainCoordinate.StandardPlainCoordination)
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( PlainCoordinate.StandardPlainCoordination )
{
vertexMat = new vec4d[4];
vertexMat = new Vec4[4];
this[0] = new Point(v0x, v0y, 0);
this[1] = new Point(v1x, v1y, 0);
this[2] = new Point(v2x, v2y, 0);
this[3] = new Point(v3x, v3y, 0);
this[ 0 ] = new Point( v0x, v0y, 0 );
this[ 1 ] = new Point( v1x, v1y, 0 );
this[ 2 ] = new Point( v2x, v2y, 0 );
this[ 3 ] = new Point( v3x, v3y, 0 );
}
public Polygon4(
PlainCoordinate coordination,
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y,
float v3x, float v3y
) : base(coordination)
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( coordination )
{
vertexMat = new vec4d[4];
vertexMat = new Vec4[4];
this[0] = new Point(v0x, v0y, 0);
this[1] = new Point(v1x, v1y, 0);
this[2] = new Point(v2x, v2y, 0);
this[3] = new Point(v3x, v3y, 0);
this[ 0 ] = new Point( v0x, v0y, 0 );
this[ 1 ] = new Point( v1x, v1y, 0 );
this[ 2 ] = new Point( v2x, v2y, 0 );
this[ 3 ] = new Point( v3x, v3y, 0 );
}
public override ReadOnlySpan<int> VertexIndices => Indices;
@@ -41,42 +41,53 @@ namespace StgSharp.Geometries
internal static int[] Indices = [0, 1, 2, 0, 2, 3, 0, 3, 4];
public unsafe Polygon5() : base(PlainCoordinate.StandardPlainCoordination)
public unsafe Polygon5()
: base( PlainCoordinate.StandardPlainCoordination )
{
vertexMat = new vec4d[5];
vertexMat = new Vec4[5];
}
public Polygon5(
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y,
float v3x, float v3y,
float v4x, float v4y
) : base(PlainCoordinate.StandardPlainCoordination)
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y,
float v4x,
float v4y )
: base( PlainCoordinate.StandardPlainCoordination )
{
vertexMat = new vec4d[5];
this[0] = new Point(v0x, v0y, 0);
this[1] = new Point(v1x, v1y, 0);
this[2] = new Point(v2x, v2y, 0);
this[3] = new Point(v3x, v3y, 0);
this[4] = new Point(v4x, v4y, 0);
vertexMat = new Vec4[5];
this[ 0 ] = new Point( v0x, v0y, 0 );
this[ 1 ] = new Point( v1x, v1y, 0 );
this[ 2 ] = new Point( v2x, v2y, 0 );
this[ 3 ] = new Point( v3x, v3y, 0 );
this[ 4 ] = new Point( v4x, v4y, 0 );
}
public Polygon5(
PlainCoordinate coordination,
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y,
float v3x, float v3y,
float v4x, float v4y
) : base(coordination)
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y,
float v4x,
float v4y )
: base( coordination )
{
vertexMat = new vec4d[5];
this[0] = new Point(v0x, v0y, 0);
this[1] = new Point(v1x, v1y, 0);
this[2] = new Point(v2x, v2y, 0);
this[3] = new Point(v3x, v3y, 0);
this[4] = new Point(v4x, v4y, 0);
vertexMat = new Vec4[5];
this[ 0 ] = new Point( v0x, v0y, 0 );
this[ 1 ] = new Point( v1x, v1y, 0 );
this[ 2 ] = new Point( v2x, v2y, 0 );
this[ 3 ] = new Point( v3x, v3y, 0 );
this[ 4 ] = new Point( v4x, v4y, 0 );
}
public override ReadOnlySpan<int> VertexIndices => Indices;
@@ -41,30 +41,31 @@ namespace StgSharp.Geometries
internal static int[] Indices = [0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5];
public Polygon6() : base(PlainCoordinate.StandardPlainCoordination)
public Polygon6()
: base( PlainCoordinate.StandardPlainCoordination )
{
vertexMat = new vec4d[6];
vertexMat = new Vec4[6];
}
public Polygon6(
PlainCoordinate coordination,
vec2d vert0,
vec2d vert1,
vec2d vert2,
vec2d vert3,
vec2d vert4,
vec2d vert5,
vec2d vert6
) : base(coordination)
Vec2 vert0,
Vec2 vert1,
Vec2 vert2,
Vec2 vert3,
Vec2 vert4,
Vec2 vert5,
Vec2 vert6 )
: base( coordination )
{
vertexMat = new vec4d[6];
vertexMat[0].vec = vert0.vec;
vertexMat[1].vec = vert1.vec;
vertexMat[2].vec = vert2.vec;
vertexMat[3].vec = vert3.vec;
vertexMat[4].vec = vert4.vec;
vertexMat[5].vec = vert5.vec;
vertexMat[6].vec = vert6.vec;
vertexMat = new Vec4[6];
vertexMat[ 0 ].vec = vert0.vec;
vertexMat[ 1 ].vec = vert1.vec;
vertexMat[ 2 ].vec = vert2.vec;
vertexMat[ 3 ].vec = vert3.vec;
vertexMat[ 4 ].vec = vert4.vec;
vertexMat[ 5 ].vec = vert5.vec;
vertexMat[ 6 ].vec = vert6.vec;
}
public override ReadOnlySpan<int> VertexIndices => Indices;
@@ -38,59 +38,54 @@ namespace StgSharp.Geometries
{
public Rectangle(
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y,
float v3x, float v3y
) : base(
v0x, v0y,
v1x, v1y,
v2x, v2y,
v3x, v3y
)
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( v0x, v0y, v1x, v1y, v2x, v2y, v3x, v3y )
{
#if DEBUG
vec2d side0 = (this[0].Coord - this[1].Coord).XY;
vec2d side1 = (this[2].Coord - this[1].Coord).XY;
if (side0.Cross(side1) == 0)
{
#if DEBUG
Vec2 side0 = ( this[ 0 ].Coord - this[ 1 ].Coord ).XY;
Vec2 side1 = ( this[ 2 ].Coord - this[ 1 ].Coord ).XY;
if( side0.Cross( side1 ) == 0 ) {
throw new ArgumentException();
}
#endif
#endif
}
public Rectangle(
PlainCoordinate coordination,
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y,
float v3x, float v3y
) : base(coordination,
v0x, v0y,
v1x, v1y,
v2x, v2y,
v3x, v3y
)
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( coordination, v0x, v0y, v1x, v1y, v2x, v2y, v3x, v3y )
{
#if DEBUG
vec2d side0 = (this[0].Coord - this[1].Coord).XY;
vec2d side1 = (this[2].Coord - this[1].Coord).XY;
if (side0.Cross(side1) == 0)
{
#if DEBUG
Vec2 side0 = ( this[ 0 ].Coord - this[ 1 ].Coord ).XY;
Vec2 side1 = ( this[ 2 ].Coord - this[ 1 ].Coord ).XY;
if( side0.Cross( side1 ) == 0 ) {
throw new ArgumentException();
}
#endif
#endif
}
/// <summary>
/// Calculate movement to center
/// </summary>
/// <param name="tick">CurrentBlueprint time tick</param>
/// <param name="tick"> CurrentBlueprint time tick </param>
/// <returns></returns>
public virtual vec3d MovCenter(uint tick)
public virtual Vec3 MovCenter( uint tick )
{
return default(vec3d);
return default( Vec3 );
}
}
@@ -34,7 +34,6 @@ using System.Numerics;
namespace StgSharp.Geometries
{
/// <summary>
/// A square
/// </summary>
@@ -42,21 +41,18 @@ namespace StgSharp.Geometries
{
public Square(
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y,
float v3x, float v3y)
: base(v0x, v0y,
v1x, v1y,
v2x, v2y,
v3x, v3y)
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y,
float v3x,
float v3y )
: base( v0x, v0y, v1x, v1y, v2x, v2y, v3x, v3y )
{
if (true)
{
}
if( true ) { }
}
}
}
@@ -37,60 +37,64 @@ using System.Numerics;
namespace StgSharp.Geometries
{
public unsafe class Triangle : PlainGeometry
{
internal static int[] Indices = [0, 1, 2];
public Triangle() : base(PlainCoordinate.StandardPlainCoordination)
public Triangle()
: base( PlainCoordinate.StandardPlainCoordination )
{
vertexMat = new vec4d[3];
vertexMat = new Vec4[3];
}
public Triangle( Point vertex01, Point vertex02, Point vertex03 )
: base( PlainCoordinate.StandardPlainCoordination )
{
this[ 0 ] = vertex01;
this[ 1 ] = vertex02;
this[ 2 ] = vertex03;
}
public Triangle(
PlainCoordinate coordination,
Point vertex01,
Point vertex02,
Point vertex03
) : base(PlainCoordinate.StandardPlainCoordination)
Point vertex03 )
: base( coordination )
{
this[0] = vertex01;
this[1] = vertex02;
this[2] = vertex03;
}
public Triangle(PlainCoordinate coordination,
Point vertex01,
Point vertex02,
Point vertex03
) : base(coordination)
{
this[0] = vertex01;
this[1] = vertex02;
this[2] = vertex03;
this[ 0 ] = vertex01;
this[ 1 ] = vertex02;
this[ 2 ] = vertex03;
}
public Triangle(
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y
) : base(PlainCoordinate.StandardPlainCoordination)
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y )
: base( PlainCoordinate.StandardPlainCoordination )
{
this[0] = new Point(v0x, v0y, 0);
this[1] = new Point(v1x, v1y, 0);
this[2] = new Point(v2x, v2y, 0);
this[ 0 ] = new Point( v0x, v0y, 0 );
this[ 1 ] = new Point( v1x, v1y, 0 );
this[ 2 ] = new Point( v2x, v2y, 0 );
}
public Triangle(PlainCoordinate coordination,
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y
) : base(coordination)
public Triangle(
PlainCoordinate coordination,
float v0x,
float v0y,
float v1x,
float v1y,
float v2x,
float v2y )
: base( coordination )
{
this[0] = new Point(v0x, v0y, 0);
this[1] = new Point(v1x, v1y, 0);
this[2] = new Point(v2x, v2y, 0);
this[ 0 ] = new Point( v0x, v0y, 0 );
this[ 1 ] = new Point( v1x, v1y, 0 );
this[ 2 ] = new Point( v2x, v2y, 0 );
}
public override ReadOnlySpan<int> VertexIndices => Indices;
+13 -11
View File
@@ -38,37 +38,39 @@ using System.Text;
namespace StgSharp.Geometries
{
[StructLayout(LayoutKind.Explicit, Size = 16)]
[StructLayout( LayoutKind.Explicit, Size = 16 )]
public struct Point
{
[FieldOffset(0)] private vec3d coord;
[FieldOffset(0)] internal Vector4 coordVec;
[FieldOffset( 0 )] private Vec3 coord;
[FieldOffset( 0 )] internal Vector4 coordVec;
internal Point(vec4d vector)
internal Point( Vec4 vector )
{
coordVec = vector.vec;
coordVec.W = 1;
}
public Point(vec3d coord)
public Point( Vec3 coord )
{
Coord = coord;
coordVec.W = 1;
}
public Point(float x, float y, float z)
public Point( float x, float y, float z )
{
coordVec = new Vector4(x, y, z, 1);
coordVec = new Vector4( x, y, z, 1 );
}
public vec3d Coord
public Vec3 Coord
{
get => coord;
set { coord = value; coordVec.W = 1; }
set
{
coord = value;
coordVec.W = 1;
}
}
}
}
@@ -34,7 +34,5 @@ using System.Text;
namespace StgSharp.Geometries.SpaceGeometry
{
internal class Class1
{
}
internal class Class1 { }
}
@@ -36,6 +36,8 @@ namespace StgSharp.Graphics
{
public interface IImageProvider
{
Image ProvideImage();
}
}
@@ -30,23 +30,35 @@
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace StgSharp.Graphics
{
public static class ImageHelper
{
public static void Resize(Image i, int width, int height, ImageMovement move)
public static void Resize(
Image i,
int width,
int height,
ImageMovement move )
{
if (i == null)
{
throw new ArgumentNullException(nameof(i));
if( i == null ) {
throw new ArgumentNullException( nameof( i ) );
}
Array.Resize(ref i.Data, width * height * i.PixelSize);
if( i.Size == (width, height) ) {
return;
}
if( !Enum.IsDefined( typeof( ImageMovement ), move ) ) {
throw new InvalidEnumArgumentException( nameof( move ) );
}
byte[] oldData = i.Data;
i.Data = new byte[width * height * i.PixelSize];
i.Height = height;
i.Width = width;
switch (move)
{
i.PixelUpdateCount++;
switch( move ) {
case ImageMovement.Discard:
break;
case ImageMovement.Top:
@@ -54,8 +66,8 @@ namespace StgSharp.Graphics
default:
throw new NotImplementedException();
}
i.PixelUpdateCount++;
}
}
[Flags]
@@ -63,7 +75,7 @@ namespace StgSharp.Graphics
{
#pragma warning disable CA1008
Discard = 0,
#pragma warning restore CA1008
#pragma warning restore CA1008
Top = 1,
Bottom = 2,
Left = 4,
@@ -72,5 +84,6 @@ namespace StgSharp.Graphics
BottomLeft = Bottom | Left,
TopRight = Top | Right,
BottomRight = Bottom | Right,
}
}
@@ -52,31 +52,31 @@ namespace StgSharp.Graphics
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public GlHandle this[int index] => _bufferHandle[index];
public GlHandle this[ int index ] => _bufferHandle[ index ];
/// <summary>
/// Bind a buffer instance to OpenGL
/// </summary>
/// <param name="index">Index of handle of the object in this instance to be bind</param>
public abstract void Bind(int index);
/// <param name="index"> Index of handle of the object in this instance to be bind </param>
public abstract void Bind( int index );
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
Dispose( disposing: true );
GC.SuppressFinalize( this );
}
/// <inheritdoc/>
/// <inheritdoc />
public override string ToString()
{
return $"This is a {GetType().FullName}, containing {_bufferHandle.Length} buffer handles: {_bufferHandle.ToString()}.";
}
protected abstract void Dispose(bool disposing);
protected abstract void Dispose( bool disposing );
~BufferObjectBase()
{
Dispose(disposing: false);
Dispose( disposing: false );
}
}
@@ -45,7 +45,7 @@ namespace StgSharp.Graphics
#region GLFW3 struct
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWcontext
{
@@ -116,12 +116,12 @@ namespace StgSharp.Graphics
//GLFW_PLATFORM_CONTEXT_STATE
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct glfwVideomode
{
/*! The refresh rate, in Hz, of the video mode.
*/
private int refreshRate;
/*! The bit depth of the blue channel of the video mode.
*/
@@ -142,12 +142,12 @@ namespace StgSharp.Graphics
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct glfwGammaramp
{
/*! An array of value describing the response of the blue channel.
*/
private ushort* blue;
/*! An array of value describing the response of the green channel.
*/
@@ -162,12 +162,12 @@ namespace StgSharp.Graphics
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWimage
{
/*! The pixel _data of this image, arranged left-to-right, top-to-bottom.
*/
private byte* pixels;
/*! The height, in pixels, of this image.
@@ -177,26 +177,25 @@ namespace StgSharp.Graphics
*/
private int width;
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWgamepadstate
{
/*! The states of each [gamepad button](@ref gamepad_buttons), `GLFW_PRESS`
* or `GLFW_RELEASE`.
*/
public fixed byte buttons[15];
public fixed byte buttons[ 15 ];
/*! The states of each [gamepad axis](@ref gamepad_axes), in the range -1.0
* to 1.0 inclusive.
*/
public fixed float axes[6];
public fixed float axes[ 6 ];
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWallocator
{
@@ -213,7 +212,7 @@ namespace StgSharp.Graphics
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct glfwMonitor
{
@@ -221,7 +220,7 @@ namespace StgSharp.Graphics
private glfwWindow* window;
private fixed byte name[128];
private fixed byte name[ 128 ];
private glfwGammaramp currentRamp;
private glfwGammaramp originalRamp;
@@ -231,57 +230,55 @@ namespace StgSharp.Graphics
private int width, height;
private IntPtr userPointer;
public glfwMonitor()
{ }
public glfwMonitor() { }
public unsafe string Name
{
get
{
fixed (byte* cptr = name)
{
return Marshal.PtrToStringAnsi((IntPtr)cptr);
fixed( byte* cptr = name ) {
return Marshal.PtrToStringAnsi( ( IntPtr )cptr );
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
unsafe struct glfwWindow
[StructLayout( LayoutKind.Sequential )]
internal unsafe struct glfwWindow
{
glfwWindow* next;
void* userPointer;
bool rawMouseMotion;
Callbacks callbacks;
private glfwWindow* next;
private void* userPointer;
private bool rawMouseMotion;
private Callbacks callbacks;
// Virtual cursor position when cursor is disabled
double virtualCursorPosX, virtualCursorPosY;
int autoIconify;
int cursorMode;
int decorated;
int doublebuffer;
int floating;
int focusOnShow;
int lockKeyMods;
int maxwidth, maxheight;
private double virtualCursorPosX, virtualCursorPosY;
private int autoIconify;
private int cursorMode;
private int decorated;
private int doublebuffer;
private int floating;
private int focusOnShow;
private int lockKeyMods;
private int maxwidth, maxheight;
int minwidth, minheight;
int mousePassthrough;
int numer, denom;
private int minwidth, minheight;
private int mousePassthrough;
private int numer, denom;
// Window settings and state
int resizable;
int shouldClose;
private int resizable;
private int shouldClose;
int stickyKeys;
int stickyMouseButtons;
IntPtr cursor; // _GLFWcursor* cursor;
private int stickyKeys;
private int stickyMouseButtons;
private IntPtr cursor; // _GLFWcursor* cursor;
// glfwVideomode videoMode; // 根据GLFWvidmode的定义转换
IntPtr monitor; // _GLFWmonitor* monitor;
public fixed byte keys[GLconst.GLFW_KEY_LAST + 1];
public fixed byte mouseButtons[GLconst.GLFW_MOUSE_BUTTON_LAST + 1];
private IntPtr monitor; // _GLFWmonitor* monitor;
public fixed byte keys[ GLconst.GLFW_KEY_LAST + 1 ];
public fixed byte mouseButtons[ GLconst.GLFW_MOUSE_BUTTON_LAST + 1 ];
// _GLFWcontext viewPortDisplay; // 根据_GLFWcontext的定义转换
@@ -312,14 +309,10 @@ namespace StgSharp.Graphics
// GLFW_PLATFORM_WINDOW_STATE platformWindowState;
}
[StructLayout( LayoutKind.Sequential )]
public struct GLFWwindowCallback { }
[StructLayout(LayoutKind.Sequential)]
public struct GLFWwindowCallback
{
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public struct GLFWcursor
{
@@ -347,7 +340,7 @@ namespace StgSharp.Graphics
}
*/
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWinitconfig
{
@@ -361,7 +354,7 @@ namespace StgSharp.Graphics
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWwndconfig
{
@@ -392,31 +385,25 @@ namespace StgSharp.Graphics
internal X11 x11 = new X11();
public GLFWwndconfig()
{
}
public GLFWwndconfig() { }
internal struct Ns
{
private GLFWbool retina = false;
public fixed byte frameName[256];
public fixed byte frameName[ 256 ];
public Ns()
{
}
public Ns() { }
}
internal struct X11
{
public fixed byte className[256];
public fixed byte instanceName[256];
public fixed byte className[ 256 ];
public fixed byte instanceName[ 256 ];
public X11()
{
}
public X11() { }
}
@@ -430,17 +417,15 @@ namespace StgSharp.Graphics
internal struct Wl
{
public fixed byte appId[256];
public fixed byte appId[ 256 ];
public Wl()
{
}
public Wl() { }
}
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWctxconfig
{
@@ -461,9 +446,7 @@ namespace StgSharp.Graphics
internal Nsgl nsgl = new Nsgl();
public GLFWctxconfig()
{
}
public GLFWctxconfig() { }
internal struct Nsgl
{
@@ -474,7 +457,7 @@ namespace StgSharp.Graphics
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWfbconfig
{
@@ -500,11 +483,13 @@ namespace StgSharp.Graphics
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
internal unsafe struct GLFWlibrary
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = GLconst.GLFW_JOYSTICK_LAST + 1)]
[MarshalAs(
UnmanagedType.ByValArray,
SizeConst = GLconst.GLFW_JOYSTICK_LAST + 1 )]
private GLFWjoystick[] joysticks = new GLFWjoystick[GLconst.GLFW_JOYSTICK_LAST + 1];
private GLFWallocator allocator;
@@ -546,9 +531,7 @@ namespace StgSharp.Graphics
internal Osmesa osmesa = new Osmesa();
public GLFWlibrary()
{
}
public GLFWlibrary() { }
internal unsafe struct Hints
{
@@ -566,6 +549,7 @@ namespace StgSharp.Graphics
{
private ulong offset;
// This is defined in platform.h
//not transformed function defination
@@ -652,11 +636,9 @@ namespace StgSharp.Graphics
private GLFWbool KHR_xlib_surface;
private GLFWbool MVK_macos_surface;
private IntPtr GetInstanceProcAddr;
private fixed ulong extensions[2];
private fixed ulong extensions[ 2 ];
public vk()
{
}
public vk() { }
}
@@ -671,7 +653,7 @@ namespace StgSharp.Graphics
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWmapelement
{
@@ -684,25 +666,24 @@ namespace StgSharp.Graphics
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWmapping
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
[MarshalAs( UnmanagedType.ByValArray, SizeConst = 6 )]
private GLFWmapelement[] axes = new GLFWmapelement[6];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 15)]
[MarshalAs( UnmanagedType.ByValArray, SizeConst = 15 )]
private GLFWmapelement[] buttons = new GLFWmapelement[15];
private fixed byte guid[33];
private fixed byte guid[ 33 ];
private fixed byte name[128];
private fixed byte name[ 128 ];
public GLFWmapping()
{ }
public GLFWmapping() { }
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWjoystick
{
@@ -710,8 +691,8 @@ namespace StgSharp.Graphics
private byte* buttons;
private byte* hats;
private void* userPointer;
private fixed byte guid[33];
private fixed byte name[128];
private fixed byte guid[ 33 ];
private fixed byte name[ 128 ];
private GLFWbool allocated;
private GLFWbool connected;
@@ -726,20 +707,20 @@ namespace StgSharp.Graphics
// not completed in transforming
// GLFW_PLATFORM_JOYSTICK_STATE;
public GLFWjoystick()
{ }
public GLFWjoystick() { }
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWls
{
// This is defined in platform.h
//GLFW_PLATFORM_TLS_STATE
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWplatform
{
@@ -812,6 +793,7 @@ namespace StgSharp.Graphics
internal IntPtr setCursorMode;
#region input
/* void (* getCursorPos) (glfwWindow*, double*, double*);
void (* setCursorPos) (glfwWindow*, double, double);
void (* setCursorMode) (glfwWindow*, int);
@@ -878,6 +860,7 @@ namespace StgSharp.Graphics
void (* waitEventsTimeout) (double);
void (* postEmptyEvent) (void);
*/
#endregion
internal IntPtr setCursorPos;
@@ -910,25 +893,24 @@ namespace StgSharp.Graphics
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
public unsafe struct GLFWmutex
{
// This is defined in platform.h
//GLFW_PLATFORM_MUTEX_STATE
}
//public unsafe struct VkAllocationCallbacks { }
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
internal unsafe struct VkExtensionProperties
{
private fixed byte extensionName[256];
private fixed byte extensionName[ 256 ];
private uint specVersion;
public VkExtensionProperties()
{
}
public VkExtensionProperties() { }
}
@@ -947,14 +929,14 @@ namespace StgSharp.Graphics
}
*/
[StructLayout(LayoutKind.Explicit, Size = 16)]
[StructLayout( LayoutKind.Explicit, Size = 16 )]
public struct uintptr_t
{
[FieldOffset(0)]
[FieldOffset( 0 )]
private long part1;
[FieldOffset(8)]
[FieldOffset( 8 )]
private long part2;
}
@@ -963,7 +945,7 @@ namespace StgSharp.Graphics
#region glad struct
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
internal struct GLsync
{
@@ -39,27 +39,59 @@ namespace StgSharp.Graphics
/// <summary>
/// Function handler to load an opengl function by searching its name.
/// </summary>
/// <param name="name">the name of the Opengl function</param>
/// <returns>An Intptr value representing the pointer to the function</returns>
public delegate IntPtr glLoader(string name);
/// <param name="name"> the name of the Opengl function </param>
/// <returns> An Intptr value representing the pointer to the function </returns>
public delegate IntPtr glLoader( string name );
#region StgSharpDele
public unsafe delegate void FrameBufferSizeHandler(IntPtr window, uint width, uint height);
public unsafe delegate void FrameBufferSizeHandler(
IntPtr window,
int width,
int height );
public unsafe delegate void FramePositionHandler(IntPtr window, float width, float height);
public unsafe delegate void FramePositionHandler(
IntPtr window,
float width,
float height );
#endregion
#region glDEBUG
internal unsafe delegate void GLDEBUGPROC(int source, int type, uint id, int severity, int length, sbyte* message, void* userParam);
internal unsafe delegate void GLDEBUGPROCARB(int source, int type, uint id, int severity, int length, sbyte* message, void* userParam);
internal unsafe delegate void GLDEBUGPROCKHR(int source, int type, uint id, int severity, int length, sbyte* message, void* userParam);
internal unsafe delegate void GLDEBUGPROCAMD(uint id, int category, int severity, int length, sbyte* message, void* userParam);
#endregion
internal unsafe delegate void GLDEBUGPROC(
int source,
int type,
uint id,
int severity,
int length,
sbyte* message,
void* userParam );
internal unsafe delegate void GLDEBUGPROCARB(
int source,
int type,
uint id,
int severity,
int length,
sbyte* message,
void* userParam );
internal unsafe delegate void GLDEBUGPROCKHR(
int source,
int type,
uint id,
int severity,
int length,
sbyte* message,
void* userParam );
internal unsafe delegate void GLDEBUGPROCAMD(
uint id,
int category,
int severity,
int length,
sbyte* message,
void* userParam );
#endregion
}
+5 -15
View File
@@ -337,7 +337,6 @@ namespace StgSharp.Graphics.OpenGL
#region glad
public const int _1PASS_EXT = 0x80A1;
public const int _1PASS_SGIS = 0x80A1;
public const int _2PASS_0_EXT = 0x80A2;
@@ -4839,12 +4838,7 @@ namespace StgSharp.Graphics.OpenGL
public const int ZERO_TO_ONE = 0x935F;
public const int Z_EXT = 0x87D7;
#endregion
}
public static class glAttachment
@@ -4854,18 +4848,14 @@ namespace StgSharp.Graphics.OpenGL
public const uint DepthAndStencil = GLconst.DEPTH_STENCIL_ATTACHMENT;
public const uint Stencil = GLconst.STENCIL_ATTACHMENT;
private static int colorRange =
OpenGLFunction.CurrentGL.GetMaskInteger((uint)GLconst.MAX_COLOR_ATTACHMENTS);
public static uint Color(int i)
public static uint Color( int i )
{
#if DEBUG
if ((i > colorRange) || (i < 0))
{
#if DEBUG
if( ( i > OpenGLFunction.CurrentGL.AttachmentColorRange ) || ( i < 0 ) ) {
throw new ArgumentOutOfRangeException();
}
#endif
return (uint)(GLconst.COLOR_ATTACHMENT0 + i);
#endif
return ( uint )( GLconst.COLOR_ATTACHMENT0 + i );
}
}
+37 -8
View File
@@ -29,13 +29,13 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System.Runtime.CompilerServices;
namespace StgSharp.Graphics.OpenGL
{
public enum PixelChannelLayout
{
UByte = GLconst.UNSIGNED_BYTE,
Byte = GLconst.BYTE,
UShort = GLconst.UNSIGNED_SHORT,
@@ -55,10 +55,12 @@ namespace StgSharp.Graphics.OpenGL
UInt8888Rev = GLconst.UNSIGNED_INT_8_8_8_8_REV,
UInt1010102 = GLconst.UNSIGNED_INT_10_10_10_2,
UInt2101010Rev = GLconst.UNSIGNED_INT_2_10_10_10_REV
}
public enum FrameBufferStatus
{
Complete = GLconst.FRAMEBUFFER_COMPLETE, // GL_FRAMEBUFFER_COMPLETE
IncompleteAttachment = GLconst.FRAMEBUFFER_INCOMPLETE_ATTACHMENT, // GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT
IncompleteMissingAttachment = GLconst.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT, // GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT
@@ -67,10 +69,12 @@ namespace StgSharp.Graphics.OpenGL
Unsupported = GLconst.FRAMEBUFFER_UNSUPPORTED, // GL_FRAMEBUFFER_UNSUPPORTED
IncompleteMultisample = GLconst.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE, // GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE
IncompleteLayerTargets = GLconst.FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS // GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS
}
internal enum VkStructureType : uint
{
VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR = 1000004000,
VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR = 1000005000,
VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR = 1000006000,
@@ -78,10 +82,12 @@ namespace StgSharp.Graphics.OpenGL
VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK = 1000123000,
VK_STRUCTURE_TYPE_METAL_SURFACE_CREATE_INFO_EXT = 1000217000,
VK_STRUCTURE_TYPE_MAX_ENUM = 0x7FFFFFFF
}
public enum FrameBufferChannel
{
STENCIL_INDEX = GLconst.STENCIL_INDEX,
DEPTH_COMPONENT = GLconst.DEPTH_COMPONENT,
DEPTH_STENCIL = GLconst.DEPTH_STENCIL,
@@ -92,17 +98,22 @@ namespace StgSharp.Graphics.OpenGL
BGR = GLconst.BGR,
RGBA = GLconst.RGBA,
BGRA = GLconst.BGRA
}
public enum FrameBufferAttachment
{
Color = GLconst.COLOR_ATTACHMENT0,
Depth = GLconst.DEPTH_ATTACHMENT,
Stencil = GLconst.STENCIL_ATTACHMENT,
DepthAndStencil = GLconst.DEPTH_STENCIL_ATTACHMENT,
}
public enum Texture2DTarget
{
Texture2D = GLconst.TEXTURE_2D,
ProxyTexture2D = GLconst.PROXY_TEXTURE_2D,
Texture1DArray = GLconst.TEXTURE_1D_ARRAY,
@@ -116,21 +127,27 @@ namespace StgSharp.Graphics.OpenGL
TextureCubeMapPositiveZ = GLconst.TEXTURE_CUBE_MAP_POSITIVE_Z,
TextureCubeMapNegativeZ = GLconst.TEXTURE_CUBE_MAP_NEGATIVE_Z,
ProxyTextureCubeMap = GLconst.PROXY_TEXTURE_CUBE_MAP
}
public enum RenderBufferInternalFormat : uint
{
RGBA8 = GLconst.RGBA8,
Depth24_Stencil8 = GLconst.DEPTH24_STENCIL8,
}
public enum GLOperation : uint
{
StencilTest = GLconst.STENCIL_TEST,
}
internal enum VkResult
{
VK_SUCCESS = 0,
VK_NOT_READY = 1,
VK_TIMEOUT = 2,
@@ -155,22 +172,26 @@ namespace StgSharp.Graphics.OpenGL
VK_ERROR_NATIVE_WINDOW_IN_USE_KHR = -1000000001,
VK_ERROR_VALIDATION_FAILED_EXT = -1000011001,
VK_RESULT_MAX_ENUM = 0x7FFFFFFF
}
#pragma warning disable CA1008
#pragma warning disable CA1008
public enum ShaderType : int
#pragma warning restore CA1008
#pragma warning restore CA1008
{
Fragment = GLconst.FRAGMENT_SHADER,
Vertex = GLconst.VERTEX_SHADER,
Compute = GLconst.COMPUTE_SHADER,
Geometry = GLconst.GEOMETRY_SHADER,
}
#pragma warning disable CA1008 // 枚举应具有零值
#pragma warning disable CA1008 // 枚举应具有零值
public enum BufferType : int
#pragma warning restore CA1008 // 枚举应具有零值
#pragma warning restore CA1008 // 枚举应具有零值
{
ArrayBuffer = GLconst.ARRAY_BUFFER,
ElementArrayBuffer = GLconst.ELEMENT_ARRAY_BUFFER,
AtomicCounterBuffer = GLconst.ATOMIC_COUNTER_BUFFER,
@@ -185,12 +206,14 @@ namespace StgSharp.Graphics.OpenGL
TEXTURE_BUFFER = GLconst.TEXTURE_BUFFER,
TRANSFORM_FEEDBACK_BUFFER = GLconst.TRANSFORM_FEEDBACK_BUFFER,
UNIFORM_BUFFER = GLconst.UNIFORM_BUFFER,
}
#pragma warning disable CA1008 // 枚举应具有零值
#pragma warning disable CA1008 // 枚举应具有零值
public enum BufferUsage : int
#pragma warning restore CA1008 // 枚举应具有零值
#pragma warning restore CA1008 // 枚举应具有零值
{
StreamDraw = 0x88E0,
StreamRead = 0x88E1,
StreamCopy = 0x88E2,
@@ -200,18 +223,21 @@ namespace StgSharp.Graphics.OpenGL
DynamicDraw = 0x88E8,
DynamicRead = 0x88E9,
DynamicCopy = 0x88EA
}
}
public enum MaskBufferBit
{
COLOR = GLconst.COLOR_BUFFER_BIT,
DEPTH = GLconst.DEPTH_BUFFER_BIT,
STENCIL = GLconst.STENCIL_BUFFER_BIT,
}
public enum GeometryType : uint
{
POINTS = 0x0000,
LINES = 0x0001,
LINE_LOOP = 0x0002,
@@ -219,11 +245,14 @@ namespace StgSharp.Graphics.OpenGL
TRIANGLES = 0x0004,
TRIANGLE_STRIP = 0x0005,
TRIANGLE_FAN = 0x0006
}
public enum TextureFiltering
{
Nearest = 0x2600,
Linear = 0x2601
}
}
+75 -42
View File
@@ -36,81 +36,114 @@ using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics
{
public delegate IntPtr GLfuncLoader(string name);
public delegate IntPtr GLfuncLoader( string name );
internal delegate void GLVULKANPROCNV();
public unsafe struct GLhandleARB
{
dynamic value;
private dynamic value;
public unsafe GLhandleARB(dynamic value)
public unsafe GLhandleARB( dynamic value )
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
if (value.GetType().Name != "Uint32")
{
if( !RuntimeInformation.IsOSPlatform( OSPlatform.OSX ) ) {
if( value.GetType().Name != "Uint32" ) {
goto errorlog;
}
this.value = value;
}
else
{
if (value.GetType().Name != "IntPtr")
{
} else {
if( value.GetType().Name != "IntPtr" ) {
goto errorlog;
}
this.value = value;
}
errorlog:
errorlog:
{
InternalIO.InternalWriteLog(
$"{value.GetType().Name} does not match definination of GLhandlARB on OS {Environment.OSVersion.Platform} ",
LogType.Error);
LogType.Error );
}
}
public static implicit operator uint(GLhandleARB value)
public static implicit operator uint( GLhandleARB value )
{
return (uint)value;
return ( uint )value;
}
}
#region GLFW_dele
internal unsafe delegate void GLFWwindowsizefun(glfwWindow* window, int width, int height);
internal unsafe delegate void GLFWwindowrefreshfun(glfwWindow* window);
internal unsafe delegate void GLFWwindowposfun(glfwWindow* window, int xpos, int ypos);
internal unsafe delegate void GLFWwindowmaximizefun(glfwWindow* window, int maximized);
internal unsafe delegate void GLFWwindowiconifyfun(glfwWindow* window, int iconified);
internal unsafe delegate void GLFWwindowfocusfun(glfwWindow* window, int focused);
internal unsafe delegate void GLFWwindowcontentscalefun(glfwWindow* window, float xscale, float yscale);
internal unsafe delegate void GLFWwindowclosefun(glfwWindow* window);
internal unsafe delegate void GLFWwindowsizefun(
glfwWindow* window,
int width,
int height );
internal unsafe delegate void GLFWwindowrefreshfun( glfwWindow* window );
internal unsafe delegate void GLFWwindowposfun(
glfwWindow* window,
int xpos,
int ypos );
internal unsafe delegate void GLFWwindowmaximizefun(
glfwWindow* window,
int maximized );
internal unsafe delegate void GLFWwindowiconifyfun(
glfwWindow* window,
int iconified );
internal unsafe delegate void GLFWwindowfocusfun(
glfwWindow* window,
int focused );
internal unsafe delegate void GLFWwindowcontentscalefun(
glfwWindow* window,
float xscale,
float yscale );
internal unsafe delegate void GLFWwindowclosefun( glfwWindow* window );
internal unsafe delegate void GLFWvkproc();
internal unsafe delegate void GLFWscrollfun(glfwWindow* window, double xoffset, double yoffset);
internal unsafe delegate void GLFWmousebuttonfun(glfwWindow* window, int button, int action, int mods);
internal unsafe delegate void GLFWmonitorfun(glfwMonitor* monitor, int monitorevent);
internal unsafe delegate void GLFWkeyfun(glfwWindow* window, int key, int scancode, int action, int mods);
internal unsafe delegate void GLFWjoystickfun(int jid, int keyevent);
internal unsafe delegate void GLFWscrollfun(
glfwWindow* window,
double xoffset,
double yoffset );
internal unsafe delegate void GLFWmousebuttonfun(
glfwWindow* window,
int button,
int action,
int mods );
internal unsafe delegate void GLFWmonitorfun(
glfwMonitor* monitor,
int monitorevent );
internal unsafe delegate void GLFWkeyfun(
glfwWindow* window,
int key,
int scancode,
int action,
int mods );
internal unsafe delegate void GLFWjoystickfun( int jid, int keyevent );
public unsafe delegate void GLFWglproc();
internal unsafe delegate void GLFWerrorfun(int error_code, sbyte* description);
internal unsafe delegate void GLFWdropfun(glfwWindow* window, int path_count, sbyte*[] paths);
internal unsafe delegate void GLFWcursorposfun(glfwWindow* window, double xpos, double ypos);
internal unsafe delegate void GLFWcursorenterfun(glfwWindow* window, int entered);
internal unsafe delegate void GLFWcharmodsfun(glfwWindow* window, uint codepoint, int mods);
internal unsafe delegate void GLFWcharfun(glfwWindow* window, uint codepoint);
#endregion
internal unsafe delegate void GLFWerrorfun(
int error_code,
sbyte* description );
internal unsafe delegate void GLFWdropfun(
glfwWindow* window,
int path_count,
sbyte*[] paths );
internal unsafe delegate void GLFWcursorposfun(
glfwWindow* window,
double xpos,
double ypos );
internal unsafe delegate void GLFWcursorenterfun(
glfwWindow* window,
int entered );
internal unsafe delegate void GLFWcharmodsfun(
glfwWindow* window,
uint codepoint,
int mods );
internal unsafe delegate void GLFWcharfun(
glfwWindow* window,
uint codepoint );
#endregion
}
+4 -2
View File
@@ -37,8 +37,10 @@ namespace StgSharp.Graphics
public interface IGraphicAPIs
{
public IntPtr GraphicApiPackageHandle { get; }
public IntPtr GraphicApiPackageHandle
{
get;
}
}
}
+116 -81
View File
@@ -46,32 +46,43 @@ namespace StgSharp.Graphics
{
public class Image : ISSDSerializable, IImageProvider
{
private byte[] _data;
private ImageInfo info;
private ImageInfo _rawInfo;
private int _pixelUpdateCount = 0;
internal unsafe Image()
{
info = new ImageInfo();
_rawInfo = new ImageInfo();
}
internal Image(ImageInfo information)
internal Image( ImageInfo information )
{
info = information;
_rawInfo = information;
_data = Array.Empty<byte>();
//int length = info.width * info.height * info.channel;
}
internal ref byte[] Data
{
get => ref _data;
//int length = _rawInfo.width * _rawInfo.height * _rawInfo.channel;
}
public (int width, int height) Size
{
get => (info.Width, info.Height);
get => (_rawInfo.Width, _rawInfo.Height);
}
public byte[] PixelBuffer
{
get
{
if( ( _data.Length == 0 ) || ( _data == null ) ) {
GetBytes();
return _data!;
}
return _data;
}
}
public ImageChannel Channel => _rawInfo.Channel;
/// <summary>
/// Hash code of time pixels updated last time.
/// </summary>
@@ -81,59 +92,51 @@ namespace StgSharp.Graphics
internal set => _pixelUpdateCount = value;
}
public byte[] PixelBuffer
{
get
{
if ((_data.Length == 0) || (_data == null))
{
GetBytes();
return _data!;
}
return _data;
}
}
public int ChannelCount => _rawInfo.ChannelCount;
public ImageChannel Channel => info.Channel;
public int ChannelCount => info.ChannelCount;
public int Height
{
get => info.Height;
internal set => info.Height = value;
get => _rawInfo.Height;
internal set => _rawInfo.Height = value;
}
public int Width
{
get => info.Width;
internal set => info.Width = value;
get => _rawInfo.Width;
internal set => _rawInfo.Width = value;
}
public int PixelSize => GlHelper.GetPixelSize(info.pixelLayout, info.Channel);
public int PixelSize => GlHelper.GetPixelSize(
_rawInfo.pixelLayout, _rawInfo.Channel );
public PixelChannelLayout PixelLayout
{
get => info.pixelLayout;
private set => info.pixelLayout = value;
get => _rawInfo.pixelLayout;
private set => _rawInfo.pixelLayout = value;
}
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.PixelImage;
public void FromBytes(byte[] stream)
internal ref byte[] Data
{
get => ref _data;
}
public static unsafe Image FromFile(string route, ImageLoader loader)
public void FromBytes( byte[] stream ) { }
public static unsafe Image FromFile( string route, ImageLoader loader )
{
Image ret = new Image();
fixed (ImageInfo* iptr = &ret.info)
{
InternalIO.InternalLoadImage(route, iptr, loader);
fixed( ImageInfo* iptr = &ret._rawInfo ) {
InternalIO.InternalLoadImage( route, iptr, loader );
}
return ret;
}
public static Image FromMemory((int width, int height) size, ImageChannel channel, byte[] stream)
public static Image FromMemory(
(int width, int height) size,
ImageChannel channel,
byte[] stream )
{
ImageInfo _info = new ImageInfo
{
@@ -142,13 +145,17 @@ namespace StgSharp.Graphics
Channel = channel,
StreamPtr = IntPtr.Zero
};
Image ret = new Image(_info);
Image ret = new Image( _info );
ret.PixelLayout = PixelChannelLayout.Byte;
ret._data = stream;
return ret;
}
public static Image FromMemory((int width, int height) size, ImageChannel channel, PixelChannelLayout layout, byte[] stream)
public static Image FromMemory(
(int width, int height) size,
ImageChannel channel,
PixelChannelLayout layout,
byte[] stream )
{
ImageInfo _info = new ImageInfo
{
@@ -157,7 +164,7 @@ namespace StgSharp.Graphics
Channel = channel,
StreamPtr = IntPtr.Zero
};
Image ret = new Image(_info);
Image ret = new Image( _info );
ret.PixelLayout = layout;
ret._data = stream;
return ret;
@@ -165,20 +172,34 @@ namespace StgSharp.Graphics
public unsafe byte[] GetBytes()
{
if (_data.Length == 0)
{
int size = Width * Height * GlHelper.GetPixelSize(PixelLayout, Channel);
_data = new Span<byte>((byte*)info.StreamPtr, size).ToArray();
fixed (ImageInfo* pptr = &info)
{
InternalIO.InternalUnloadImage(pptr);
if( _data.Length == 0 ) {
int size = Width * Height * GlHelper.GetPixelSize(
PixelLayout, Channel );
_data = new Span<byte>( ( byte* )_rawInfo.StreamPtr,
size ).ToArray();
fixed( ImageInfo* pptr = &_rawInfo ) {
InternalIO.InternalUnloadImage( pptr );
}
info.StreamPtr = IntPtr.Zero;
_rawInfo.StreamPtr = IntPtr.Zero;
}
return _data;
}
public Image ProvideImage() => this;
internal static Image FromMemory(
ImageInfo info,
byte[] data,
int operationCount )
{
return new Image
{
_rawInfo = info,
_data = data,
_pixelUpdateCount = operationCount
};
}
byte[] ISSDSerializable.GetBytes()
{
throw new NotImplementedException();
@@ -186,7 +207,7 @@ namespace StgSharp.Graphics
}
[StructLayout(LayoutKind.Sequential)]
[StructLayout( LayoutKind.Sequential )]
internal struct ImageInfo
{
@@ -204,7 +225,7 @@ namespace StgSharp.Graphics
public int ChannelCount
{
get => GlHelper.GetChannelCount(channel);
get => GlHelper.GetChannelCount( channel );
}
public int Height
@@ -215,7 +236,8 @@ namespace StgSharp.Graphics
public int StreamSize
{
get => width * height * GlHelper.GetPixelSize(pixelLayout, channel);
get => width * height * GlHelper.GetPixelSize(
pixelLayout, channel );
}
public int Width
@@ -230,27 +252,30 @@ namespace StgSharp.Graphics
internal set => pixelPtr = value;
}
public override string ToString()
{
return $"{channel}\t{width}\t{height}\t{(ulong)StreamPtr}";
}
public override int GetHashCode()
{
int hash = 17;
hash = hash * 17 + width;
hash = hash * 17 + height;
hash = hash * 17 + (int)channel;
hash = hash * 17 + ( int )channel;
return hash;
}
public override string ToString()
{
return $"{channel}\t{width}\t{height}\t{(ulong)StreamPtr}";
}
}
public enum ImageChannel : uint
{
SingleColor = GLconst.RED,
DoubleColor = GLconst.RG,
TripleColor = GLconst.RGB,
WithAlphaChannel = GLconst.RGBA,
}
}
@@ -259,7 +284,7 @@ namespace StgSharp.Graphics.OpenGL
public static partial class GlHelper
{
internal static int GetChannelCount(ImageChannel channel)
internal static int GetChannelCount( ImageChannel channel )
{
return channel switch
{
@@ -267,34 +292,44 @@ namespace StgSharp.Graphics.OpenGL
ImageChannel.DoubleColor => 2,
ImageChannel.TripleColor => 3,
ImageChannel.WithAlphaChannel => 4,
_ => throw new InvalidCastException("Unknown color channel decoding setting.")
_ => throw new InvalidCastException(
"Unknown color channel decoding setting." )
};
}
internal static int GetPixelSize(PixelChannelLayout layout, ImageChannel cahnnel)
internal static int GetPixelSize(
PixelChannelLayout layout,
ImageChannel cahnnel )
{
return layout switch
{
PixelChannelLayout.UByte => sizeof(byte) * GetChannelCount(cahnnel),
PixelChannelLayout.Byte => sizeof(byte) * GetChannelCount(cahnnel),
PixelChannelLayout.UShort => sizeof(short) * GetChannelCount(cahnnel),
PixelChannelLayout.Short => sizeof(short) * GetChannelCount(cahnnel),
PixelChannelLayout.UInt => sizeof(int) * GetChannelCount(cahnnel),
PixelChannelLayout.Int => sizeof(int) * GetChannelCount(cahnnel),
PixelChannelLayout.Float => sizeof(float) * GetChannelCount(cahnnel),
PixelChannelLayout.UByte332 => sizeof(byte),
PixelChannelLayout.UByte233Rev => sizeof(byte),
PixelChannelLayout.UShort565 => sizeof(short),
PixelChannelLayout.UShort565Rev => sizeof(short),
PixelChannelLayout.UShort4444 => sizeof(short),
PixelChannelLayout.UShort4444Rev => sizeof(short),
PixelChannelLayout.UShort5551 => sizeof(short),
PixelChannelLayout.UShort1555Rev => sizeof(short),
PixelChannelLayout.UInt8888 => sizeof(int),
PixelChannelLayout.UInt8888Rev => sizeof(int),
PixelChannelLayout.UInt1010102 => sizeof(int),
PixelChannelLayout.UInt2101010Rev => sizeof(int),
_ => throw new ArgumentException("Unknown layout type"),
PixelChannelLayout.UByte => sizeof( byte ) * GetChannelCount(
cahnnel ),
PixelChannelLayout.Byte => sizeof( byte ) * GetChannelCount(
cahnnel ),
PixelChannelLayout.UShort => sizeof( short ) * GetChannelCount(
cahnnel ),
PixelChannelLayout.Short => sizeof( short ) * GetChannelCount(
cahnnel ),
PixelChannelLayout.UInt => sizeof( int ) * GetChannelCount(
cahnnel ),
PixelChannelLayout.Int => sizeof( int ) * GetChannelCount(
cahnnel ),
PixelChannelLayout.Float => sizeof( float ) * GetChannelCount(
cahnnel ),
PixelChannelLayout.UByte332 => sizeof( byte ),
PixelChannelLayout.UByte233Rev => sizeof( byte ),
PixelChannelLayout.UShort565 => sizeof( short ),
PixelChannelLayout.UShort565Rev => sizeof( short ),
PixelChannelLayout.UShort4444 => sizeof( short ),
PixelChannelLayout.UShort4444Rev => sizeof( short ),
PixelChannelLayout.UShort5551 => sizeof( short ),
PixelChannelLayout.UShort1555Rev => sizeof( short ),
PixelChannelLayout.UInt8888 => sizeof( int ),
PixelChannelLayout.UInt8888Rev => sizeof( int ),
PixelChannelLayout.UInt1010102 => sizeof( int ),
PixelChannelLayout.UInt2101010Rev => sizeof( int ),
_ => throw new ArgumentException( "Unknown layout type" ),
};
}
@@ -29,60 +29,60 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Collections;
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;
using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
/// <summary>
/// A collection of a sets of OpenGL textures. The collection can automatically select one of the
/// texture with minimum costs to upgrade pixels to buffer. Usually <see cref="AutoTextureGL"/> is used for
/// <see cref="IImageProvider"/> loading, but not for target of
/// <see cref="OpenGLFunction.FrameBufferTexture2d(FrameBufferTarget, uint, Texture2DTarget, GlHandle, int)"/>.
/// A collection of a sets of OpenGL textures. The collection can automatically select one of
/// the texture with minimum costs to upgrade pixels to buffer. Usually <see
/// cref="AutoTextureGL" /> is used for <see cref="IImageProvider" /> loading, but not for
/// target of <see cref="OpenGLFunction.FrameBufferTexture2d(FrameBufferTarget, uint,
/// Texture2DTarget, GlHandle, int)" />.
/// </summary>
public sealed class AutoTextureGL
{
private BidirectionalDictionary<Image, int> imageIndexMap = new BidirectionalDictionary<Image, int>();
private Dictionary<Image, int> imageUpdateIndex = new Dictionary<Image, int>();
private TextureProperty[] propertyCache;
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)
private AutoTextureGL( TextureGL texture )
{
texturePackage = texture;
_size = texture.Count;
imageIndexMap = new BidirectionalDictionary<Image, int>();
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range(0, _size));
Enumerable.Range( 0, _size ) );
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
public AutoTextureGL(int textureObjectSize, [NotNull]glRender binding)
public AutoTextureGL( int textureObjectSize, [NotNull]glRender binding )
{
this._size = textureObjectSize;
imageIndexMap = new BidirectionalDictionary<Image, int>();
texturePackage = new TextureGL(textureObjectSize, binding);
texturePackage = new TextureGL( textureObjectSize, binding );
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range(0, _size));
Enumerable.Range( 0, _size ) );
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
@@ -93,75 +93,70 @@ namespace StgSharp.Graphics.OpenGL
set => _textureProperty = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SelectTextureAndBind(Image i)
private OpenGLFunction GL
{
get => texturePackage.GL;
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SelectTextureAndBind( Image i )
{
TextureProperty property = _textureProperty;
SelectTextureAndBind(i, property);
SelectTextureAndBind( i, property );
}
public void SelectTextureAndBind([NotNull]Image i, TextureProperty property)
public void SelectTextureAndBind(
[NotNull]Image i,
TextureProperty property )
{
//usable texture with image match
if (imageIndexMap.TryGetValue(i, out int index))
{
if( imageIndexMap.TryGetValue( i, out int index ) ) {
//prop setting match
if (propertyCache[index] == property)
{
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);
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
{
_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))
{
} 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
{
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;
usedTextureIndex.AddLast( reusedIndex );
imageIndexMap[ i ] = reusedIndex;
propertyCache[ newIndex ] = property;
imageUpdateIndex[ i ] = i.PixelUpdateCount;
}
}
}
public static AutoTextureGL ToAuto([NotNull]TextureGL texture)
public static AutoTextureGL ToAuto( [NotNull]TextureGL texture )
{
if (texture.IndexOfCurrentTexture != -1)
{
throw new InvalidOperationException("Texture to be converted has been editted.");
if( texture.IndexOfCurrentTexture != -1 ) {
throw new InvalidOperationException(
"Texture to be converted has been editted." );
}
return new AutoTextureGL(texture);
return new AutoTextureGL( texture );
}
}
}
@@ -41,42 +41,50 @@ using System.Text;
namespace StgSharp.Graphics.OpenGL
{
/// <summary>
/// A collection of handle to Element Buffer Object in OpenglFunc.
/// Each <see langword="uint"/> value indexed from instance of this class this
/// is the only handle to one Element Buffer Object.
/// A collection of handle to Element Buffer Object in OpenglFunc. Each <see langword="uint" />
/// value indexed from instance of this class this is the only handle to one Element Buffer
/// Object.
/// </summary>
public sealed unsafe class ElementBuffer : GlBufferObjectBase
{
internal ElementBuffer(int n, glRender binding) : base(binding)
internal ElementBuffer( int n, glRender binding )
: base( binding )
{
_bufferHandle = GL.GenBuffers(n);
_bufferHandle = GL.GenBuffers( n );
}
public override sealed void Bind(int index)
public override sealed void Bind( int index )
{
GL.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
GL.BindBuffer(
BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
}
public void SetValue<T>(int index, T[] bufferArray, BufferUsage usage)
where T : struct, IConvertible
public void SetValue<T>( int index, T[] bufferArray, BufferUsage usage )
where T: struct, IConvertible
{
GL.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ElementArrayBuffer, bufferArray, usage);
GL.BindBuffer(
BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferData(
BufferType.ElementArrayBuffer, bufferArray, usage );
}
public void SetValue<T>(int index, ReadOnlySpan<T> bufferSpan, BufferUsage usage)
where T : struct, IConvertible
public void SetValue<T>(
int index,
ReadOnlySpan<T> bufferSpan,
BufferUsage usage )
where T: struct, IConvertible
{
GL.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ElementArrayBuffer, bufferSpan, usage);
GL.BindBuffer(
BufferType.ElementArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferData( BufferType.ElementArrayBuffer, bufferSpan,
usage );
}
protected override sealed void Dispose(bool disposing)
protected override sealed void Dispose( bool disposing )
{
if (disposing)
{
GL.DeleteBuffers(_bufferHandle);
if( disposing ) {
GL.DeleteBuffers( _bufferHandle );
}
}
@@ -40,55 +40,59 @@ using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
#pragma warning disable CA1008
#pragma warning disable CA1028
#pragma warning disable CA1008
#pragma warning disable CA1028
public enum FrameBufferTarget : uint
#pragma warning restore CA1028
#pragma warning restore CA1008
#pragma warning restore CA1028
#pragma warning restore CA1008
{
Read = GLconst.READ_FRAMEBUFFER,
All = GLconst.FRAMEBUFFER,
Draw = GLconst.DRAW_FRAMEBUFFER,
}
public sealed class FrameBuffer : GlBufferObjectBase
{
internal unsafe FrameBuffer(int count, glRender binding) : base(binding)
internal unsafe FrameBuffer( int count, glRender binding )
: base( binding )
{
_bufferHandle = GL.GenFrameBuffers(count);
_bufferHandle = GL.GenFrameBuffers( count );
}
/// <summary>
/// Bind the frame buffer object with name frame buffer to the frame buffer target specified by target.
/// <see langword="FrameBufferTarget.All"/> will be set as default target.
/// Bind the frame buffer object with name frame buffer to the frame buffer target specified
/// by target. <see langword="FrameBufferTarget.All" /> will be set as default target.
/// </summary>
/// <param name="index">Index of object to be binded in handle set</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override unsafe void Bind(int index)
/// <param name="index"> Index of object to be binded in handle set </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public override unsafe void Bind( int index )
{
GL.BindFrameBuffer(FrameBufferTarget.All, _bufferHandle[index]);
GL.BindFrameBuffer( FrameBufferTarget.All, _bufferHandle[ index ] );
}
/// <summary>
/// Bind the frame buffer object with name frame buffer to the frame buffer target specified by target.
/// Target of this frame buffer should be set manually.
/// Bind the frame buffer object with name frame buffer to the frame buffer target specified
/// by target. Target of this frame buffer should be set manually.
/// </summary>
/// <param name="target">The frame buffer target of the binding operation.</param>
/// <param name="index">Index of object to be binded in handle set</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Bind(FrameBufferTarget target, int index)
/// <param name="target"> The frame buffer target of the binding operation. </param>
/// <param name="index"> Index of object to be binded in handle set </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void Bind( FrameBufferTarget target, int index )
{
GL.BindFrameBuffer(target, _bufferHandle[index]);
GL.BindFrameBuffer( target, _bufferHandle[ index ] );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static void BindNull()
{
OpenGLFunction.CurrentGL.BindFrameBuffer(FrameBufferTarget.All, GlHandle.Zero);
OpenGLFunction.CurrentGL
.BindFrameBuffer( FrameBufferTarget.All, GlHandle.Zero );
}
protected override void Dispose(bool disposing)
protected override void Dispose( bool disposing )
{
throw new NotImplementedException();
}
@@ -41,7 +41,7 @@ namespace StgSharp.Graphics.OpenGL
private readonly glRender _contextBinding;
protected GlBufferObjectBase(glRender contextBinding)
protected GlBufferObjectBase( glRender contextBinding )
{
binding = contextBinding;
_contextBinding = contextBinding;
@@ -35,36 +35,38 @@ using System.Collections.Generic;
using System.Security.Principal;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public sealed class RenderBuffer : GlBufferObjectBase
{
public RenderBuffer(int count, glRender binding) : base(binding)
public RenderBuffer( int count, glRender binding )
: base( binding )
{
_bufferHandle = GL.GenRenderBuffer(count);
_bufferHandle = GL.GenRenderBuffer( count );
}
public override void Bind(int index)
public override void Bind( int index )
{
GL.BindRenderBuffer(this[index]);
GL.BindRenderBuffer( this[ index ] );
}
public void Store(RenderBufferInternalFormat format, (int width, int height) size)
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");
if( ( size.width > binding.Width ) || ( size.height > binding.Height ) ) {
StgSharp.LogWarning(
"FrameBuffer is larger than current canvas binding" );
}
}
protected override void Dispose(bool disposing)
protected override void Dispose( bool disposing )
{
throw new NotImplementedException();
foreach( GlHandle item in _bufferHandle ) {
Console.WriteLine( "removing a render buffer" );
GL.DeleteRenderBuffer( item );
}
}
}
@@ -28,7 +28,7 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data;
using StgSharp.Data.Intrinsic;
using StgSharp.Math;
using System;
@@ -58,8 +58,6 @@ namespace StgSharp.Graphics.OpenGL
_textureHandle = _gl.GenTextures( count );
}
internal OpenGLFunction GL => _gl;
public GlHandle this[ int index ]
{
get => _textureHandle[ index ];
@@ -77,12 +75,17 @@ namespace StgSharp.Graphics.OpenGL
get => currentEditingTextureIndex;
}
public void ActivateAs( TextureUnit unit ) { _gl.ActiveTextureUnit( ( uint )unit ); }
internal OpenGLFunction GL => _gl;
public void ActivateAs( TextureUnit unit )
{
_gl.ActiveTextureUnit( ( uint )unit );
}
public void Bind2D( int index )
{
currentEditingTextureIndex = index;
_gl.BindTexture( GLconst.TEXTURE_2D, _textureHandle[ index ] );
_gl.BindTexture( GLconst.TEXTURE_2D, _textureHandle[ index ] );
}
/// <summary>
@@ -94,8 +97,8 @@ namespace StgSharp.Graphics.OpenGL
{
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 );
Texture2DTarget.Texture2D, 0, i.Channel, ( uint )i.Width,
( uint )i.Height, i.Channel, i.PixelLayout, pixels: handle );
_gl.GenerateMipmap( Texture2DTarget.Texture2D );
}
@@ -108,14 +111,17 @@ namespace StgSharp.Graphics.OpenGL
TextureFilter onMagnify )
{
#if DEBUG
if( index != currentEditingTextureIndex )
{
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 );
_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 )]
@@ -125,21 +131,25 @@ namespace StgSharp.Graphics.OpenGL
TextureWrap onVertical )
{
#if DEBUG
if( index != currentEditingTextureIndex )
{
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 );
_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 );
Set2dFilterProperty(
index, property.FilterOnMinify, property.FilterOnMagnify );
Set2dWrapProperty(
index, property.WrapOnHorizontial, property.WrapOnVertical );
}
#endregion texture setting
@@ -192,23 +202,35 @@ namespace StgSharp.Graphics.OpenGL
set => vert = value;
}
public override bool Equals( [NotNullWhen( true )] object obj )
{
return base.Equals( obj );
}
public override int GetHashCode()
{
return HashCode.Combine(
FilterOnMagnify, FilterOnMagnify, WrapOnHorizontial, WrapOnVertical );
}
public override bool Equals([NotNullWhen(true)] object obj)
{
return base.Equals(obj);
FilterOnMagnify, FilterOnMagnify, WrapOnHorizontial,
WrapOnVertical );
}
public override string ToString()
{
return $"FilterOnMagnify:{FilterOnMagnify}, " +
$"FilterOnMagnify:{FilterOnMagnify}, " +
$"WrapOnHorizontial:{WrapOnHorizontial}, " +
$"WrapOnVertical:{WrapOnVertical}";
return $"FilterOnMagnify:{FilterOnMagnify}, " + $"FilterOnMagnify:{FilterOnMagnify}, " + $"WrapOnHorizontial:{WrapOnHorizontial}, " + $"WrapOnVertical:{WrapOnVertical}";
}
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;
}
public static implicit operator TextureProperty(
@@ -219,18 +241,10 @@ namespace StgSharp.Graphics.OpenGL
{
return new TextureProperty(
propertyValueTuple.onMagnify, propertyValueTuple.onMinify,
propertyValueTuple.onHorizontial, propertyValueTuple.onVertical );
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
@@ -29,7 +29,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
@@ -40,37 +39,41 @@ namespace StgSharp.Graphics.OpenGL
public sealed unsafe class VertexArray : GlBufferObjectBase
{
internal VertexArray(int n, glRender binding) : base(binding)
internal VertexArray( int n, glRender binding )
: base( binding )
{
_bufferHandle = GL.GenVertexArrays(n);
_bufferHandle = GL.GenVertexArrays( n );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override sealed void Bind(int index)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public override sealed void Bind( int index )
{
GL.BindVertexArray(_bufferHandle[index]);
GL.BindVertexArray( _bufferHandle[ index ] );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public static void BindNull()
{
OpenGLFunction.CurrentGL.BindVertexArray(GlHandle.Zero);
OpenGLFunction.CurrentGL.BindVertexArray( GlHandle.Zero );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetVertexAttribute(uint index, int vertexLength, TypeCode dataType, bool isNomalized, uint stride, int pointer)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetVertexAttribute(
uint index,
int vertexLength,
TypeCode dataType,
bool isNomalized,
uint stride,
int pointer )
{
GL.SetVertexAttribute(
index, vertexLength, dataType,
isNomalized,
stride, pointer);
index, vertexLength, dataType, isNomalized, stride, pointer );
}
protected override sealed void Dispose(bool disposing)
protected override sealed void Dispose( bool disposing )
{
if (disposing)
{
GL.DeleteVertexArrays(_bufferHandle);
if( disposing ) {
GL.DeleteVertexArrays( _bufferHandle );
}
}
@@ -43,108 +43,126 @@ namespace StgSharp.Graphics.OpenGL
public sealed unsafe class VertexBuffer : GlBufferObjectBase
{
internal VertexBuffer(int n, glRender binding) : base(binding)
internal VertexBuffer( int n, glRender binding )
: base( binding )
{
_bufferHandle = GL.GenBuffers(n);
_bufferHandle = GL.GenBuffers( n );
}
public override sealed void Bind(int index)
public override sealed void Bind( int index )
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
}
/// <summary>
///
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Unbind()
{
GL.BindBuffer(BufferType.ArrayBuffer, GlHandle.Zero);
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)
where T : struct, IMat
/// <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 )
where T: struct, IMat
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ArrayBuffer, bufferData, usage);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferData( BufferType.ArrayBuffer, bufferData, usage );
}
/// <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="bufferArray">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, T[] bufferArray, BufferUsage usage)
where T : struct,
/// <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>
public void WriteScalerData<T>(
int index,
T[] bufferArray,
BufferUsage usage )
where T: struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
#endif
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ArrayBuffer, bufferArray, usage);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferData( BufferType.ArrayBuffer, bufferArray, usage );
}
/// <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="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,
/// <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>
public void WriteScalerData<T>(
int index,
ReadOnlySpan<T> scalerSpan,
BufferUsage usage )
where T: struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
#endif
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ArrayBuffer, scalerSpan, usage);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferData( BufferType.ArrayBuffer, scalerSpan, usage );
}
/// <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="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
/// <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>
public void WriteVectorData<T>(
int index,
ReadOnlySpan<T> vectorSpan,
BufferUsage usage )
where T: struct, IVector
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferVectorData(BufferType.ArrayBuffer, vectorSpan, usage);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferVectorData( BufferType.ArrayBuffer, vectorSpan, usage );
}
/// <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="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
/// <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>
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);
GL.BindBuffer( BufferType.ArrayBuffer, _bufferHandle[ index ] );
GL.SetBufferVectorData( BufferType.ArrayBuffer, vectorArray,
usage );
}
protected override sealed void Dispose(bool disposing)
protected override sealed void Dispose( bool disposing )
{
if (disposing)
{
GL.DeleteBuffers(_bufferHandle);
if( disposing ) {
GL.DeleteBuffers( _bufferHandle );
}
}
@@ -42,22 +42,25 @@ namespace StgSharp.Graphics.ShaderEdit
{
/// <summary>
///
///
/// </summary>
public void DisplayGLtypeDefinition();
/// <summary>
///
///
/// </summary>
public void GainAllUniforms(ShaderProgram source, params string[] uniformName);
public void GainAllUniforms(
ShaderProgram source,
params string[] uniformName );
/// <summary>
///
///
/// </summary>
/// <returns></returns>
public ShaderStruct GetConvertedGLtype();
/// <summary>
///
///
/// </summary>
public void SetAllUniforms();
@@ -45,19 +45,21 @@ namespace StgSharp.Graphics.OpenGL
{
/// <summary>
/// Create an instance of <see cref="Shader"/> program
/// Create an instance of <see cref="Shader" /> program
/// </summary>
/// <returns>New instance of <see cref="Shader"/> instance. </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
/// <returns> New instance of <see cref="Shader" /> instance. </returns>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected override sealed ShaderProgram CreateShaderProgram()
{
return new ShaderProgram(this);
return new ShaderProgram( this );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override sealed Shader CreateShaderSegment(ShaderType type, int count)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
protected override sealed Shader CreateShaderSegment(
ShaderType type,
int count )
{
return new Shader(GL.CreateShaderSet(count, type), type, this);
return new Shader( GL.CreateShaderSet( count, type ), type, this );
}
}
@@ -69,7 +71,10 @@ namespace StgSharp.Graphics.OpenGL
internal readonly GlHandle[] handle;
public readonly ShaderType type;
internal unsafe Shader(GlHandle[] handle, ShaderType usage, glRender stream)
internal unsafe Shader(
GlHandle[] handle,
ShaderType usage,
glRender stream )
{
this.handle = handle;
GL = stream.GL;
@@ -81,60 +86,58 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// Attach one shader code to a shader program.
/// </summary>
/// <param name="target">Shader program to attach</param>
/// <param name="index">Index of shader code in current shader code set.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AttachTo(int index, ShaderProgram target)
/// <param name="target"> Shader program to attach </param>
/// <param name="index"> Index of shader code in current shader code set. </param>
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void AttachTo( int index, ShaderProgram target )
{
GL.AttachShader(target.handle, handle[index]);
GL.AttachShader( target.handle, handle[ index ] );
}
public void CheckStatus(int index, ShaderStatus status)
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}");
string log = GL.GetShaderStatus( this, index, ( int )status );
if( !string.IsNullOrEmpty( log ) ) {
throw new Exception( $"{$"Shader Error \t{status}\n"}{log}" );
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Compile(int index, byte[] codeStream)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void Compile( int index, byte[] codeStream )
{
if (codeStream == null)
{
throw new ArgumentNullException(nameof(codeStream));
if( codeStream == null ) {
throw new ArgumentNullException( nameof( codeStream ) );
}
GL.LoadShaderSource(handle[index], codeStream);
GL.CompileShader(handle[index]);
CheckStatus(index, ShaderStatus.CompileStatus);
GL.LoadShaderSource( handle[ index ], codeStream );
GL.CompileShader( handle[ index ] );
CheckStatus( index, ShaderStatus.CompileStatus );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Compile(int index, string codeStream)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void Compile( int index, string codeStream )
{
if (codeStream == null)
{
throw new ArgumentNullException(nameof(codeStream));
if( codeStream == null ) {
throw new ArgumentNullException( nameof( codeStream ) );
}
GL.LoadShaderSource(handle[index], Encoding.ASCII.GetBytes(codeStream));
GL.CompileShader(handle[index]);
CheckStatus(index, ShaderStatus.CompileStatus);
GL.LoadShaderSource(
handle[ index ], Encoding.ASCII.GetBytes( codeStream ) );
GL.CompileShader( handle[ index ] );
CheckStatus( index, ShaderStatus.CompileStatus );
}
public void FromBytes(byte[] stream)
public void FromBytes( byte[] stream )
{
throw new NotImplementedException();
}
public static byte[] FromCodeFile(string fileRoute)
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}");
string str = File.ReadAllText( fileRoute );
if( string.IsNullOrEmpty( str ) ) {
throw new InvalidOperationException(
$"Cannot load and GLSL code from {fileRoute}" );
}
return Encoding.UTF8.GetBytes(str);
return Encoding.UTF8.GetBytes( str );
}
public byte[] GetBytes()
@@ -142,7 +145,7 @@ namespace StgSharp.Graphics.OpenGL
return Array.Empty<byte>();
}
public byte[] GetBytes(out int length)
public byte[] GetBytes( out int length )
{
throw new NotImplementedException();
}
@@ -156,7 +159,9 @@ namespace StgSharp.Graphics.OpenGL
public enum ShaderStatus : int
{
CompileStatus = GLconst.COMPILE_STATUS,
}
public class ShaderProgram
@@ -168,64 +173,63 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// CustomizeInit a program with no shader attached.
/// </summary>
internal unsafe ShaderProgram(glRender binding)
internal unsafe ShaderProgram( glRender binding )
{
GL = binding.GL;
handle = GL.CreateProgram();
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// Get a uniform form current shader, the value type of the uniform should be provided.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <param name="name"> ContextName of the Uniform in shader code </param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Uniform<T> GetUniform<T>(string name) where T : struct
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe Uniform<T> GetUniform<T>( string name ) where T: struct
{
return new Uniform<T>(GL.GetUniformLocation(this.handle, name));
return new Uniform<T>( GL.GetUniformLocation( this.handle, name ) );
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// Get a uniform form current shader, the value type of the uniform should be provided.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <param name="name"> ContextName of the Uniform in shader code </param>
/// <returns></returns>
public unsafe Uniform<T, U> GetUniform<T, U>(string name)
where T : struct
where U : struct
public unsafe Uniform<T, U> GetUniform<T, U>( string name )
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>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// Get a uniform form current shader, the value type of the uniform should be provided.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <param name="name"> ContextName of the Uniform in shader code </param>
/// <returns></returns>
public unsafe Uniform<T, U, V> GetUniform<T, U, V>(string name)
where T : struct
where U : struct
where V : struct
public unsafe Uniform<T, U, V> GetUniform<T, U, V>( string name )
where T: struct
where U: struct
where V: struct
{
return new Uniform<T, U, V>(GL.GetUniformLocation(this.handle, name));
return new Uniform<T, U, V>(
GL.GetUniformLocation( this.handle, name ) );
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// Get a uniform form current shader, the value type of the uniform should be provided.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <param name="name"> ContextName of the Uniform in shader code </param>
/// <returns></returns>
public unsafe Uniform<T, U, V, W> GetUniform<T, U, V, W>(string name)
where T : struct
where U : struct
where V : struct
where W : struct
public unsafe Uniform<T, U, V, W> GetUniform<T, U, V, W>( string name )
where T: struct
where U: struct
where V: struct
where W: struct
{
return new Uniform<T, U, V, W>(GL.GetUniformLocation(this.handle, name));
return new Uniform<T, U, V, W>(
GL.GetUniformLocation( this.handle, name ) );
}
/// <summary>
@@ -233,20 +237,18 @@ namespace StgSharp.Graphics.OpenGL
/// </summary>
public unsafe void Link()
{
if (InternalIO.InternalLinkShaderProgram((OpenglContext*)this.GL.ContextHandle, handle.Value) == 0)
{
if( InternalIO.InternalLinkShaderProgram(
( OpenglContext* )this.GL.ContextHandle, handle.Value ) == 0 ) {
IntPtr logPtr = InternalIO.InternalReadSSCLog();
try
{
try {
byte[] logByte = new byte[512];
Marshal.Copy(logPtr, logByte, 0, 512);
string log = Encoding.UTF8.GetString(logByte);
log = log.Replace("\0", string.Empty);
InternalIO.InternalWriteLog(log, LogType.Error);
Marshal.Copy( logPtr, logByte, 0, 512 );
string log = Encoding.UTF8.GetString( logByte );
log = log.Replace( "\0", string.Empty );
InternalIO.InternalWriteLog( log, LogType.Error );
}
catch (Exception ex)
{
InternalIO.InternalWriteLog(ex.Message, LogType.Error);
catch( Exception ex ) {
InternalIO.InternalWriteLog( ex.Message, LogType.Error );
}
}
}
@@ -254,10 +256,10 @@ namespace StgSharp.Graphics.OpenGL
/// <summary>
/// Let the current viewPortDisplay use this shader.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public unsafe void Use()
{
GL.UseProgram(handle);
GL.UseProgram( handle );
}
~ShaderProgram()
@@ -52,93 +52,73 @@ namespace StgSharp.Graphics.OpenGL
}
public sealed class Uniform<T> : Uniform
where T : struct
public sealed class Uniform<T> : Uniform where T: struct
{
internal Uniform()
{
internal Uniform() { }
}
internal unsafe Uniform(GlHandle id)
internal unsafe Uniform( GlHandle id )
{
this.id = id;
}
internal static Uniform<T> FromHandle(GlHandle handle)
internal static Uniform<T> FromHandle( GlHandle handle )
{
return new Uniform<T> { id = handle };
}
}
public sealed class Uniform<T, U> : Uniform
where T : struct
where U : struct
public sealed class Uniform<T, U> : Uniform where T: struct where U: struct
{
internal Uniform() { }
internal Uniform()
{
}
internal unsafe Uniform(GlHandle id)
internal unsafe Uniform( GlHandle id )
{
this.id = id;
}
internal static Uniform<T, U> FromHandle(GlHandle handle)
internal static Uniform<T, U> FromHandle( GlHandle handle )
{
return new Uniform<T, U> { id = handle };
}
}
public sealed class Uniform<T, U, V> : Uniform
where T : struct
where U : struct
where V : struct
public sealed class Uniform<T, U, V> : Uniform where T: struct
where U: struct
where V: struct
{
internal Uniform()
{
internal Uniform() { }
}
internal unsafe Uniform(GlHandle id)
internal unsafe Uniform( GlHandle id )
{
this.id = id;
}
internal static Uniform<T, U, V> FromHandle(GlHandle handle)
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
where T : struct
where U : struct
where V : struct
where W : struct
public sealed class Uniform<T, U, V, W> : Uniform where T: struct
where U: struct
where V: struct
where W: struct
{
internal Uniform()
{
internal Uniform() { }
}
internal unsafe Uniform(GlHandle id)
internal unsafe Uniform( GlHandle id )
{
this.id = id;
}
internal static Uniform<T, U, V, W> FromHandle(GlHandle handle)
internal static Uniform<T, U, V, W> FromHandle( GlHandle handle )
{
return new Uniform<T, U, V, W> { id = handle };
}
@@ -148,59 +128,71 @@ namespace StgSharp.Graphics.OpenGL
public unsafe partial class OpenGLFunction
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue
(Uniform<Matrix44> uniform, Matrix44 mat)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetUniformValue( Uniform<Matrix44> uniform, Matrix44 mat )
{
Matrix44 temp = mat;
Context.glUniformMatrix4fv(uniform.id.SignedValue, 1, false, (float*)&temp);
Context.glUniformMatrix4fv(
uniform.id.SignedValue, 1, false, ( float* )&temp );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float, float, float, float> uniform, vec4d vec)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetUniformValue(
Uniform<float, float, float, float> uniform,
Vec4 vec )
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.SignedValue, 4, &temp);
Vec4 temp = vec;
Context.glUniform1fv( uniform.id.SignedValue, 4, &temp );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<vec4d> uniform, vec4d vec)
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void SetUniformValue( Uniform<Vec4> uniform, Vec4 vec )
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.SignedValue, 4, &temp);
Vec4 temp = vec;
Context.glUniform1fv( uniform.id.SignedValue, 4, &temp );
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float> uniform, float v0)
[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)
[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)
[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)
[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)
[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 );
}
}
}
@@ -34,14 +34,11 @@ using System.Text;
namespace StgSharp.Graphics.OpenGL
{
[AttributeUsage(AttributeTargets.Method)]
[AttributeUsage( AttributeTargets.Method )]
public sealed class OpenGLAPICallingAttribute : Attribute
{
public OpenGLAPICallingAttribute()
{
}
public OpenGLAPICallingAttribute() { }
}
}
File diff suppressed because it is too large Load Diff
@@ -36,6 +36,7 @@ namespace StgSharp.Graphics.OpenGL
{
public static partial class glManager
{
#region coreVersion
private static bool core10 = false;
@@ -682,8 +683,6 @@ namespace StgSharp.Graphics.OpenGL
private static bool WIN_phong_shading;
private static bool WIN_specular_fog;
#endregion
}
}
@@ -0,0 +1,92 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glFucntionSourceManager.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;
}
}
}
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More