daily update on 20240828 by nitload youmu, autotexture added

This commit is contained in:
Nitload
2024-08-28 10:58:31 +08:00
parent d082071f2d
commit 1ee4e4a42f
586 changed files with 60910 additions and 123106 deletions
@@ -30,7 +30,7 @@
//-----------------------------------------------------------------------
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharp.Math;
using System;
@@ -43,14 +43,19 @@ namespace StgSharp.Controls
{
public class BattleField : ControllingItem
{
public override vec4d[] TextureBox
{
get ;
}
public override IEnumerator<PlainGeometryMesh> GetEnumerator()
public bool IsEntity => true;
public ReadOnlySpan<vec4d> TextureBox
{
get => throw new NotImplementedException();
}
public Rectangle BoundingBox { get; set; }
public vec2d Position { get; set; }
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
throw new NotImplementedException();
}
}
}
@@ -1,4 +1,34 @@
using StgSharp.Geometries;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ButtonGroup.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.Geometries;
using StgSharp.Graphics;
using StgSharp.Math;
@@ -6,19 +36,42 @@ using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Transactions;
namespace StgSharp.Controls
{
public class KeyboardButtonGroup : ControllingItem
public abstract class KeyboardButtonGroup : ControllingItem
{
private List<TriggerButton> buttonList;
private List<TriggerButton> buttonList;
private TriggerButton current;
public KeyboardButtonGroup()
{
buttonList = new List<TriggerButton>();
buttonList = new List<TriggerButton>();
}
public bool IsEntity { get => false; }
public ReadOnlySpan<vec4d> TextureBox
{
get => throw new NotSupportedException();
}
public Rectangle BoundingBox { get; set; }
public TriggerButton CurrentButton
{
get => current;
}
public vec2d Position { get; set; }
protected List<TriggerButton> AllButton
{
get => buttonList;
}
public void AddButton(TriggerButton button)
@@ -26,46 +79,79 @@ namespace StgSharp.Controls
buttonList.Add(button);
}
public TriggerButton CurrentButton
public abstract void Confirm();
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
get => current;
}
public override vec4d[] TextureBox
{
get => throw new NotSupportedException();
}
public void MoveLeft()
{
}
public void MoveRight()
{
}
public void MoveUp()
{
}
public void MoveDown()
{
}
public void Confirm()
{
}
public override IEnumerator<PlainGeometryMesh> GetEnumerator()
{
foreach (var item in buttonList)
foreach (TriggerButton item in buttonList)
{
yield return item.Single();
}
}
public void MoveDown()
{
TriggerButton button = current;
while ((button.Down != null) && button.Down.IsDisabled)
{
button = button.Right;
}
if (current == button)
{
return;
}
current.DeHighlight();
button.Enable();
current = button;
}
public void MoveLeft()
{
TriggerButton button = current;
while ((button.Left != null) && button.Left.IsDisabled)
{
button = button.Left;
}
if (current == button)
{
return;
}
current.DeHighlight();
button.Enable();
current = button;
}
public void MoveRight()
{
TriggerButton button = current;
while ((button.Right != null) && button.Right.IsDisabled)
{
button = button.Right;
}
if (current == button)
{
return;
}
current.DeHighlight();
button.Enable();
current = button;
}
public void MoveUp()
{
TriggerButton button = current;
while ((button.Up != null) && button.Up.IsDisabled)
{
button = button.Right;
}
if (current == button)
{
return;
}
current.DeHighlight();
button.Enable();
current = button;
}
}
}
@@ -1,4 +1,34 @@
using StgSharp.Geometries;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="CharacterIndexImage.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.Geometries;
using StgSharp.Graphics;
using StgSharp.Math;
@@ -13,41 +43,14 @@ namespace StgSharp.Controls
{
public class CharacterLineIndexImage : ControllingItem
{
private int length;
private char[] displayIndex;
private char defaultChar;
Dictionary<char, PlainGeometryMesh> texIndex;
private int length;
PlainGeometryMesh _tittleMesh;
public override vec4d[] TextureBox
{
get => throw new NotSupportedException();
}
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);
displayIndex = result.ToCharArray();
}
public override IEnumerator<PlainGeometryMesh> GetEnumerator()
{
yield return _tittleMesh;
foreach (char item in displayIndex)
{
yield return texIndex[item];
}
}
public CharacterLineIndexImage(
int length, char defaultChar, PlainGeometryMesh tittleMesh,
IEnumerable<(char, PlainGeometryMesh)> indexEnumeration)
@@ -58,5 +61,40 @@ namespace StgSharp.Controls
texIndex = indexEnumeration.ToDictionary(item => item.Item1, item => item.Item2);
}
public bool IsEntity
{
get => true;
}
public ReadOnlySpan<vec4d> 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)
{
if (string.IsNullOrEmpty(message))
{
message = string.Empty;
}
string result = (message.Length >= length) ?
message.Substring(message.Length - displayIndex.Length) :
message.PadLeft(length, defaultChar);
displayIndex = result.ToCharArray();
}
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
yield return _tittleMesh;
foreach (char item in displayIndex)
{
yield return texIndex[item];
}
}
}
}
@@ -1,4 +1,34 @@
using StgSharp.Geometries;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ControllingIntem.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.Geometries;
using StgSharp.Graphics;
using StgSharp.Math;
@@ -9,19 +39,20 @@ using System.Text;
namespace StgSharp.Controls
{
public abstract partial class ControllingItem: IEnumerable<PlainGeometryMesh>
public interface ControllingItem : IEnumerable<PlainGeometryMesh>
{
public vec2d Position { get; set; }
public Rectangle BoundingBox { get; set; }
public abstract vec4d[] TextureBox { 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 IEnumerator<PlainGeometryMesh> GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
@@ -1,4 +1,34 @@
using StgSharp.Controls;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="DecorationBox.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.Controls;
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Math;
@@ -11,21 +41,28 @@ namespace StgSharp.Controls
{
public class DecorationBox : ControllingItem
{
private PlainGeometryMesh renderMesh;
public override vec4d[] TextureBox
public DecorationBox(Rectangle bound, Image texture, vec2d[] texCoord)
{
renderMesh = new PlainGeometryMesh(BoundingBox, new TextureProvider(texture, texCoord));
}
public bool IsEntity => true;
public ReadOnlySpan<vec4d> TextureBox
{
get => renderMesh.TextureCoord;
}
public Rectangle BoundingBox { get; set; }
public override IEnumerator<PlainGeometryMesh> GetEnumerator()
public vec2d Position { get; set; }
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
yield return renderMesh;
}
public DecorationBox(Rectangle bound, Image texture, vec4d[] texCoord)
{
renderMesh = new PlainGeometryMesh(BoundingBox, texture, texCoord);
}
}
}
@@ -1,7 +1,38 @@
using StgSharp.Controls;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="MarkingLable.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.Controls;
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Math;
using StgSharp.Timing;
using System;
using System.Collections.Generic;
@@ -12,28 +43,12 @@ namespace StgSharp.Controls
{
public class MarkingLabel : ControllingItem
{
public override vec4d[] TextureBox
{
get => marker.TextureCoord;
}
private vec2d _currentPosition, _movementVec;
private TimeFunction _movement;
private PlainGeometryMesh marker;
public void MoveTo(vec2d target)
{
Move(target - Position);
}
private TimeFunction _movement;
public void Move(vec2d movement)
{
if (!_movement.IsComplete)
{
Position = _currentPosition + _movement.Calculate() * _movementVec;
}
}
private vec2d _currentPosition, _movementVec;
public MarkingLabel(PlainGeometryMesh marker, TimeFunction movement)
{
@@ -41,10 +56,32 @@ namespace StgSharp.Controls
_movement = movement;
}
public override IEnumerator<PlainGeometryMesh> GetEnumerator()
public bool IsEntity => true;
public ReadOnlySpan<vec4d> TextureBox
{
get => marker.TextureCoord;
}
public Rectangle BoundingBox { get; set; }
public vec2d Position { get; set; }
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
yield return marker;
}
public void Move(vec2d movement)
{
if (!_movement.IsComplete)
{
Position = _currentPosition + (_movement.Calculate() * _movementVec);
}
}
public void MoveTo(vec2d target)
{
Move(target - Position);
}
}
}
@@ -35,81 +35,183 @@ using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Controls
{
public delegate void RenderButtonTextureCallback(ButtonStatus status, float beginTime, in TextureProvider texture);
public enum ButtonStatus
{
Error = 0b0,
Disable = 0b1,
Enable = 0b10,
Highlight = 0b100,
Confirm = 0b1000,
DisableToEnable = Disable | Enable,
EnableToDisable = -(Enable | DisableToEnable),
EnableToHighlight = Enable | Highlight,
HighlightToEnable = -(Enable | Highlight),
HighlightToDisable = -(Highlight | Disable),
}
public class TriggerButton : ControllingItem
{
private AnimationBuilder switchAnimationBuilder;
private Action? confirmCallback;
private Action? disableCallback;
#nullable enable
private Action? enableAction;
private Action? disableAction;
private Action? confirmAction;
private Action? enableCallback;
private float _statusBeginTime;
private RenderButtonTextureCallback _renderButton;
private TextureProvider _texture;
#nullable restore
public override vec4d[] TextureBox
public TriggerButton()
{
get { return switchAnimationBuilder.TextureFrame.VertexStream; }
}
public bool IsHighLighted { get; internal set; }
public bool IsDisabled { get; internal set; }
public event Action EnableEvent
{
add { enableAction += value; }
remove { enableAction -= value; }
}
public event Action DisableEvent
{
add { disableAction += value; }
remove { disableAction -= value; }
CurrentStatus = ButtonStatus.Disable;
}
public event Action ConfirmEvent
{
add { confirmAction += value; }
remove { confirmAction -= value; }
add { confirmCallback += value; }
remove { confirmCallback -= value; }
}
public void Enable(AnimationBuilder animation)
public event Action DisableEvent
{
if (!IsDisabled)
add { disableCallback += value; }
remove { disableCallback -= value; }
}
public event Action EnableEvent
{
add { enableCallback += value; }
remove { enableCallback -= value; }
}
public event RenderButtonTextureCallback RenderButtonTexture
{
add
{
if (_renderButton == null)
{
_renderButton = value;
}
else
{
_renderButton += value;
}
}
remove
{
if (_renderButton != null)
{
_renderButton -= value;
}
}
}
public bool IsHighLighted { get; internal set; }
public bool IsDisabled { get; internal set; }
public bool IsEntity => true;
public ReadOnlySpan<vec4d> TextureBox
{
get => MemoryMarshal.Cast<vec2d, vec4d>(_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; }
internal TextureProvider Texture
{
get => _texture;
set => _texture = value;
}
protected ButtonStatus CurrentStatus { get; set; }
public void DeHighlight()
{
if (CurrentStatus == ButtonStatus.Highlight)
{
CurrentStatus = ButtonStatus.HighlightToEnable;
}
}
public void Disable()
{
CurrentStatus = CurrentStatus switch
{
ButtonStatus.Enable => ButtonStatus.EnableToDisable,
ButtonStatus.Highlight => ButtonStatus.HighlightToDisable,
_ => CurrentStatus,
};
if (disableCallback != null)
{
disableCallback();
}
}
public void Enable()
{
if (CurrentStatus == ButtonStatus.Disable)
{
CurrentStatus = ButtonStatus.DisableToEnable;
}
else
{
return;
}
if (switchAnimationBuilder == null || switchAnimationBuilder.IsComplete)
if (enableCallback != null)
{
switchAnimationBuilder = animation;
enableCallback();
}
if( enableAction != null)enableAction();
}
public void Disable(AnimationBuilder animation)
public IEnumerator<PlainGeometryMesh> GetEnumerator()
{
if (switchAnimationBuilder == null || switchAnimationBuilder.IsComplete)
{
switchAnimationBuilder = animation;
}
if (disableAction != null) disableAction();
_renderButton(CurrentStatus, _statusBeginTime, in _texture);
yield return new PlainGeometryMesh(this.BoundingBox, _texture);
}
public void Highlight(AnimationBuilder animation)
public void Highlight()
{
if (switchAnimationBuilder == null || switchAnimationBuilder.IsComplete)
if (CurrentStatus == ButtonStatus.Enable)
{
switchAnimationBuilder = animation;
CurrentStatus |= ButtonStatus.EnableToHighlight;
}
else
{
return;
}
if (confirmCallback != null)
{
confirmCallback();
}
if (confirmAction != null) confirmAction();
}
public override IEnumerator<PlainGeometryMesh> GetEnumerator()
internal void Init(ButtonStatus status)
{
yield return new PlainGeometryMesh(this.BoundingBox, switchAnimationBuilder.GetAnimationFrame(),
this.TextureBox);
if (CurrentStatus == ButtonStatus.Error)
{
CurrentStatus = status;
}
}
}//----------------------------------- End of class --------------------------------------------
@@ -1,72 +0,0 @@
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Controls;
using StgSharp.Controlling.UsrActivity;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace StgSharp.Graphics
{
public class ViewPortDesigner
{
private KeyboardButtonGroup currentButtonGroup;
private List<ControllingItem> _controlList;
public ViewPortDesigner()
{
_controlList = new List<ControllingItem>();
}
public KeyboardButtonGroup CreateKeyboardButtonGroup(
ITrigger leftBidning,
ITrigger rightBinding,
ITrigger upBinding,
ITrigger downBinding,
ITrigger confirmBinding
)
{
var ret = new KeyboardButtonGroup();
_controlList.Add(ret);
currentButtonGroup = ret;
return ret;
}
public TriggerButton CreateKeyboardButton(
Rectangle bonding, AnimationBuilder defaultAnimation, bool isEnable
)
{
var ret = new TriggerButton();
ret.BoundingBox = bonding;
if (isEnable)
{
ret.IsDisabled = false;
ret.Enable(defaultAnimation);
}
else
{
ret.IsDisabled = true;
ret.Disable(defaultAnimation);
}
currentButtonGroup.AddButton(ret);
return ret;
}
public CharacterLineIndexImage CreateCharacterLine(
int length, char blankFilling, PlainGeometryMesh tittle, IEnumerable<(char,PlainGeometryMesh)> charList
)
{
var ret = new CharacterLineIndexImage(length, blankFilling,tittle,charList);
_controlList.Add(ret);
return ret;
}
}//---------------------------------- End of Class -----------------------------------------
}
+26 -23
View File
@@ -52,7 +52,7 @@ namespace StgSharp
[DllImport(SSC_libName, EntryPoint = "linkShaderProgram",
CallingConvention = CallingConvention.Cdecl)]
internal static extern unsafe uint InternalLinkShaderProgram(GLcontext* context, uint shaderProgram);
internal static extern unsafe uint InternalLinkShaderProgram(OpenglContext* context, uint shaderProgram);
[DllImport(SSC_libName, EntryPoint = "readLog",
CallingConvention = CallingConvention.Cdecl)]
@@ -76,8 +76,32 @@ namespace StgSharp.Graphics
public delegate IntPtr ImageLoader(string name, ref int width, ref int height, ref int definedChannel, int desiredChannel);
[StructLayout(LayoutKind.Sequential)]
public struct GLcontext
public struct OpenglContext
{
public override bool Equals(object obj)
{
return false;
}
public override unsafe int GetHashCode()
{
fixed (OpenglContext* sptr = &this)
{
return sptr->GetHashCode();
}
}
public static bool operator !=(OpenglContext left, OpenglContext right)
{
return !(left == right);
}
public static bool operator ==(OpenglContext left, OpenglContext right)
{
return left.Equals(right);
}
#region glapi
internal unsafe delegate*<uint, GLfixed, void> glAccumxOES;
@@ -2615,27 +2639,6 @@ namespace StgSharp.Graphics
#endregion glapi
public override bool Equals(object obj)
{
return false;
}
public unsafe override int GetHashCode()
{
fixed (GLcontext* sptr = &this)
{
return sptr->GetHashCode();
}
}
public static bool operator ==(GLcontext left, GLcontext right)
{
return left.Equals(right);
}
public static bool operator !=(GLcontext left, GLcontext right)
{
return !(left == right);
}
}
}
@@ -30,7 +30,7 @@
//-----------------------------------------------------------------------
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -53,9 +53,10 @@ namespace StgSharp
InfoError,
InfoWarning,
}
internal static unsafe partial class InternalIO
{
internal const string SS_errorLog =
"SS_errorlog.log";
@@ -65,13 +66,13 @@ namespace StgSharp
internal static Dictionary<TypeCode, uint> GLtype =
new Dictionary<TypeCode, uint>();
internal static SemaphoreSlim logSyncSemaphore = new SemaphoreSlim(1, 1);
internal static readonly GCHandle ssc_logHandle =
GCHandle.Alloc(new byte[512], GCHandleType.Pinned);
internal static IntPtr SSClibPtr = IntPtr.Zero;
internal static SemaphoreSlim logSyncSemaphore = new SemaphoreSlim(1, 1);
static InternalIO()
{
GLtype.Add(TypeCode.Single, GLconst.FLOAT);
@@ -103,10 +104,12 @@ namespace StgSharp
try
{
IntPtr procPtr =
#if Windows
#if WINDOWS
IntPtr.Zero;
#elif Linux
#elif LINUX
#else
IntPtr.Zero;
#endif
return procPtr;
}
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="KeyEventAttribute.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;
@@ -6,14 +36,15 @@ using System.Threading.Tasks;
namespace StgSharp
{
[AttributeUsage( AttributeTargets.Method)]
public class KeyEventAttribute:Attribute
[AttributeUsage(AttributeTargets.Method)]
public class KeyEventAttribute : Attribute
{
internal int _keyTarget;
internal int _equipment;
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;
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ITrigger.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;
@@ -6,7 +36,9 @@ namespace StgSharp.Controlling.UsrActivity
{
public interface ITrigger
{
public int TargetKeyOrButtonID { get; }
public KeyStatus TriggeredStatus { get; }
}
}
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="JoystickTrigger.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;
@@ -6,28 +36,18 @@ namespace StgSharp.Controlling.UsrActivity
{
public struct JoystickTrigger : ITrigger, IEquatable<JoystickTrigger>
{
public Joystick Stick;
private KeyStatus _triggeredStat;
public int TargetKeyOrButtonID => (int)Stick;
public KeyStatus TriggeredStatus => _triggeredStat;
public Joystick Stick;
public JoystickTrigger(Joystick targetKey)
{
this.Stick = targetKey;
}
public static bool operator ==(JoystickTrigger left, JoystickTrigger right)
{
return left._triggeredStat == right._triggeredStat && left.Stick == right.Stick;
}
public int TargetKeyOrButtonID => (int)Stick;
public static bool operator !=(JoystickTrigger left, JoystickTrigger right)
{
return !(left == right);
}
public KeyStatus TriggeredStatus => _triggeredStat;
public override bool Equals(object obj)
{
@@ -36,7 +56,7 @@ namespace StgSharp.Controlling.UsrActivity
public override int GetHashCode()
{
return (int)Stick + 17 * (int)_triggeredStat;
return ((int)Stick) + (17 * ((int)_triggeredStat));
}
public override string ToString()
@@ -44,9 +64,20 @@ namespace StgSharp.Controlling.UsrActivity
return $"Key {Stick} triggered when {_triggeredStat}";
}
public static bool operator !=(JoystickTrigger left, JoystickTrigger right)
{
return !(left == right);
}
public static bool operator ==(JoystickTrigger left, JoystickTrigger right)
{
return (left._triggeredStat == right._triggeredStat) && (left.Stick == right.Stick);
}
bool IEquatable<JoystickTrigger>.Equals(JoystickTrigger other)
{
return other == this;
}
}
}
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="KeyTrigger.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.Data.Common;
using System.Text;
@@ -6,29 +36,21 @@ using System.Text;
namespace StgSharp.Controlling.UsrActivity
{
public struct KeyTrigger: ITrigger,IEquatable<KeyTrigger>
public struct KeyTrigger : ITrigger, IEquatable<KeyTrigger>
{
public KeyboardKey TargetKey;
private KeyboardKey _targetKey;
private KeyStatus _triggerStat;
int ITrigger.TargetKeyOrButtonID => (int)TargetKey;
KeyStatus ITrigger.TriggeredStatus => _triggerStat;
public KeyTrigger(KeyboardKey targetKey)
public KeyTrigger(KeyboardKey targetKey, KeyStatus targetStat)
{
this.TargetKey = targetKey;
this._targetKey = targetKey;
this._triggerStat = targetStat;
}
public static bool operator ==(KeyTrigger left, KeyTrigger right)
{
return left._triggerStat == right._triggerStat && left.TargetKey == right.TargetKey;
}
public int TargetKeyOrButtonID => (int)_targetKey;
public static bool operator !=(KeyTrigger left, KeyTrigger right)
{
return !(left == right);
}
public KeyStatus TriggeredStatus => _triggerStat;
public override bool Equals(object obj)
{
@@ -37,17 +59,28 @@ namespace StgSharp.Controlling.UsrActivity
public override int GetHashCode()
{
return (int)TargetKey + 17 * (int)_triggerStat;
return ((int)_targetKey) + (17 * ((int)_triggerStat));
}
public override string ToString()
{
return $"Key {TargetKey} triggered when {_triggerStat}";
return $"Key {_targetKey} triggered when {_triggerStat}";
}
public static bool operator !=(KeyTrigger left, KeyTrigger right)
{
return !(left == right);
}
public static bool operator ==(KeyTrigger left, KeyTrigger right)
{
return (left._triggerStat == right._triggerStat) && (left._targetKey == right._targetKey);
}
bool IEquatable<KeyTrigger>.Equals(KeyTrigger other)
{
return other == this;
}
}
}
@@ -1,4 +1,34 @@
using StgSharp.Data;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="root.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;
using System;
using System.Collections.Generic;
@@ -10,10 +40,10 @@ namespace StgSharp
{
public static unsafe partial class StgSharp
{
private static SSD defaultIdProvider = new SSD();
private static List<Area> root = new List<Area>();
private static byte leastUnusedArea;
private static List<Area> root = new List<Area>();
private static SSD defaultIdProvider = new SSD();
public static byte NewArea()
{
+92 -3
View File
@@ -1,4 +1,34 @@
using StgSharp;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="InternalData.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.Generic;
@@ -8,7 +38,66 @@ namespace StgSharp
{
internal partial class InternalIO
{
internal const string CollisionTextureVertexShader ="#version 430 core\r\n\r\nlayout(location = 0) in vec2 localCollisionCoord;\r\nlayout(location = 1) in vec2 spaceCoord;\r\nlayout(location = 2) in float rotation;\r\nlayout(location = 3) in float scaling;\r\n\r\nuniform vec2 target;\r\nuniform mat2 projection;\r\n\r\nvoid main()\r\n{\r\n mat2 scaling = mat2(\r\n scaling,0,\r\n 0,scaling\r\n );\r\n mat2 rotation = mat2(\r\n cos(rotation),-sin(rotation),\r\n sin(rotation),cos(rotation) \r\n );\r\n vec2 realCoord = (rotation * scaling * localCollisionCoord) + spaceCoord - target;\r\n realCoord = projection * realCoord;\r\n\r\n float dist = distance(realCoord, vec2(0,0));\r\n float angle = atan(realCoord.y, realCoord.x);\r\n \r\n gl_Position = vec4(angle, realCoord.y, dist, 1);\r\n}";
internal const string CollisionTextureFragmentShader = "#version 430 core\r\n\r\nout vec4 Color;\r\n\r\nuniform float range;\r\n\r\nvoid main()\r\n{\r\n float dist = gl_FragCoord.z;\r\n\r\n if(dist > range)\r\n {\r\n discard;\r\n }\r\n dist /= range;\r\n gl_FragDepth = min(dist, gl_FragDepth);\r\n\r\n Color = vec4(dist,0,0,1);\r\n}";
#region ControllingItemRender
internal const string ControlItemRenderVertexShader = """
""";
#endregion
#region CollisionTexture
internal const string CollisionTextureVertexShader = """
#version 430 core
layout(location = 0) in vec2 localCollisionCoord;
layout(location = 1) in vec2 spaceCoord;
layout(location = 2) in float rotation;
layout(location = 3) in float scaling;
uniform vec2 target;
uniform mat2 projection;
void main()
{
mat2 scaling = mat2(
scaling,0,
0,scaling );
mat2 rotation = mat2(
cos(rotation),-sin(rotation),
sin(rotation),cos(rotation) );
vec2 realCoord = (rotation * scaling * localCollisionCoord) + spaceCoord - target;
realCoord = projection * realCoord;
float dist = distance(realCoord, vec2(0,0));
float angle = atan(realCoord.y, realCoord.x);
gl_Position = vec4(angle, realCoord.y, dist, 1);
}
""";
internal const string CollisionTextureFragmentShader = """
#version 430 core
out vec4 Color;
uniform float range;
void main()
{
float dist = gl_FragCoord.z;
if(dist > range)
{
discard;
}
dist /= range;
gl_FragDepth = min(dist, gl_FragDepth);
Color = vec4(dist,0,0,1);
}
""";
#endregion
}
}
+29 -2
View File
@@ -32,6 +32,7 @@ using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
@@ -43,8 +44,9 @@ using System.Text;
namespace StgSharp.Data
{
[StructLayout(LayoutKind.Explicit, Pack = 16)]
public unsafe struct M128:IMemoryType
public unsafe struct M128 : IMemoryType
{
[FieldOffset(0)] internal Vector4 vec;
internal M128(Vector4 v)
@@ -52,6 +54,20 @@ namespace StgSharp.Data
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
@@ -89,7 +105,7 @@ namespace StgSharp.Data
#if NET8_0_OR_GREATER
, INumber
#else
,IConvertible
, IConvertible
#endif
{
fixed (Vector4* p = &vec)
@@ -100,7 +116,17 @@ namespace StgSharp.Data
}
}
[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
@@ -165,5 +191,6 @@ namespace StgSharp.Data
}
#endif
}
}
+34 -2
View File
@@ -1,4 +1,34 @@
using StgSharp.Data;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// 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 StgSharp.Data;
using System;
using System.Collections.Generic;
@@ -12,8 +42,9 @@ namespace StgSharp.Math.HighPrecession
{
[StructLayout(LayoutKind.Sequential)]
public unsafe struct M256:IMemoryType
public unsafe struct M256 : IMemoryType
{
private M128 v0;
private M128 v1;
@@ -33,5 +64,6 @@ namespace StgSharp.Math.HighPrecession
*(((T*)mptr) + index) = value;
}
}
}
}
+60 -29
View File
@@ -1,4 +1,34 @@
using StgSharp.Data;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="RandomGenerator.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;
using System;
using System.IO;
@@ -14,15 +44,16 @@ namespace StgSharp.Data
public class RandomGenerator
{
private byte[] currentKey;
private readonly byte[] originKey;
private byte[] currentKey;
private int cycleCount;
private SHA512 hash;
public RandomGenerator():this(DateTime.UtcNow.ToBinary())
public RandomGenerator() : this(DateTime.UtcNow.ToBinary())
{
}
public RandomGenerator(object source)
@@ -77,28 +108,38 @@ namespace StgSharp.Data
return source.Read<int>(cycleCount % 4);
}
public byte GenRandomInt8()
{
cycleCount++;
if (cycleCount % 64 == 0)
{
PrivateRand();
}
return currentKey[cycleCount % 64];
}
public float GenRandomSingle()
{
cycleCount++;
while (true)
{
M128 source = PrivateRand();
uint
temp0 = source.Read<uint>(0),
temp1 = source.Read<uint>(2);
if (temp0 * temp1 != 0)
{
float ret = (temp0 % temp1) * 1.0f / temp1;
float ret = ((temp0 % temp1) * 1.0f) / temp1;
if (ret < 0.335f)
{
ret = ret * (ret * -0.7811934f + 1.4489113f);
ret = ret * ((ret * (-0.7811934f)) + 1.4489113f);
}
else
else
{
ret = ret * (ret * -0.1158368f + 1.0580600f) + 0.0590584f;
ret = (ret * ((ret * (-0.1158368f)) + 1.0580600f)) + 0.0590584f;
}
if (ret > 1)
{
@@ -111,14 +152,11 @@ namespace StgSharp.Data
}
public byte GenRandomInt8()
public void Reset()
{
cycleCount++;
if (cycleCount % 64 == 0)
{
PrivateRand();
}
return (byte)(currentKey[ cycleCount % 64 ]);
currentKey = originKey;
cycleCount = 0;
}
private unsafe M128 PrivateRand()
@@ -127,16 +165,16 @@ namespace StgSharp.Data
M128 ret;
fixed (byte* bptr = currentKey)
{
switch ((cycleCount % 16) / 4)
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();
}
@@ -145,12 +183,5 @@ namespace StgSharp.Data
return ret;
}
public void Reset()
{
currentKey = originKey;
cycleCount = 0;
}
}
}
+32 -2
View File
@@ -1,4 +1,34 @@
using StgSharp.Data.FileIO;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Area.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.FileIO;
using System;
using System.Collections.Generic;
@@ -15,6 +45,6 @@ namespace StgSharp.Data
/// </summary>
public partial class Area
{
}
}
+6 -6
View File
@@ -43,19 +43,19 @@ namespace StgSharp.Data
public struct SSDSegmentHead
{
[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(12)] internal byte size;
[FieldOffset(13)] public byte selfDefine_1;
[FieldOffset(14)] public byte selfDefine_2;
[FieldOffset(15)] public byte selfDefine_3;
public int Size
{
get => ((int)size) + 1;
+18 -18
View File
@@ -54,24 +54,6 @@ namespace StgSharp.Data
this.PreviousHash = previousHash;
}
public static SSDSegment FromStream(byte[] stream)
{
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));
}
}
return ret;
}
public byte this[int index]
{
get
@@ -113,6 +95,24 @@ namespace StgSharp.Data
}
}
public static SSDSegment FromStream(byte[] stream)
{
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)));
}
}
return ret;
}
public byte[] GetBytes()
{
byte[] ret = new byte[16 * StgSharp.ssdSegmentLength];
+2 -2
View File
@@ -39,11 +39,11 @@ namespace StgSharp.Data
{
public partial class SSD
{
private SSDrawHead head;
private Dictionary<string, SSDraw> fileList;
private FileStream file;
private SSDrawHead head;
public SSD()
{
@@ -39,9 +39,10 @@ namespace StgSharp.Data
{
public class SSDFolder : ISSDSerializable
{
internal Dictionary<string, SSDFolder> folders;
internal int _folderID;
internal string _name;
internal Dictionary<string, SSDFolder> folders;
internal SSDFolder()
{
@@ -68,6 +69,11 @@ namespace StgSharp.Data
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.VirtualFolder;
public void FromBytes(byte[] stream)
{
throw new NotImplementedException();
}
//TODO 虚拟文件夹的GetBytes好难写
public byte[] GetBytes()
@@ -75,10 +81,5 @@ namespace StgSharp.Data
throw new NotImplementedException();
}
public void FromBytes(byte[] stream)
{
throw new NotImplementedException();
}
}
}
+3 -1
View File
@@ -47,6 +47,7 @@ namespace StgSharp.Data.FileIO
{
public class SSDraw
{
private byte[] data;
public SSDraw(string name, Stream streamSource)
@@ -62,13 +63,14 @@ namespace StgSharp.Data.FileIO
public SSDrawHead Head { get; set; }
public string Name { get; set; }
}
[StructLayout(LayoutKind.Explicit, Size = 32 * 16)]
public unsafe struct SSDrawHead
{
}
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ISSDSerializable.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;
@@ -9,11 +39,13 @@ namespace StgSharp.Data
public interface ISSDSerializable
{
public SerializableTypeCode SSDTypeCode { get; }
public byte[] GetBytes();
internal void FromBytes(byte[] stream);
}
public enum SerializableTypeCode
@@ -31,14 +63,10 @@ namespace StgSharp.Data
public static partial class Serializer
{
public static byte[] Serialize(ISSDSerializable serializableObject)
{
return serializableObject.GetBytes();
}
public static T Deserialize<T>(byte[] stream)where T : ISSDSerializable
public static T Deserialize<T>(byte[] stream) where T : ISSDSerializable
{
T serializableObject = (T)Activator.CreateInstance<T>();
T serializableObject = Activator.CreateInstance<T>();
serializableObject.FromBytes(stream);
return serializableObject;
}
@@ -67,5 +95,10 @@ namespace StgSharp.Data
throw new ArgumentException("Unknown file type");
}
}
public static byte[] Serialize(ISSDSerializable serializableObject)
{
return serializableObject.GetBytes();
}
}
}
+36 -6
View File
@@ -1,13 +1,41 @@
//using StgSharp.Environment.Win32;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Program.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.Environment.Win32;
using StgSharp.Controlling.UsrActivity;
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharp.Math;
using StgSharp.MVVM;
using StgSharpDebug.Logic;
using System;
using System.Runtime.CompilerServices;
using System.Xml.XPath;
@@ -17,6 +45,7 @@ namespace StgSharp
internal static class Program
{
internal static unsafe void Main(string[] args)
{
try
@@ -42,10 +71,11 @@ namespace StgSharp
catch (Exception ex)
{
InternalIO.InternalWriteLog(
ex.Message + "\n" + ex.StackTrace,
$"{ex.Message}\n{ex.StackTrace}",
LogType.Error);
Environment.FailFast(ex.Message + "\n" + ex.StackTrace);
Environment.FailFast($"{ex.Message}\n{ex.StackTrace}");
}
}
}
}
@@ -32,8 +32,9 @@ using StgSharp.Controls;
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Graphics.OpenGL;
using StgSharp.Logic;
using StgSharp.Math;
using StgSharp.Timing;
using System;
using System.Collections.Generic;
@@ -46,215 +47,207 @@ namespace StgSharp
public class ParticleRenderStream : glRenderStream
{
ElementBuffer ebo;
ElementBuffer f_ebo;
FrameBuffer fbo;
Image i;
PlainInstancingBuffer<ParticleOnPlain> buffer;
RenderBuffer rbo;
ShaderProgram frameMainShader;
ShaderProgram s;
TextureGL t;
Uniform<int> texUniform;
Uniform<float> time;
VertexArray f_vao;
VertexArray vao;
private ElementBuffer ebo;
private ElementBuffer f_ebo;
private FrameBuffer fbo;
private Image i;
private PlainInstancingBuffer<ParticleOnPlain> buffer;
private RenderBuffer rbo;
private ShaderProgram frameMainShader;
private ShaderProgram s;
VertexBuffer f_vbo;
VertexBuffer vbo;
private AutoTextureGL autoT;
private TextureGL f_t;
private TextureGL t;
private Uniform<int> texUniform;
private Uniform<float> time;
private VertexArray f_vao;
private VertexArray vao;
public ParticleRenderStream()
{
private VertexBuffer f_vbo;
private VertexBuffer vbo;
}
public ParticleRenderStream() { }
public override bool IsContextSharable => true;
public Rectangle ButtonBounding
{
get;
private set;
}
public Rectangle ButtonBounding { get; private set; }
public TextureProvider ButtonTextureProvider { get; private set; }
int temp = 0;
//render a controlling item
public void AnotherMain(IEnumerable<PlainGeometryMesh> items)
public void OtherMain( IEnumerable<PlainGeometryMesh> items )
{
//Console.WriteLine("Render Button Itself");
GL.BindFrameBuffer(FrameBufferTarget.All, GlHandle.Zero); //GL.Assert(true);
GL.ClearColor(0.4f, TimePassed % 1.0f, 0f, 1.0f); //GL.Assert(true);
GL.Clear(MaskBufferBit.COLOR /**/| MaskBufferBit.DEPTH/**/); //GL.Assert(true);
GL.BindFrameBuffer( FrameBufferTarget.All, GlHandle.Zero ); //_gl.Assert(true);
GL.ClearColor( 0.4f, TimePassed % 1.0f, 0f, 1.0f ); //_gl.Assert(true);
GL.Clear( MaskBufferBit.COLOR /**/ | MaskBufferBit.DEPTH/**/ ); //_gl.Assert(true);
f_vao.Bind(0); //GL.Assert(true);
f_vao.Bind( 0 ); //_gl.Assert(true);
foreach (PlainGeometryMesh mesh in items)
foreach( PlainGeometryMesh mesh in items )
{
f_t.LoadTexture(0, mesh.TextureImage);
autoT.SelectTextureAndBind(mesh.TextureImage);
//f_t.LoadTexture( 0, mesh.TextureImage );
//_gl.Assert(true);
frameMainShader.Use(); //_gl.Assert(true);
GL.DrawElements(GeometryType.TRIANGLES, 6, TypeCode.UInt32, IntPtr.Zero);
}
//GL.Assert(true);
frameMainShader.Use(); //GL.Assert(true);
//_gl.Assert(true);
GL.DrawElements(GeometryType.TRIANGLES, 6, TypeCode.UInt32, IntPtr.Zero);
//GL.Assert(true);
//GL.DrawElements(GeometryType.LINES, 6, TypeCode.UInt32, IntPtr.Zero);
//_gl.DrawElements(GeometryType.LINES, 6, TypeCode.UInt32, IntPtr.Zero);
//BlueprintPipeline.SkipAll(output);
SwapBuffers();
}
public void RenderButton(ButtonStatus status, float statusBegin, in TextureProvider provider)
{
provider.UpdateFromImage(i);
}
public void RenderButton(
ButtonStatus status,
float statusBegin,
in TextureProvider provider )
{ provider.UpdateFromImage( i ); }
internal static vec3d DefaultRotation(TimeSpanProvider provider, out float rotation)
internal static vec3d DefaultRotation( TimeSpanProvider provider, out float rotation )
{
rotation = provider.SpanLengthLowPrecession;
float angle = provider.CurrentSecond * 2;
return (new vec3d(
Scaler.Cos(angle),
Scaler.Sin(angle),
0
)) * provider.SpanLengthLowPrecession;
return ( new vec3d( Scaler.Cos( angle ), Scaler.Sin( angle ), 0 ) ) *
provider.SpanLengthLowPrecession;
}
protected override void CustomizeDeinit()
{
}
protected override void CustomizeDeinit() { }
protected override void CustomizeInit()
{
//GL.ClearError();
//GL.Assert(true);
//_gl.ClearError();
//_gl.Assert(true);
buffer = new PlainInstancingBuffer<ParticleOnPlain>();
for (int i = 0; i < 10; i++)
for( int i = 0; i < 10; i++ )
{
float ai = Scaler.Abs(i - 5.0f);
for (int t = 0; t < 10; t++)
float ai = Scaler.Abs( i - 5.0f );
for( int t = 0; t < 10; t++ )
{
float at = Scaler.Abs(t - 5.0f);
float at = Scaler.Abs( t - 5.0f );
ParticleOnPlain p = new ParticleOnPlain(buffer);
((IInstancing)p).Coord = new vec3d(
(((-5) + i) * 0.2f) + 0.1f, (((-5) + t) * 0.2f) + 0.1f, 0);
((IInstancing)p).Scale =
Scaler.MinOf(i, t) * 0.15f;
((IInstancing)p).Motion = new GeometryMotion(
true, this._timeProvider,
DefaultRotation)
;
ParticleOnPlain p = new ParticleOnPlain( buffer );
( ( IInstancing )p ).Coord = new vec3d(
( ( ( -5 ) + i ) * 0.2f ) + 0.1f, ( ( ( -5 ) + t ) * 0.2f ) + 0.1f, 0 );
( ( IInstancing )p ).Scale =
Scaler.MinOf( i, t ) * 0.15f;
( ( IInstancing )p ).Motion = new GeometryMotion(
true, this._timeProvider, DefaultRotation );
}
}
//GL.Assert(true);
//_gl.Assert(true);
//SetSizeLimit(800, 800, 800, 800);
s = CreateShaderProgram();
frameMainShader = CreateShaderProgram();
Shader pvs = CreateShaderSegment(ShaderType.Vertex, 2);
Shader pfs = CreateShaderSegment(ShaderType.Fragment, 2);
Shader pvs = CreateShaderSegment( ShaderType.Vertex, 2 );
Shader pfs = CreateShaderSegment( ShaderType.Fragment, 2 );
//GL.Assert(true);
pvs.Compile(0, Shader.FromCodeFile("Shader\\particle.vert"));
//GL.Assert(true);
pvs.AttachTo(0, s);
//GL.Assert(true);
pfs.Compile(0, Shader.FromCodeFile("Shader\\particle.frag"));
pfs.AttachTo(0, s);
//_gl.Assert(true);
pvs.Compile( 0, Shader.FromCodeFile( "Shader\\particle.vert" ) );
//_gl.Assert(true);
pvs.AttachTo( 0, s );
//_gl.Assert(true);
pfs.Compile( 0, Shader.FromCodeFile( "Shader\\particle.frag" ) );
pfs.AttachTo( 0, s );
s.Link();
//GL.Assert(true);
pvs.Compile(1, Shader.FromCodeFile("Shader\\fbo.vert"));
pvs.AttachTo(1, frameMainShader);
pfs.Compile(1, Shader.FromCodeFile("Shader\\fbo.frag"));
pfs.AttachTo(1, frameMainShader);
//_gl.Assert(true);
pvs.Compile( 1, Shader.FromCodeFile( "Shader\\fbo.vert" ) );
pvs.AttachTo( 1, frameMainShader );
pfs.Compile( 1, Shader.FromCodeFile( "Shader\\fbo.frag" ) );
pfs.AttachTo( 1, frameMainShader );
frameMainShader.Link();
//GL.Assert(true);
vbo = CreateVertexBuffer(3);
vao = CreateVertexArray(1);
ebo = CreateElementBuffer(1);
vbo.Bind(0);
//_gl.Assert(true);
vbo = CreateVertexBuffer( 3 );
vao = CreateVertexArray( 1 );
ebo = CreateElementBuffer( 1 );
vbo.Bind( 0 );
Rectangle rec = new Rectangle
(
0.05f, 0.05f,
0.05f, -0.05f,
-0.05f, -0.05f,
-0.05f, 0.05f
);
Rectangle rec = new Rectangle(
0.05f, 0.05f, 0.05f, -0.05f, -0.05f, -0.05f, -0.05f, 0.05f );
//GL.Assert(true);
vao.Bind(0);
vbo.WriteVectorData(0, rec.VertexStream, BufferUsage.StaticDraw);
ebo.SetValue(0, rec.VertexIndices, BufferUsage.StaticDraw);
vao.SetVertexAttribute(0, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
//_gl.Assert(true);
vao.Bind( 0 );
vbo.WriteVectorData( 0, rec.VertexStream, BufferUsage.StaticDraw );
ebo.SetValue( 0, rec.VertexIndices, BufferUsage.StaticDraw );
vao.SetVertexAttribute( 0, 3, TypeCode.Single, false, 4 * sizeof( float ), 0 );
vbo.WriteVectorData<vec4d>(1, buffer.CoordAndRotationSpan, BufferUsage.StreamDraw);
vao.SetVertexAttribute(1, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
vao.SetVertexAttribute(2, 1, TypeCode.Single, false, 4 * sizeof(float), 3 * sizeof(float));
vbo.WriteVectorData<vec4d>( 1, buffer.CoordAndRotationSpan, BufferUsage.StreamDraw );
vao.SetVertexAttribute( 1, 3, TypeCode.Single, false, 4 * sizeof( float ), 0 );
vao.SetVertexAttribute(
2, 1, TypeCode.Single, false, 4 * sizeof( float ), 3 * sizeof( float ) );
GL.VertexAttributeDivisor(1, 1);
GL.VertexAttributeDivisor(2, 1);
GL.VertexAttributeDivisor( 1, 1 );
GL.VertexAttributeDivisor( 2, 1 );
vbo.WriteScalerData<float>(2, buffer.ScalingSpan, BufferUsage.StaticDraw);
vao.SetVertexAttribute(3, 1, TypeCode.Single, false, sizeof(float), 0);
vbo.WriteScalerData<float>( 2, buffer.ScalingSpan, BufferUsage.StaticDraw );
vao.SetVertexAttribute( 3, 1, TypeCode.Single, false, sizeof( float ), 0 );
GL.VertexAttributeDivisor(3, 1);
GL.VertexAttributeDivisor( 3, 1 );
vbo.Unbind();
GL.BindVertexArray(GlHandle.Zero);
GL.BindVertexArray( GlHandle.Zero );
NativeCameraViewTarget
(
(0, 0, -100),
(0, 0, 0),
(0, 1, 0)
);
NativeCameraViewRange(new Degree(1.5f), Vec2d.Zero, (50, 50));
NativeCameraUniform(s, "Camera");
NativeCameraViewTarget( (0, 0, -100), (0, 0, 0), (0, 1, 0) );
NativeCameraViewRange( new Degree( 1.5f ), Vec2d.Zero, (50, 50) );
NativeCameraUniform( s, "Camera" );
s.Use();
fbo = CreateFrameBuffer(1);
rbo = CreateRenderBuffer(1);
fbo = CreateFrameBuffer( 1 );
rbo = CreateRenderBuffer( 1 );
fbo.Bind(0);
rbo.Bind(0);
GL.SetRenderBufferStorage(
RenderBufferInternalFormat.Depth24_Stencil8, this.Size);
fbo.Bind( 0 );
rbo.Bind( 0 );
GL.SetRenderBufferStorage( RenderBufferInternalFormat.Depth24_Stencil8, this.Size );
//GL.Assert(true);
t = CreateTexture(1);
t.Bind2D(0);
GL.TextureImage2d<byte>(Texture2DTarget.Texture2D, 0, (int)ImageChannel.WithAlphaChannel,
(uint)Width, (uint)Height, (int)ImageChannel.WithAlphaChannel, PixelChannelLayout.Byte, null);
t.Set2dWrapProperty(Wrap.Repeat, Wrap.Repeat);
t.Set2dFilterProperty(Filter.Nearest, Filter.Nearest);
//_gl.Assert(true);
t = CreateTexture( 1 );
t.Bind2D( 0 );
GL.TextureImage2d<byte>(
Texture2DTarget.Texture2D, 0, ( int )ImageChannel.WithAlphaChannel, ( uint )Width,
( uint )Height, ( int )ImageChannel.WithAlphaChannel, PixelChannelLayout.Byte,
null );
t.Set2dWrapProperty( 0, TextureWrap.Repeat, TextureWrap.Repeat );
t.Set2dFilterProperty( 0, TextureFilter.Nearest, TextureFilter.Nearest );
//GL.Assert(true);
GL.FrameBufferTexture2d(FrameBufferTarget.All, glAttachment.Color(0),
Texture2DTarget.Texture2D, t[0], 0);
//_gl.Assert(true);
GL.FrameBufferTexture2d(
FrameBufferTarget.All, glAttachment.Color( 0 ), Texture2DTarget.Texture2D, t[ 0 ],
0 );
//GL.Assert(true);
GL.CombineFrameBufferRenderBuffer(FrameBufferAttachment.Stencil|FrameBufferAttachment.Depth, rbo[0]);
//_gl.Assert(true);
GL.CombineFrameBufferRenderBuffer(
FrameBufferAttachment.Stencil | FrameBufferAttachment.Depth, rbo[ 0 ] );
Console.WriteLine(GL.CheckFrameBufferStatus(FrameBufferTarget.All));
Console.WriteLine( GL.CheckFrameBufferStatus( FrameBufferTarget.All ) );
FrameBuffer.BindNull();
//GL.Assert(true);
//_gl.Assert(true);
int streamLength = this.Width * this.Height * 4;
byte[] imageStream = new byte[streamLength];
i = Image.FromMemory(this.Size, ImageChannel.WithAlphaChannel, imageStream);
i = Image.FromMemory( this.Size, ImageChannel.WithAlphaChannel, imageStream );
time = s.GetUniform<float>("time");
time = s.GetUniform<float>( "time" );
vec2d[] buttonTextureCoordArray = {
(0f, 1f),
@@ -262,117 +255,124 @@ namespace StgSharp
(1f, 0f),
(0f, 0f)
};
ButtonBounding = new Rectangle(
-0.9f, 0.9f,
0.9f, 0.9f,
0.9f, -0.9f,
-0.9f, -0.9f
ButtonBounding = new Rectangle( -0.9f, 0.9f, 0.9f, 0.9f, 0.9f, -0.9f, -0.9f, -0.9f );
//_gl.Assert(true);
ButtonTextureProvider = new TextureProvider( i, buttonTextureCoordArray );
f_vao = CreateVertexArray( 1 );
f_vbo = CreateVertexBuffer( 2 );
f_ebo = CreateElementBuffer( 1 );
//_gl.Assert(true);
f_vao.Bind( 0 );
f_ebo.Bind( 0 );
f_ebo.SetValue( 0, ButtonBounding.VertexIndices, BufferUsage.StaticDraw );
//_gl.Assert(true);
f_vbo.Bind( 0 );
f_vbo.WriteVectorData( 0, ButtonBounding.VertexStream, BufferUsage.StaticDraw );
f_vao.SetVertexAttribute( 0, 3, TypeCode.Single, false, 4 * sizeof( float ), 0 );
//_gl.Assert(true);
f_vbo.Bind( 1 );
f_vbo.WriteVectorData( 1, buttonTextureCoordArray, BufferUsage.StaticDraw );
f_vao.SetVertexAttribute( 1, 3, TypeCode.Single, false, 4 * sizeof( float ), 0 );
//_gl.Assert(true);
autoT = CreateAutoTexture(4);
autoT.DefaultTextureProperty = new TextureProperty(
TextureFilter.Nearest, TextureFilter.Nearest,
TextureWrap.Repeat, TextureWrap.Repeat
);
//GL.Assert(true);
ButtonTextureProvider = new TextureProvider(i, buttonTextureCoordArray);
f_t = CreateTexture( 1 );
f_t.Bind2D( 0 );
f_t.Set2dWrapProperty( 0, TextureWrap.Repeat, TextureWrap.Repeat );
f_t.Set2dFilterProperty( 0, TextureFilter.Nearest, TextureFilter.Nearest );
f_vao = CreateVertexArray(1);
f_vbo = CreateVertexBuffer(2);
f_ebo = CreateElementBuffer(1);
//_gl.Assert(true);
f_t.ActivateAs( TextureUnit.Unit1 );
//GL.Assert(true);
f_vao.Bind(0);
f_ebo.Bind(0);
f_ebo.SetValue(0, ButtonBounding.VertexIndices, BufferUsage.StaticDraw);
//GL.Assert(true);
f_vbo.Bind(0);
f_vbo.WriteVectorData(0, ButtonBounding.VertexStream, BufferUsage.StaticDraw);
f_vao.SetVertexAttribute(0, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
//GL.Assert(true);
f_vbo.Bind(1);
f_vbo.WriteVectorData(1, buttonTextureCoordArray, BufferUsage.StaticDraw);
f_vao.SetVertexAttribute(1, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
//GL.Assert(true);
f_t = CreateTexture(1);
f_t.Bind2D(0);
f_t.Set2dWrapProperty(Wrap.Repeat, Wrap.Repeat);
f_t.Set2dFilterProperty(Filter.Nearest, Filter.Nearest);
//GL.Assert(true);
f_t.ActivateAs(TextureUnit.Unit1);
//GL.Assert(true);
//_gl.Assert(true);
frameMainShader.Use();
texUniform = frameMainShader.GetUniform<int>("tex");
//GL.Assert(true);
GL.SetUniformValue(texUniform, 1);
//GL.Assert(true);
texUniform = frameMainShader.GetUniform<int>( "tex" );
//_gl.Assert(true);
GL.SetUniformValue( texUniform, 1 );
//_gl.Assert(true);
}
TextureGL f_t;
protected override void Main()
{
//GL.ClearError();
temp++;
//_gl.ClearError();
//Console.Clear();
buffer.UpdateAllParticles();
//Console.WriteLine(GL.CheckFrameBufferStatus(FrameBufferTarget.All));
//Console.WriteLine(_gl.CheckFrameBufferStatus(FrameBufferTarget.All));
fbo.Bind(0); //GL.Assert(true);
vao.Bind(0); //GL.Assert(true);
t.Bind2D(0); //GL.Assert(true);
fbo.Bind( 0 ); //_gl.Assert(true);
vao.Bind( 0 ); //_gl.Assert(true);
t.Bind2D( 0 ); //_gl.Assert(true);
/**/
GL.TextureImage2d(Texture2DTarget.Texture2D, 0, (int)ImageChannel.WithAlphaChannel,
(uint)Width, (uint)Height, (int)ImageChannel.WithAlphaChannel, PixelChannelLayout.Byte, new byte[1]);
GL.TextureImage2d(
Texture2DTarget.Texture2D, 0, ( int )ImageChannel.WithAlphaChannel, ( uint )Width,
( uint )Height, ( int )ImageChannel.WithAlphaChannel, PixelChannelLayout.Byte,
new byte[1] );
/**/
//GL.Assert(true);
//_gl.Assert(true);
GL.ClearColor((0.6f + TimePassed) % 1.0f, 0.1f, 0.3f, 1);
GL.Clear(MaskBufferBit.COLOR | MaskBufferBit.DEPTH);
GL.ClearColor( ( 0.6f + TimePassed ) % 1.0f, 0.1f, 0.3f, 1 );
GL.Clear( MaskBufferBit.COLOR | MaskBufferBit.DEPTH );
//GL.Assert(true);
//_gl.Assert(true);
vbo.Bind(1);
vbo.WriteVectorData<vec4d>(1, buffer.CoordAndRotationSpan, BufferUsage.StreamDraw);
vbo.Bind( 1 );
vbo.WriteVectorData<vec4d>( 1, buffer.CoordAndRotationSpan, BufferUsage.StreamDraw );
s.Use();
NativeCamera.SetAllUniforms();
GL.SetUniformValue(time, TimePassed);
GL.SetUniformValue( time, TimePassed );
GL.DrawElementsInstanced( GeometryType.TRIANGLES, 6, TypeCode.UInt32, IntPtr.Zero,
100 );
GL.DrawElementsInstanced(
GeometryType.TRIANGLES, 6, TypeCode.UInt32, IntPtr.Zero, 100
);
//Console.WriteLine(TimePassed);
//GL.Assert(true);
//_gl.Assert(true);
GL.WaitAccomplishment();
GL.BindVertexArray(GlHandle.Zero);
GL.BindVertexArray( GlHandle.Zero );
/**/
//GL.Assert(true);
ImageHelper.Resize(i, Width, Height, ImageMovement.Discard);
//_gl.Assert(true);
//GL.ClearError();
ImageHelper.Resize( i, Width, Height, ImageMovement.Discard );
GL.GetTextureImage(Texture2DTarget.Texture2D, 0, ImageChannel.WithAlphaChannel,
PixelChannelLayout.Byte, i.PixelBuffer);
//_gl.ClearError();
GL.GetTextureImage(
Texture2DTarget.Texture2D, 0, ImageChannel.WithAlphaChannel,
PixelChannelLayout.Byte, i.PixelBuffer );
/*
for (int num = 0; num < i.PixelBuffer.Length; num+=10000)
{
Console.Write($"{i.PixelBuffer[num]}\t");
}
/**/
//GL.Assert(true);
//_gl.Assert(true);
//Array.Fill<byte>(i.PixelBuffer, 24);
GL.BindFrameBuffer(FrameBufferTarget.All, GlHandle.Zero);
GL.BindFrameBuffer( FrameBufferTarget.All, GlHandle.Zero );
//GL.Assert(true);
//_gl.Assert(true);
/**/
/*
+37 -5
View File
@@ -1,5 +1,35 @@
using StgSharp.MVVM.View;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Control.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.Controlling.UsrActivity;
using StgSharp.MVVM.View;
using System;
using System.Collections.Generic;
@@ -8,25 +38,27 @@ using System.Text;
using System.Threading.Tasks;
namespace StgSharp
{
{
public partial class ViewMain
{
protected class Control : ViewResponder<ViewMain>
{
public Control(ViewMain view):base(view)
public Control(ViewMain view) : base(view)
{
}
public override void CustomizedInitialize(Func<ITrigger, string, Action> keyRegister)
{
}
public override bool ValidateInitializing()
{
return true;
}
}
}
}
+46 -9
View File
@@ -1,35 +1,68 @@
using StgSharp.Graphics;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Design.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.Controlling;
using StgSharp.Controlling.UsrActivity;
using StgSharp.Controls;
using StgSharp.Geometries;
using StgSharp.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StgSharp.Controls;
using System.Text.RegularExpressions;
using System.Runtime.CompilerServices;
using StgSharp.Geometries;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace StgSharp
{
public partial class ViewMain
{
internal DemoButtonGroup Group { get; set; }
internal TriggerButton OnlyButton { get; set; }
internal class Design : ViewDesigner<ViewMain>
{
public Design(ViewMain view):base(view)
public Design(ViewMain view) : base(view)
{
}
public override sealed void CustomizedInitialize()
{
Binding.Group = CreateKeyboardButtonGroup<DemoButtonGroup>(
new KeyTrigger(KeyboardKey.LEFT,KeyStatus.PRESS),
new KeyTrigger(KeyboardKey.LEFT, KeyStatus.PRESS),
new KeyTrigger(KeyboardKey.RIGHT, KeyStatus.PRESS),
new KeyTrigger(KeyboardKey.UP, KeyStatus.PRESS),
new KeyTrigger(KeyboardKey.DOWN, KeyStatus.PRESS),
@@ -47,14 +80,18 @@ namespace StgSharp
{
return true;
}
}
}
public class DemoButtonGroup : KeyboardButtonGroup
{
public override sealed void Confirm()
{
return;
}
}
}
+38 -4
View File
@@ -1,4 +1,34 @@
using StgSharp.Graphics;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="NewRender.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 System;
using System.Collections.Generic;
@@ -10,25 +40,29 @@ namespace StgSharp
{
public partial class ViewMain
{
public ParticleRenderStream Stream { get; set; }
private class NewRender : ViewRender<ViewMain>
{
public NewRender(ViewMain view):base(view)
public NewRender(ViewMain view) : base(view)
{
}
public override void CustomizedInitialize()
{
Binding.Stream = CreateRenderStream<ParticleRenderStream>((1,1,1));
Binding.Stream = CreateRenderStream<ParticleRenderStream>((1, 1, 1));
}
public override bool ValidateInitializing()
{
return Binding.Stream != null;
}
}
}
}
@@ -1,24 +0,0 @@
using StgSharp.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp
{
public class Render : ViewRender<ViewMain>
{
public override void CustomizedInitialize()
{
}
public override bool ValidateInitializing()
{
}
}
}
+37 -6
View File
@@ -1,5 +1,34 @@
using StgSharp.Graphics;
using StgSharp.Logic;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ViewMain.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.MVVM;
using StgSharp.MVVM.View;
using StgSharp.MVVM.ViewModel;
@@ -14,13 +43,14 @@ namespace StgSharp
{
public partial class ViewMain : ViewBase
{
Dictionary<string, DataBindingEntry> _databindingIndexMap;
public ViewMain()
{
_databindingIndexMap = new Dictionary<string, DataBindingEntry>();
}
Dictionary<string, DataBindingEntry> _databindingIndexMap;
public override void CustomizedInitialize(ViewModelBase viewModelBinding)
{
Designer = new Design(this);
@@ -34,7 +64,7 @@ namespace StgSharp
public override bool TryGetObjectReference(string name, out DataBindingEntry entry)
{
if (_databindingIndexMap.TryGetValue(name,out entry))
if (_databindingIndexMap.TryGetValue(name, out entry))
{
return true;
}
@@ -56,7 +86,8 @@ namespace StgSharp
protected internal override void Show()
{
Stream.Draw();
Stream.AnotherMain(OnlyButton);
Stream.OtherMain(OnlyButton);
}
}
}
+41 -11
View File
@@ -1,9 +1,37 @@
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharp.MVVM.ViewModel;
using StgSharp.MVVM;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ViewModelMain.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 StgSharpDebug.Logic;
using StgSharp.MVVM;
using StgSharp.MVVM.ViewModel;
using System;
using System.Collections.Generic;
@@ -15,12 +43,18 @@ namespace StgSharp
{
public class ViewModelMain : ViewModelBase
{
public ViewModelMain(ViewPort vp):base(vp,60)
Dictionary<string, DataBindingEntry> dataBindingEntryIndexmap;
public ViewModelMain(ViewPort vp) : base(vp, 60)
{
dataBindingEntryIndexmap = new Dictionary<string, DataBindingEntry>();
}
Dictionary<string, DataBindingEntry> dataBindingEntryIndexmap;
public override void CustomizeInitialize()
{
}
public override bool TryGetObjectReference(string name, out DataBindingEntry entry)
{
@@ -42,9 +76,5 @@ namespace StgSharp
return true;
}
public override void CustomizeInitialize()
{
}
}//------------------------------------- End of Class ------------------------------------------
}
@@ -39,13 +39,13 @@ namespace StgSharp.Entities
{
internal Launcher<EntityPartical> _awardLauncher;
internal LinkedList<Launcher<EntityPartical>> _commonBulletLauncher;
internal Launcher<EntityPartical> _dieBulletLauncher;
internal LinkedList<Launcher<EntityPartical>> _commonBulletLauncher;
public bool _selectalbe;
public Launcher<EntityPartical> AwardLauncher { get; set; }
public LinkedList<Launcher<EntityPartical>> CommonBulletLauncher { get; set; }
public Launcher<EntityPartical> DieBulletLauncher { get; set; }
public LinkedList<Launcher<EntityPartical>> CommonBulletLauncher { get; set; }
public virtual void OnRender()
{
+15 -15
View File
@@ -40,14 +40,24 @@ namespace StgSharp
{
protected uint _bornTick;
internal Point _basePoint;
internal Func<int, vec3d> _movHandler;
internal LinkedList<PlainGeometry> _collisionBox;
internal Sensor<PlainGeometry> _collisionSensor;
internal Func<int,vec3d> _movHandler;
internal Point _basePoint;
internal Point _pos;
internal Point _position;
internal Sensor<PlainGeometry> _collisionSensor;
internal string _texture;
/// <summary>
/// X position of an enenmy entity
/// </summary>
public float X { get; set; }
/// <summary>
/// Y position of an enemy entity
/// </summary>
public float Y { get; set; }
public LinkedList<PlainGeometry> CollisionBox
{
get => _collisionBox;
@@ -63,23 +73,13 @@ namespace StgSharp
set => _collisionSensor = value;
}
public string TextureGL { get; set; }
/// <summary>
/// A 2D vector presenting the position of an enemy entity, position can also be visited by X, Y
/// </summary>
public vec2d Location { get; }
public string TextureGL { get; set; }
/// <summary>
/// X position of an enenmy entity
/// </summary>
public float X { get; set; }
/// <summary>
/// Y position of an enemy entity
/// </summary>
public float Y { get; set; }
public abstract void OnRenderFrame();
public void SetLocation(Point p)
+3 -2
View File
@@ -36,14 +36,15 @@ namespace StgSharp
public class Launcher<T> where T : IEntity
{
internal uint[] launchtick; //发射子弹的内部计时
internal Counter<int> _internalParameter; //发射器的内部计时器
internal EntityPartical _bulletSample; //发射的子弹类型
/*
*用于发射其他的实体,主要是子弹 和 掉落物
*/
internal vec2d _center; //发射器的参考位置,运动轨迹的方程应当基于这个参考点构建
internal Counter<int> _internalParameter; //发射器的内部计时器
internal uint[] launchtick; //发射子弹的内部计时
public EntityPartical Bullet
{
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ErrorDefine.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;
@@ -8,10 +38,12 @@ namespace StgSharp
{
public class UniformEmptyReferenceException : Exception
{
public UniformEmptyReferenceException(string program, string name):
public UniformEmptyReferenceException(string program, string name) :
base($"Location -1 returned when trying to find uniform {name} in shader program {program}")
{
}
}
}
@@ -42,10 +42,12 @@ namespace StgSharp
public static unsafe partial class StgSharp
{
internal const int ssdSegmentLength = 16;
static byte[] _currentHash;
private static bool _inited;
internal const int ssdSegmentLength = 16;
private static int _mainThreadID = -1;
public static byte[] CurrentAssemblyHash
{
@@ -65,8 +67,15 @@ namespace StgSharp
}
}
public static int MainThreadID
{
get => (_mainThreadID == -1) ?
throw new InvalidOperationException("StgSharp environment is not inited. " +
"Main thread id is not available") : _mainThreadID;
}
/// <summary>
/// Init an instance of OpenGL program,
/// 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)
@@ -99,5 +108,5 @@ namespace StgSharp
}
}//------------------------end of class------------------------//
}//-------------------------------------- End of Class ---------------------------------------//
}
@@ -1,4 +1,34 @@
using StgSharp.Graphics;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Monitors.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 System;
using System.Collections.Generic;
@@ -11,18 +41,19 @@ namespace StgSharp
{
public static partial class StgSharp
{
private unsafe static IntPtr[] monitorsArray;
private static unsafe IntPtr[] monitorsArray;
public static unsafe IntPtr[] MonitorsHandleArray
{
get
get
{
if (monitorsArray == null)
{
int count = 0;
IntPtr* arrayhandle = InternalIO.glfwGetMonitors(&count);
monitorsArray = new IntPtr[count];
Marshal.Copy((IntPtr)arrayhandle,monitorsArray,0,count);
Marshal.Copy((IntPtr)arrayhandle, monitorsArray, 0, count);
Marshal.FreeHGlobal((IntPtr)arrayhandle);
}
return monitorsArray;
@@ -31,11 +62,9 @@ namespace StgSharp
public static IntPtr DefaultMonitor
{
get
{
return MonitorsHandleArray[0];
}
get { return MonitorsHandleArray[0]; }
}
}
@@ -42,6 +42,7 @@ using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
#if Windows
@@ -64,8 +65,6 @@ namespace StgSharp
VK
}
public static partial class StgSharp
{
@@ -76,8 +75,9 @@ namespace StgSharp
/// </summary>
public const long version = 430;
private static uint markCount = 0;
private static bool vsyncActivated;
private static uint markCount = 0;
internal static GraphicAPI API = default;
public static void Init()
@@ -89,6 +89,7 @@ namespace StgSharp
InternalIO.InternalWriteLog(
$"Program {Assembly.GetEntryAssembly()!.FullName} Started.",
LogType.Info);
_mainThreadID = Environment.CurrentManagedThreadId;
}
public static void LogError(Exception ex)
@@ -96,6 +97,11 @@ namespace StgSharp
InternalIO.InternalWriteLog(ex.Message, LogType.Error);
}
public static void LogInfo(string log)
{
InternalIO.InternalWriteLog(log, LogType.Info);
}
public static void LogWarning(string log)
{
InternalIO.InternalWriteLog(log, LogType.Warning);
@@ -105,11 +111,6 @@ namespace StgSharp
InternalIO.InternalWriteLog(notVerySeriesException.Message, LogType.Warning);
}
public static void LogInfo(string log)
{
InternalIO.InternalWriteLog(log, LogType.Info);
}
public static void Mark(bool needConsole)
{
markCount++;
@@ -121,7 +122,7 @@ namespace StgSharp
public static void Terminate()
{
MainTimeProvider.Terminate();
MainTimeProvider.StopProvidingTime();
InternalIO.glfwTerminate();
}
@@ -28,7 +28,9 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Logic;
using StgSharp.Timing;
using System;
using System.Collections.Generic;
@@ -39,29 +41,28 @@ using System.Threading;
namespace StgSharp
{
public partial class StgSharp
public static partial class StgSharp
{
internal static StgSharpTime mainTimeProvider = new StgSharpTime();
internal static StgSharpTime mainTimeProvider;
internal static StgSharpTime MainTimeProvider => mainTimeProvider;
internal static TimeSourceProviderBase MainTimeProvider => mainTimeProvider;
}
public sealed class StgSharpTime : TimeSourceProviderBase
{
private static List<TimeSpanProvider> subscriberList = new List<TimeSpanProvider>();
private static long accuracy;
private static Stopwatch mainProvider = new Stopwatch();
private static List<TimeSpanProvider> subscriberList = new List<TimeSpanProvider>();
private static Thread timeProvideThread;
internal StgSharpTime()
{
}
public static StgSharpTime OnlyInstance => StgSharp.MainTimeProvider;
public static TimeSourceProviderBase OnlyInstance => StgSharp.MainTimeProvider;
public override sealed void StartProvidingTime()
{
@@ -92,6 +93,14 @@ namespace StgSharp
timeProvideThread.Start();
}
public override void StopProvidingTime()
{
lock (mainProvider)
{
mainProvider.Stop();
}
}
public void Terminate()
{
lock (mainProvider)
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="globalKeyStat.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.Concurrent;
using System.Collections.Generic;
using System.Linq;
@@ -10,7 +40,8 @@ namespace StgSharp
public static partial class StgSharp
{
private static ConcurrentDictionary<int, KeyStatus> keyListener
private static ConcurrentDictionary<int, KeyStatus> keyListener
= new ConcurrentDictionary<int, KeyStatus>();
public static KeyStatus CheckKey(KeyboardKey key)
@@ -1,4 +1,34 @@
using StgSharp.Math;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="CoordinationBase.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;
@@ -10,9 +40,10 @@ namespace StgSharp.Geometries
{
public abstract class CoordinationBase
{
private bool globalCoordAvailable;
private CoordinationBase localCoordination;
private Matrix44 coordMat;
private bool globalCoordAvailable;
public CoordinationBase(
@@ -24,7 +55,7 @@ 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;
}
@@ -46,7 +77,7 @@ namespace StgSharp.Geometries
set => coordMat.colum2.XYZ = value;
}
protected ref Matrix44 CoordMat
protected ref Matrix44 CoordMat
{
get => ref coordMat;
}
@@ -39,6 +39,13 @@ namespace StgSharp.Geometries
{
public class PlainCoordinate : CoordinationBase
{
private static PlainCoordinate statndardPlainCoordination = new PlainCoordinate(
null, new Point(0, 0, 0),
new vec3d(1, 0, 0),
new vec3d(0, 1, 0)
);
public PlainCoordinate(
CoordinationBase local,
Point origin,
@@ -55,12 +62,7 @@ namespace StgSharp.Geometries
LocalOrigin = origin;
}
private static PlainCoordinate statndardPlainCoordination = new PlainCoordinate(
null, new Point(0,0,0),
new vec3d(1,0,0),
new vec3d(0, 1, 0)
);
public static PlainCoordinate StandardPlainCoordination => statndardPlainCoordination;
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Class1.cs"
// file="SpaceCoordinate.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -38,11 +38,13 @@ namespace StgSharp.Geometries
{
public class SpaceCoordinate : CoordinationBase
{
public SpaceCoordinate(
CoordinationBase localCoordination, Point origin,
vec3d xAxis, vec3d yAxis, vec3d zAxis
) : base(localCoordination)
{
}
}
}
@@ -1,4 +1,34 @@
using StgSharp.Math;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="StreamLocalCoordinate.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;
@@ -1,4 +1,35 @@
using StgSharp.Math;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GeometryOperation.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 StgSharp.Timing;
using System;
using System.Collections.Generic;
@@ -8,34 +39,17 @@ using System.Text;
namespace StgSharp.Geometries
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate vec3d GeometryMotionDelegate(TimeSpanProvider timeSource, out float rotation);
public class GeometryMotion
{
private bool isIncrementMode;
private bool sourceIsStatic;
private TimeSpanProvider time;
private GeometryMotionDelegate movement;
private IntPtr handle;
public static GeometryMotion DefaultMotion
{
get
{
return new GeometryMotion
(
true,
null,
null
);
}
}
private static vec3d defaultMotion(TimeSpanProvider provider, out float rotation)
{
rotation = 0;
return Vec3d.Zero;
}
private TimeSpanProvider time;
public unsafe GeometryMotion(
bool isIncreament,
@@ -53,35 +67,40 @@ namespace StgSharp.Geometries
else if (motionDelegate.Method.IsStatic)
{
sourceIsStatic = true;
handle = Marshal.GetFunctionPointerForDelegate(motionDelegate);
handle = Marshal.GetFunctionPointerForDelegate(motionDelegate);
movement = motionDelegate;
}
else
{
movement = motionDelegate;
}
sourceIsStatic = false;
//sourceIsStatic = false;
}
public bool IsIncrement
{
get => isIncrementMode;
get => isIncrementMode;
}
public static GeometryMotion DefaultMotion
{
get => new GeometryMotion(true, null, null);
}
public unsafe void RunMotion(ref vec3d coord, ref float rotation)
{
float rot = 0;
float rot;
vec3d vec;
if (sourceIsStatic)
if (sourceIsStatic)
{
vec = ((delegate*<TimeSpanProvider, out float, vec3d>)handle)(time, out rot);
vec = ((delegate* unmanaged[Cdecl]<TimeSpanProvider, out float, vec3d>)handle)(time, out rot);
}
else
{
vec = movement(time, out rot);
}
if (isIncrementMode)
{
coord += vec;
@@ -89,9 +108,16 @@ namespace StgSharp.Geometries
}
else
{
coord = vec.XYZ;
coord = vec;
rotation = rot;
}
}
private static vec3d defaultMotion(TimeSpanProvider provider, out float rotation)
{
rotation = 0;
return Vec3d.Zero;
}
}//------------------------------- End of Class -------------------------------
}
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Angle.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;
@@ -9,12 +39,19 @@ namespace StgSharp.Math
{
public static partial class GeometryScaler
{
internal const float DegToRad = 180 / Scaler.Pi;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Degree ToDegree(float value)
public static float Cos(Radius r)
{
return new Degree(value);
return MathF.Cos(r._radius);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Cos(Degree r)
{
return MathF.Cos(r._degree / DegToRad);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -23,24 +60,18 @@ namespace StgSharp.Math
return MathF.Sin(r._radius);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sin(Degree r)
{
return MathF.Sin(r._degree / DegToRad);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Tan(Radius r)
{
return MathF.Tan(r._radius);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Cos(Radius r)
{
return MathF.Cos(r._radius);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sin(Degree r)
{
return MathF.Sin(r._degree/DegToRad);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Tan(Degree r)
{
@@ -48,18 +79,19 @@ namespace StgSharp.Math
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Cos(Degree r)
public static Degree ToDegree(float value)
{
return MathF.Cos(r._degree / DegToRad);
return new Degree(value);
}
}
public struct Degree
{
internal float _degree;
internal Degree(float dgree)
internal Degree(float dgree)
{
_degree = dgree;
}
@@ -68,28 +100,25 @@ namespace StgSharp.Math
{
return new Radius(d._degree / GeometryScaler.DegToRad);
}
}
public struct Radius
{
internal float _radius;
[Obsolete("Unsafe, you may forget this is radius.", true)]
public Radius() { }
public Radius(float radius)
{
_radius = radius;
}
public static Radius Zero
{
get =>new Radius(0);
}
public Radius(float radius)
{
_radius = radius;
}
[Obsolete("Unsafe, you may forget this is radius.",true)]
public Radius() { }
public static implicit operator Degree(Radius r)
{
return new Degree(r._radius * 180 / Scaler.Pi);
get => new Radius(0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -105,9 +134,9 @@ namespace StgSharp.Math
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator +(Radius left, Radius Right)
public static bool operator !=(Radius left, Radius right)
{
return new Radius(left._radius + Right._radius);
return left._radius != right._radius;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -128,16 +157,21 @@ namespace StgSharp.Math
return left._radius / right._radius;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Radius operator +(Radius left, Radius Right)
{
return new Radius(left._radius + Right._radius);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Radius left, Radius right)
{
return left._radius == right._radius;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Radius left, Radius right)
public static implicit operator Degree(Radius r)
{
return left._radius != right._radius;
return new Degree((r._radius * 180) / Scaler.Pi);
}
}
@@ -41,7 +41,6 @@ namespace StgSharp.Geometries
{
public interface IGeometry
{
public CoordinationBase Coordination { get; }
public Point this[int index]
{
@@ -49,19 +48,20 @@ namespace StgSharp.Geometries
set;
}
public int VertexCount
{
get;
}
#pragma warning disable CA1819
public vec4d[] VertexStream
#pragma warning restore CA1819
{
get;
}
public CoordinationBase Coordination { get; }
public ReadOnlySpan<int> VertexIndices
public int VertexCount
{
get;
}
public ReadOnlySpan<int> VertexIndices
{
get;
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Exception.cs"
// file="IGeomtryBuffer.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -28,14 +28,17 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Logic
namespace StgSharp.Geometries
{
}
public interface IGeomtryBuffer
{
}
}
@@ -43,30 +43,6 @@ namespace StgSharp.Geometries
public interface IInstancing
{
public int BufferId
{
get;
internal set;
}
public vec3d CenterPositionGlobal
{
get;
internal set;
}
public vec3d Coord
{
get { return GlobalBuffer.CoordAndRotationList[BufferId].XYZ; }
set { GlobalBuffer.CoordAndRotationList[BufferId] = new vec4d(value.vec); }
}
public IInstancingBuffer GlobalBuffer
{
get;
internal set;
}
public float Rotation
{
get { return GlobalBuffer.CoordAndRotationList[BufferId].W; }
@@ -89,6 +65,30 @@ namespace StgSharp.Geometries
get; set;
}
public IInstancingBuffer GlobalBuffer
{
get;
internal set;
}
public int BufferId
{
get;
internal set;
}
public vec3d CenterPositionGlobal
{
get;
internal set;
}
public vec3d Coord
{
get { return GlobalBuffer.CoordAndRotationList[BufferId].XYZ; }
set { GlobalBuffer.CoordAndRotationList[BufferId] = new vec4d(value.vec); }
}
public void Move()
{
(vec3d coord, float rotation) = (Coord, Rotation);
@@ -1,4 +1,34 @@
using StgSharp.Math;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IInstancingBuffer.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;
@@ -9,6 +39,10 @@ namespace StgSharp.Geometries
public interface IInstancingBuffer
{
public Span<vec4d> CoordAndRotationSpan { get; }
public Span<float> ScalingSpan { get; }
internal IGeometry TypicalShape { get; }
internal List<IInstancing> InstanceList { get; }
@@ -17,11 +51,7 @@ namespace StgSharp.Geometries
internal List<float> ScalingList { get; }
public Span<vec4d> CoordAndRotationSpan { get; }
public Span<float> ScalingSpan { get; }
}
}
@@ -37,6 +37,7 @@ namespace StgSharp.Geometries
public static unsafe class GeometryOperation
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static vec3d DefaultMotion(int tick)
{
@@ -1,4 +1,34 @@
using StgSharp.Math;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IPlainEntity.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;
@@ -11,22 +41,19 @@ namespace StgSharp.Geometries
public interface IPlainEntity
{
public vec2d CenterPosition { get; set; }
public bool CollideWith(IPlainEntity entity);
}
public class PlainEntity:IPlainEntity
public class PlainEntity : IPlainEntity
{
private PlainGeometry _shape;
vec2d IPlainEntity.CenterPosition
{
get => _shape.Coordination.LocalOrigin.Coord.XY;
set => throw new InvalidOperationException();
}
private PlainGeometry _shape;
public PlainEntity(PlainGeometry shape)
{
@@ -37,6 +64,13 @@ namespace StgSharp.Geometries
{
throw new NotImplementedException();
}
vec2d IPlainEntity.CenterPosition
{
get => _shape.Coordination.LocalOrigin.Coord.XY;
set => throw new InvalidOperationException();
}
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IInstancing.cs"
// file="ParticleOnPlain.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -54,7 +54,7 @@ namespace StgSharp.Geometries
((IInstancingBuffer)buffer).InstanceList.Add(this);
}
public int BufferId
public GeometryMotion Motion
{
get;
set;
@@ -65,9 +65,10 @@ namespace StgSharp.Geometries
get;
set;
}
public GeometryMotion Motion
{
get;
public int BufferId
{
get;
set;
}
@@ -77,16 +78,17 @@ namespace StgSharp.Geometries
set;
}
vec2d IPlainEntity.CenterPosition
{
get => GlobalBuffer.CoordAndRotationList[BufferId].XY;
set => throw new NotImplementedException();
}
bool IPlainEntity.CollideWith(IPlainEntity entity)
{
throw new NotImplementedException();
}
vec2d IPlainEntity.CenterPosition
{
get => GlobalBuffer.CoordAndRotationList[BufferId].XY;
set => throw new NotImplementedException();
}
}
}
@@ -41,9 +41,11 @@ namespace StgSharp.Geometries
/// </summary>
public abstract class PlainGeometry : IGeometry
{
protected vec4d[] vertexMat;
internal CoordinationBase coordinate;
internal PlainGeometry(CoordinationBase coordination)
{
coordinate = coordination;
@@ -44,30 +44,24 @@ using System.Threading.Tasks;
namespace StgSharp.Geometries
{
public class PlainInstancingBuffer<T> :
IDisposable,IEnumerable<T>, IInstancingBuffer
where T :
public class PlainInstancingBuffer<T> :
IDisposable, IEnumerable<T>, IInstancingBuffer
where T :
IInstancing
{
private bool disposedValue;
private CoordinatePlain globalCorrdinnate;
private List<vec4d> coordList;
private List<IInstancing> instanceList;
private List<float> scalingList;
private Mutex mutex;
private bool disposedValue;
#region field of mem opt
vec4d[] coordArray;
float[] scaleArray;
#endregion
public PlainInstancingBuffer()
{
coordList = new List<vec4d>(capacity: 100);
instanceList = new List<IInstancing>(capacity:100);
instanceList = new List<IInstancing>(capacity: 100);
scalingList = new List<float>(capacity: 100);
coordArray = Array.Empty<vec4d>();
scaleArray = Array.Empty<float>();
@@ -133,8 +127,6 @@ namespace StgSharp.Geometries
}
}
IGeometry IInstancingBuffer.TypicalShape => throw new NotImplementedException();
public int CreateInstanceID()
{
mutex.WaitOne();
@@ -145,13 +137,32 @@ namespace StgSharp.Geometries
return ret;
}
// ~PlainInstancingBuffer()
// {
// Dispose(disposing: false);
// }
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
public IEnumerator<T> GetEnumerator()
{
foreach (IInstancing item in instanceList)
{
yield return (T)item;
}
}
public void Remove(T instance)
{
mutex.WaitOne();
if (instance.GlobalBuffer != this)
{
throw new ArgumentException(
message:"instance does not belong to current Particle Buffer",
message: "instance does not belong to current Particle Buffer",
paramName: nameof(instance));
}
int index = instance.BufferId;
@@ -170,7 +181,7 @@ namespace StgSharp.Geometries
public void UpdateAllParticles()
{
foreach (var particle in instanceList)
foreach (IInstancing particle in instanceList)
{
particle.Move();
}
@@ -192,31 +203,23 @@ namespace StgSharp.Geometries
}
}
// ~PlainInstancingBuffer()
// {
// Dispose(disposing: false);
// }
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
public IEnumerator<T> GetEnumerator()
{
foreach (var item in instanceList)
{
yield return (T)item;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
foreach (var item in instanceList)
foreach (IInstancing item in instanceList)
{
yield return (T)item;
}
}
IGeometry IInstancingBuffer.TypicalShape => throw new NotImplementedException();
#region field of mem opt
vec4d[] coordArray;
float[] scaleArray;
#endregion
}
}
@@ -38,14 +38,15 @@ namespace StgSharp.Geometries
{
public class Polygon4 : PlainGeometry
{
protected static int[] Indices = [0, 1, 2, 0, 2, 3];
internal Polygon4():base(PlainCoordinate.StandardPlainCoordination)
internal Polygon4() : base(PlainCoordinate.StandardPlainCoordination)
{
vertexMat = new vec4d[4];
}
internal Polygon4(vec4d[] rawCoord):
internal Polygon4(vec4d[] rawCoord) :
base(PlainCoordinate.StandardPlainCoordination)
{
if (rawCoord.Length != 4)
@@ -60,7 +61,7 @@ namespace StgSharp.Geometries
Point topRight,
Point bottomRight,
Point bottomLeft
):base(PlainCoordinate.StandardPlainCoordination)
) : base(PlainCoordinate.StandardPlainCoordination)
{
this[0] = topLeft;
this[1] = topRight;
@@ -69,21 +70,6 @@ namespace StgSharp.Geometries
}
public Polygon4(
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y,
float v3x, float v3y
):base(PlainCoordinate.StandardPlainCoordination)
{
vertexMat = new vec4d[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);
}
public Polygon4(CoordinationBase coordinate,
PlainCoordinate coordination,
@@ -100,6 +86,21 @@ namespace StgSharp.Geometries
}
public Polygon4(
float v0x, float v0y,
float v1x, float v1y,
float v2x, float v2y,
float v3x, float v3y
) : base(PlainCoordinate.StandardPlainCoordination)
{
vertexMat = new vec4d[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);
}
public Polygon4(
PlainCoordinate coordination,
float v0x, float v0y,
@@ -39,7 +39,9 @@ namespace StgSharp.Geometries
public unsafe class Polygon5 : PlainGeometry
{
public unsafe Polygon5():base(PlainCoordinate.StandardPlainCoordination)
internal static int[] Indices = [0, 1, 2, 0, 2, 3, 0, 3, 4];
public unsafe Polygon5() : base(PlainCoordinate.StandardPlainCoordination)
{
vertexMat = new vec4d[5];
}
@@ -50,7 +52,7 @@ namespace StgSharp.Geometries
float v2x, float v2y,
float v3x, float v3y,
float v4x, float v4y
):base(PlainCoordinate.StandardPlainCoordination)
) : base(PlainCoordinate.StandardPlainCoordination)
{
vertexMat = new vec4d[5];
this[0] = new Point(v0x, v0y, 0);
@@ -67,7 +69,7 @@ namespace StgSharp.Geometries
float v2x, float v2y,
float v3x, float v3y,
float v4x, float v4y
):base(coordination)
) : base(coordination)
{
vertexMat = new vec4d[5];
this[0] = new Point(v0x, v0y, 0);
@@ -77,8 +79,7 @@ namespace StgSharp.Geometries
this[4] = new Point(v4x, v4y, 0);
}
internal static int[] Indices = [ 0, 1, 2, 0, 2, 3, 0, 3, 4 ];
public override ReadOnlySpan<int> VertexIndices => Indices;
}
}
@@ -38,7 +38,10 @@ namespace StgSharp.Geometries
{
public class Polygon6 : PlainGeometry
{
public Polygon6():base(PlainCoordinate.StandardPlainCoordination)
internal static int[] Indices = [0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5];
public Polygon6() : base(PlainCoordinate.StandardPlainCoordination)
{
vertexMat = new vec4d[6];
}
@@ -64,8 +67,7 @@ namespace StgSharp.Geometries
vertexMat[6].vec = vert6.vec;
}
internal static int[] Indices = [ 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5 ];
public override ReadOnlySpan<int> VertexIndices => Indices;
}
}
@@ -86,14 +86,12 @@ namespace StgSharp.Geometries
/// <summary>
/// Calculate movement to center
/// </summary>
/// <param name="tick">Current time tick</param>
/// <param name="tick">CurrentBlueprint time tick</param>
/// <returns></returns>
public virtual vec3d MovCenter(uint tick)
{
return default(vec3d);
}
}
}
@@ -42,7 +42,9 @@ namespace StgSharp.Geometries
public unsafe class Triangle : PlainGeometry
{
public Triangle():base(PlainCoordinate.StandardPlainCoordination)
internal static int[] Indices = [0, 1, 2];
public Triangle() : base(PlainCoordinate.StandardPlainCoordination)
{
vertexMat = new vec4d[3];
}
@@ -58,6 +60,17 @@ namespace StgSharp.Geometries
this[2] = vertex03;
}
public Triangle(PlainCoordinate coordination,
Point vertex01,
Point vertex02,
Point vertex03
) : base(coordination)
{
this[0] = vertex01;
this[1] = vertex02;
this[2] = vertex03;
}
public Triangle(
float v0x, float v0y,
float v1x, float v1y,
@@ -69,17 +82,6 @@ namespace StgSharp.Geometries
this[2] = new Point(v2x, v2y, 0);
}
public Triangle(PlainCoordinate coordination,
Point vertex01,
Point vertex02,
Point vertex03
) : base(coordination)
{
this[0] = vertex01;
this[1] = vertex02;
this[2] = vertex03;
}
public Triangle(PlainCoordinate coordination,
float v0x, float v0y,
float v1x, float v1y,
@@ -90,7 +92,6 @@ namespace StgSharp.Geometries
this[1] = new Point(v1x, v1y, 0);
this[2] = new Point(v2x, v2y, 0);
}
internal static int[] Indices = [ 0, 1, 2 ];
public override ReadOnlySpan<int> VertexIndices => Indices;
+37 -6
View File
@@ -1,4 +1,34 @@
using StgSharp.Math;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Point.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;
@@ -11,12 +41,14 @@ namespace StgSharp.Geometries
[StructLayout(LayoutKind.Explicit, Size = 16)]
public struct Point
{
[FieldOffset(0)] private vec3d coord;
[FieldOffset(0)] internal Vector4 coordVec;
public Point(float x, float y, float z)
internal Point(vec4d vector)
{
coordVec = new Vector4(x,y,z,1);
coordVec = vector.vec;
coordVec.W = 1;
}
public Point(vec3d coord)
@@ -25,10 +57,9 @@ namespace StgSharp.Geometries
coordVec.W = 1;
}
internal Point(vec4d vector)
public Point(float x, float y, float z)
{
coordVec = vector.vec;
coordVec.W = 1;
coordVec = new Vector4(x, y, z, 1);
}
public vec3d Coord
@@ -1,4 +1,34 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IImageProvider.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;
@@ -7,6 +37,5 @@ namespace StgSharp.Graphics
public interface IImageProvider
{
Image ProvideImage();
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="FormThreading.cs"
// file="ImageHelper.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -28,47 +28,49 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using StgSharp.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Graphics
{
public partial class View
public static class ImageHelper
{
internal Blueprint localLogic;
/*
private void GatherSingleFrameAsyncThread(MethodInfo[] methods)
public static void Resize(Image i, int width, int height, ImageMovement move)
{
if (methods.Length == 0)
if (i == null)
{
return;
throw new ArgumentNullException(nameof(i));
}
foreach (MethodInfo m in methods) //find all methods decorated by RenderActivityAttribute
Array.Resize(ref i.Data, width * height * i.PixelSize);
i.Height = height;
i.Width = width;
switch (move)
{
RenderActivityAttribute attr = m.GetCustomAttribute<RenderActivityAttribute>(false);
if (attr == null)
{
continue;
}
if (!m.IsStatic && (m.GetParameters().Length != 0) && (m.ReturnType != typeof(void)))
{
throw new NotSupportedException("A render activity cannot have parameters, returning value or be static.");
}
ThreadStart s = (ThreadStart)Delegate.CreateDelegate(typeof(ThreadStart), this, m);
FrameAsyncThread thread = new(s, attr._priority);
//singleFrameAsyncThreadList.Add(thread);
case ImageMovement.Discard:
break;
case ImageMovement.Top:
break;
default:
throw new NotImplementedException();
}
i.PixelUpdateCount++;
}
/**/
}
[Flags]
public enum ImageMovement
{
#pragma warning disable CA1008
Discard = 0,
#pragma warning restore CA1008
Top = 1,
Bottom = 2,
Left = 4,
Right = 8,
TopLeft = Top | Left,
BottomLeft = Bottom | Left,
TopRight = Top | Right,
BottomRight = Bottom | Right,
}
}
@@ -28,28 +28,31 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics
{
/// <summary>
/// Interface of all kinds OpenGL buffer objects
/// </summary>
public abstract class BufferObjectBase : IDisposable
{
protected GlHandle[] _bufferHandle;
protected RenderStream binding;
protected glHandleSet _bufferHandle;
/// <summary>
/// Get the only handle to one of the Object instance
/// </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
@@ -66,7 +69,7 @@ namespace StgSharp.Graphics.GL
/// <inheritdoc/>
public override string ToString()
{
return $"This is a {GetType().FullName}, containing {_bufferHandle.length} buffer handles: {_bufferHandle.ToString()}.";
return $"This is a {GetType().FullName}, containing {_bufferHandle.Length} buffer handles: {_bufferHandle.ToString()}.";
}
protected abstract void Dispose(bool disposing);
@@ -28,7 +28,7 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using System;
using System.Runtime.InteropServices;
@@ -49,22 +49,9 @@ namespace StgSharp.Graphics
public unsafe struct GLFWcontext
{
private int client;
private IntPtr destroy;
private delegate*<byte*> extensionSupported;
private GLFWbool forward, debug, noerror;
//PFNGLGETINTEGERVPROC GetIntegerv;
private IntPtr GetIntegerv;
private delegate*<delegate*<void>, void> getProcAddress;
//PFNGLGETSTRINGPROC GetString;
private IntPtr GetString;
//PFNGLGETSTRINGIPROC GetStringi;
private IntPtr GetStringi;
private int major, minor, revision;
/*
void (* makeCurrent) (glfwWindow*);
void (* swapBuffers) (glfwWindow*);
@@ -75,12 +62,26 @@ namespace StgSharp.Graphics
*/
private delegate*<glfwWindow*> makeCurrent;
private delegate*<glfwWindow*> swapBuffer;
private delegate*<int> swapInterval;
private GLFWbool forward, debug, noerror;
private int client;
private int major, minor, revision;
private int profile;
private int release;
private int robustness;
private int source;
private delegate*<glfwWindow*> swapBuffer;
private delegate*<int> swapInterval;
private IntPtr destroy;
//PFNGLGETINTEGERVPROC GetIntegerv;
private IntPtr GetIntegerv;
//PFNGLGETSTRINGPROC GetString;
private IntPtr GetString;
//PFNGLGETSTRINGIPROC GetStringi;
private IntPtr GetStringi;
internal struct egl
{
@@ -165,15 +166,16 @@ namespace StgSharp.Graphics
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.
*/
private int height;
/*! The width, in pixels, of this image.
*/
private int width;
/*! The pixel data of this image, arranged left-to-right, top-to-bottom.
*/
private byte* pixels;
}
@@ -182,22 +184,24 @@ namespace StgSharp.Graphics
public unsafe struct GLFWgamepadstate
{
/*! The states of each [gamepad axis](@ref gamepad_axes), in the range -1.0
* to 1.0 inclusive.
*/
public fixed float axes[6];
/*! The states of each [gamepad button](@ref gamepad_buttons), `GLFW_PRESS`
* or `GLFW_RELEASE`.
*/
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];
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct GLFWallocator
{
private void* user;
//GLFWallocatefun allocate;
private IntPtr allocate;
@@ -207,34 +211,32 @@ namespace StgSharp.Graphics
//GLFWreallocatefun reallocate;
private IntPtr reallocate;
private void* user;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct glfwMonitor
{
private fixed byte name[128];
private IntPtr userPointer;
private int width, height;
private glfwVideomode* modes;
private glfwWindow* window;
private glfwVideomode* modes;
private int modeCount;
private glfwVideomode currentMode;
private fixed byte name[128];
private glfwGammaramp currentRamp;
private glfwGammaramp originalRamp;
private glfwGammaramp currentRamp;
private glfwVideomode currentMode;
private int modeCount;
private int width, height;
private IntPtr userPointer;
public glfwMonitor()
{ }
public unsafe string Name
{
get
get
{
fixed (byte* cptr = name)
{
@@ -242,69 +244,73 @@ namespace StgSharp.Graphics
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
unsafe struct glfwWindow
{
glfwWindow* next;
// Window settings and state
int resizable;
int decorated;
int autoIconify;
int floating;
int focusOnShow;
int mousePassthrough;
int shouldClose;
void* userPointer;
int doublebuffer;
// glfwVideomode videoMode; // 根据GLFWvidmode的定义转换
IntPtr monitor; // _GLFWmonitor* monitor;
IntPtr cursor; // _GLFWcursor* cursor;
int minwidth, minheight;
int maxwidth, maxheight;
int numer, denom;
int stickyKeys;
int stickyMouseButtons;
int lockKeyMods;
int cursorMode;
public fixed byte mouseButtons[GLconst.GLFW_MOUSE_BUTTON_LAST + 1];
public fixed byte keys[GLconst.GLFW_KEY_LAST + 1];
bool rawMouseMotion;
Callbacks callbacks;
// Virtual cursor position when cursor is disabled
double virtualCursorPosX, virtualCursorPosY;
bool rawMouseMotion;
int autoIconify;
int cursorMode;
int decorated;
int doublebuffer;
int floating;
int focusOnShow;
int lockKeyMods;
int maxwidth, maxheight;
// _GLFWcontext context; // 根据_GLFWcontext的定义转换
int minwidth, minheight;
int mousePassthrough;
int numer, denom;
// Window settings and state
int resizable;
int shouldClose;
int stickyKeys;
int stickyMouseButtons;
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];
// _GLFWcontext viewPortDisplay; // 根据_GLFWcontext的定义转换
// Callbacks are represented as IntPtr since we don't need the actual function pointers in C#
internal struct Callbacks
{
internal IntPtr pos;
internal IntPtr size;
internal IntPtr close;
internal IntPtr refresh;
internal IntPtr focus;
internal IntPtr iconify;
internal IntPtr maximize;
internal IntPtr fbsize;
internal IntPtr scale;
internal IntPtr mouseButton;
internal IntPtr cursorPos;
internal IntPtr cursorEnter;
internal IntPtr scroll;
internal IntPtr key;
internal IntPtr character;
internal IntPtr charmods;
internal IntPtr close;
internal IntPtr cursorEnter;
internal IntPtr cursorPos;
internal IntPtr drop;
}
Callbacks callbacks;
internal IntPtr fbsize;
internal IntPtr focus;
internal IntPtr iconify;
internal IntPtr key;
internal IntPtr maximize;
internal IntPtr mouseButton;
internal IntPtr pos;
internal IntPtr refresh;
internal IntPtr scale;
internal IntPtr scroll;
internal IntPtr size;
// GLFW_PLATFORM_WINDOW_STATE platformWindowState;
}
}
// GLFW_PLATFORM_WINDOW_STATE platformWindowState;
}
[StructLayout(LayoutKind.Sequential)]
@@ -345,9 +351,9 @@ namespace StgSharp.Graphics
public unsafe struct GLFWinitconfig
{
private int angleType;
private GLFWbool hatButtons;
private int angleType;
private int platformID;
//PFN_vkGetInstanceProcAddr vulkanLoader;
@@ -359,19 +365,20 @@ namespace StgSharp.Graphics
public unsafe struct GLFWwndconfig
{
private byte* title;
private GLFWbool autoIconify;
private GLFWbool centerCursor;
private GLFWbool decorated;
private GLFWbool floating;
private GLFWbool focused;
private GLFWbool focusOnShow;
private int height;
private GLFWbool maximized;
private GLFWbool mousePassthrough;
private GLFWbool resizable;
private GLFWbool scaleToMonitor;
private byte* title;
private GLFWbool visible;
private int height;
private int width;
private int xpos;
@@ -437,19 +444,20 @@ namespace StgSharp.Graphics
public unsafe struct GLFWctxconfig
{
private int client;
private GLFWbool debug;
private GLFWbool forward;
private GLFWbool noerror;
private int client;
private int major;
private int minor;
private GLFWbool noerror;
private int profile;
private int release;
private int robustness;
private int source;
//glfwWindow* share;
private IntPtr share;
private int source;
internal Nsgl nsgl = new Nsgl();
@@ -470,6 +478,11 @@ namespace StgSharp.Graphics
public unsafe struct GLFWfbconfig
{
private GLFWbool doublebuffer;
private GLFWbool sRGB;
private GLFWbool stereo;
private GLFWbool transparent;
private int accumAlphaBits;
private int accumBlueBits;
private int accumGreenBits;
@@ -478,16 +491,12 @@ namespace StgSharp.Graphics
private int auxBuffers;
private int blueBits;
private int depthBits;
private GLFWbool doublebuffer;
private int greenBits;
private uintptr_t handle;
private int redBits;
private int samples;
private GLFWbool sRGB;
private int stencilBits;
private GLFWbool stereo;
private GLFWbool transparent;
private uintptr_t handle;
}
@@ -495,37 +504,37 @@ namespace StgSharp.Graphics
internal unsafe struct GLFWlibrary
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = GLconst.GLFW_JOYSTICK_LAST + 1)]
private GLFWjoystick[] joysticks = new GLFWjoystick[GLconst.GLFW_JOYSTICK_LAST + 1];
private GLFWallocator allocator;
private GLFWbool initialized;
private GLFWbool joysticksInitialized;
private GLFWls contextSlot;
private GLFWls errorSlot;
private GLFWmutex errorLock;
private GLFWplatform platform;
private int mappingCount;
private int monitorCount;
//GLFWcursor* cursorListHead;
private IntPtr cursorListHead;
//GLFWerror* errorListHead;
private IntPtr errorListHead;
private GLFWmutex errorLock;
private GLFWls errorSlot;
private GLFWbool initialized;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = GLconst.GLFW_JOYSTICK_LAST + 1)]
private GLFWjoystick[] joysticks = new GLFWjoystick[GLconst.GLFW_JOYSTICK_LAST + 1];
private GLFWbool joysticksInitialized;
private int mappingCount;
//GLFWmapping* mappings;
private IntPtr mappings;
private int monitorCount;
//GLFWmonitor** monitors;
private IntPtr monitors;
private GLFWplatform platform;
//glfwWindow* windowListHead;
private IntPtr windowListHead;
@@ -548,8 +557,8 @@ namespace StgSharp.Graphics
private GLFWfbconfig framebuffer;
private GLFWinitconfig init;
private int refreshRate;
private GLFWwndconfig window;
private int refreshRate;
}
@@ -566,23 +575,36 @@ namespace StgSharp.Graphics
internal unsafe struct Egl
{
internal void* display;
internal void* handle;
internal bool ANGLE_platform_angle;
internal bool ANGLE_platform_angle_d3d;
internal bool ANGLE_platform_angle_metal;
internal bool ANGLE_platform_angle_opengl;
internal bool ANGLE_platform_angle_vulkan;
internal bool EXT_client_extensions;
internal bool EXT_platform_base;
internal bool EXT_platform_wayland;
internal bool EXT_platform_x11;
internal bool EXT_present_opaque;
internal bool KHR_colorSpace;
internal bool KHR_context_flush_control;
internal bool KHR_create_context;
internal bool KHR_create_context_no_error;
internal bool KHR_get_all_proc_addresses;
internal bool prefix;
internal int major, minor;
internal int platform;
internal IntPtr BindAPI;
internal IntPtr CreateContext;
internal IntPtr CreatePlatformWindowSurfaceEXT;
internal IntPtr CreateWindowSurface;
internal IntPtr DestroyContext;
internal IntPtr DestroySurface;
internal void* display;
internal bool EXT_client_extensions;
internal bool EXT_platform_base;
internal bool EXT_platform_wayland;
internal bool EXT_platform_x11;
internal bool EXT_present_opaque;
internal IntPtr GetConfigAttrib;
internal IntPtr GetConfigs;
@@ -591,20 +613,8 @@ namespace StgSharp.Graphics
internal IntPtr GetPlatformDisplayEXT;
internal IntPtr GetProcAddress;
internal void* handle;
internal IntPtr Initialize;
internal bool KHR_colorSpace;
internal bool KHR_context_flush_control;
internal bool KHR_create_context;
internal bool KHR_create_context_no_error;
internal bool KHR_get_all_proc_addresses;
internal int major, minor;
internal IntPtr MakeCurrent;
internal int platform;
internal bool prefix;
internal IntPtr QueryString;
internal IntPtr SwapBuffers;
internal IntPtr SwapInterval;
@@ -615,6 +625,8 @@ namespace StgSharp.Graphics
internal unsafe struct Osmesa
{
private void* handle;
private IntPtr CreateContextAttribs;
private IntPtr CreateContextExt;
@@ -622,8 +634,6 @@ namespace StgSharp.Graphics
private IntPtr GetColorBuffer;
private IntPtr GetDepthBuffer;
private IntPtr GetProcAddress;
private void* handle;
private IntPtr MakeCurrent;
}
@@ -631,17 +641,18 @@ namespace StgSharp.Graphics
internal unsafe struct vk
{
private void* handle;
private GLFWbool available;
private GLFWbool EXT_metal_surface;
private fixed ulong extensions[2];
private IntPtr GetInstanceProcAddr;
private void* handle;
private GLFWbool KHR_surface;
private GLFWbool KHR_wayland_surface;
private GLFWbool KHR_win32_surface;
private GLFWbool KHR_xcb_surface;
private GLFWbool KHR_xlib_surface;
private GLFWbool MVK_macos_surface;
private IntPtr GetInstanceProcAddr;
private fixed ulong extensions[2];
public vk()
{
@@ -664,12 +675,13 @@ namespace StgSharp.Graphics
public unsafe struct GLFWmapelement
{
private sbyte axisOffset;
private sbyte axisScale;
private byte index;
private byte type;
private sbyte axisOffset;
private sbyte axisScale;
}
[StructLayout(LayoutKind.Sequential)]
@@ -694,20 +706,21 @@ namespace StgSharp.Graphics
public unsafe struct GLFWjoystick
{
private GLFWbool allocated;
private float* axes;
private byte* buttons;
private byte* hats;
private void* userPointer;
private fixed byte guid[33];
private fixed byte name[128];
private GLFWbool allocated;
private GLFWbool connected;
private int axisCount;
private int buttonCount;
private byte* buttons;
private GLFWbool connected;
private fixed byte guid[33];
private int hatCount;
private byte* hats;
//GLFWmapping* mapping;
private IntPtr mapping;
private fixed byte name[128];
private void* userPointer;
// This is defined in platform.h
// not completed in transforming
@@ -730,12 +743,12 @@ namespace StgSharp.Graphics
public unsafe struct GLFWplatform
{
private int platformID;
// init
//GLFWbool(*init)(void);
private IntPtr init;
private int platformID;
//void (* terminate) (void);
private IntPtr terminate;
internal IntPtr createCursor;
@@ -953,6 +966,9 @@ namespace StgSharp.Graphics
[StructLayout(LayoutKind.Sequential)]
internal struct GLsync
{
public IntPtr Handle;
}
#endregion glad struct
@@ -28,14 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
/*
* This file is created to link functions in OpenGL to version in C#
* The name of delegates and organization to init all these delegates
* are refferd from GLAD1 in agreement of MIT license generated from
* https://glad.dav1d.de/
*/
using StgSharp.Math;
using System;
@@ -44,19 +36,22 @@ using System.Runtime.InteropServices;
namespace StgSharp.Graphics
{
#region StgSharpDele
public unsafe delegate void FrameBufferSizeHandler(IntPtr window, uint width, uint height);
#endregion
/// <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>
/// <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 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);
@@ -31,7 +31,7 @@
using System;
using System.Drawing;
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics.OpenGL
{
//rename types in style of GLconst
@@ -4849,13 +4849,18 @@ namespace StgSharp.Graphics.GL
public static class glAttachment
{
public const uint Depth = GLconst.DEPTH_ATTACHMENT;
public const uint DepthAndStencil = GLconst.DEPTH_STENCIL_ATTACHMENT;
public const uint Stencil = GLconst.STENCIL_ATTACHMENT;
private static int colorRange =
glFunc.GetMaskInteger((uint)GLconst.MAX_COLOR_ATTACHMENTS);
OpenGLFunction.CurrentGL.GetMaskInteger((uint)GLconst.MAX_COLOR_ATTACHMENTS);
public static uint Color(int i)
{
#if DEBUG
if (i>colorRange||i<0)
if ((i > colorRange) || (i < 0))
{
throw new ArgumentOutOfRangeException();
}
@@ -4863,8 +4868,5 @@ namespace StgSharp.Graphics.GL
return (uint)(GLconst.COLOR_ATTACHMENT0 + i);
}
public const uint Depth = GLconst.DEPTH_ATTACHMENT;
public const uint Stencil = GLconst.STENCIL_ATTACHMENT;
public const uint DepthAndStencil = GLconst.DEPTH_STENCIL_ATTACHMENT;
}
}
@@ -30,9 +30,11 @@
//-----------------------------------------------------------------------
namespace StgSharp.Graphics.GL
using System.Runtime.CompilerServices;
namespace StgSharp.Graphics.OpenGL
{
public enum ImageChannelLayout
public enum PixelChannelLayout
{
UByte = GLconst.UNSIGNED_BYTE,
Byte = GLconst.BYTE,
@@ -41,20 +43,31 @@ namespace StgSharp.Graphics.GL
UInt = GLconst.UNSIGNED_INT,
Int = GLconst.INT,
Float = GLconst.FLOAT,
UByte332 = 0x8032, // GL_UNSIGNED_BYTE_3_3_2
UByte233Rev = 0x8362, // GL_UNSIGNED_BYTE_2_3_3_REV
UShort565 = 0x8363, // GL_UNSIGNED_SHORT_5_6_5
UShort565Rev = 0x8364, // GL_UNSIGNED_SHORT_5_6_5_REV
UShort4444 = 0x8033, // GL_UNSIGNED_SHORT_4_4_4_4
UShort4444Rev = 0x8034, // GL_UNSIGNED_SHORT_4_4_4_4_REV
UShort5551 = 0x8035, // GL_UNSIGNED_SHORT_5_5_5_1
UShort1555Rev = 0x8366, // GL_UNSIGNED_SHORT_1_5_5_5_REV
UInt8888 = 0x8035, // GL_UNSIGNED_INT_8_8_8_8
UInt8888Rev = 0x8367, // GL_UNSIGNED_INT_8_8_8_8_REV
UInt1010102 = 0x8036, // GL_UNSIGNED_INT_10_10_10_2
UInt2101010Rev = 0x8368 // GL_UNSIGNED_INT_2_10_10_10_REV
UByte332 = GLconst.UNSIGNED_BYTE_3_3_2,
UByte233Rev = GLconst.UNSIGNED_BYTE_2_3_3_REV,
UShort565 = GLconst.UNSIGNED_SHORT_5_6_5,
UShort565Rev = GLconst.UNSIGNED_SHORT_5_6_5_REV,
UShort4444 = GLconst.UNSIGNED_SHORT_4_4_4_4,
UShort4444Rev = GLconst.UNSIGNED_SHORT_4_4_4_4_REV,
UShort5551 = GLconst.UNSIGNED_SHORT_5_5_5_1,
UShort1555Rev = GLconst.UNSIGNED_SHORT_1_5_5_5_REV,
UInt8888 = GLconst.UNSIGNED_INT_8_8_8_8,
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
IncompleteDrawBuffer = GLconst.FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER, // GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER
IncompleteReadBuffer = GLconst.FRAMEBUFFER_INCOMPLETE_READ_BUFFER, // GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER
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
{
@@ -81,6 +94,12 @@ namespace StgSharp.Graphics.GL
BGRA = GLconst.BGRA
}
public enum FrameBufferAttachment
{
Color = GLconst.COLOR_ATTACHMENT0,
Depth = GLconst.DEPTH_ATTACHMENT,
Stencil = GLconst.STENCIL_ATTACHMENT,
}
public enum Texture2DTarget
{
@@ -103,7 +103,6 @@ namespace StgSharp.Graphics
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 FramebuffersizeHandler(IntPtr window, int width, int height); //window is the pointer to a glfwWindow instance
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);
@@ -1,60 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.GL
{
#pragma warning disable CA1008
#pragma warning disable CA1028
public enum FrameBufferTarget:uint
#pragma warning restore CA1028
#pragma warning restore CA1008
{
Read = GLconst.READ_FRAMEBUFFER,
All = GLconst.FRAMEBUFFER,
Draw = GLconst.DRAW_FRAMEBUFFER,
}
public class FrameBuffer : BufferObjectBase
{
internal unsafe FrameBuffer(int count, glRenderStream contextBinding)
{
binding = contextBinding;
_bufferHandle = new glHandleSet(count);
((GLcontext*)binding.ContextHandle)->glGenFramebuffers((uint)count,_bufferHandle.handle);
}
/// <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.
/// </summary>
/// <param name="index">Index of object to be binded in handle set</param>
public unsafe override void Bind(int index)
{
glFunc.BindFrameBuffer(FrameBufferTarget.All,_bufferHandle[index]);
}
public static void BindNull()
{
glFunc.BindFrameBuffer(FrameBufferTarget.All,glHandle.Zero);
}
/// <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.
/// </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>
public unsafe void Bind(FrameBufferTarget target, int index)
{
((GLcontext*)binding.ContextHandle)->glBindFramebuffer((uint)target, _bufferHandle[index].Value);
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
}
}
@@ -1,38 +0,0 @@
using System;
using System.Collections.Generic;
using System.Security.Principal;
using System.Text;
namespace StgSharp.Graphics.GL
{
public class RenderBuffer : BufferObjectBase
{
public RenderBuffer(int count, glRenderStream binding)
{
this.binding = binding;
_bufferHandle = glFunc.GenRenderBuffer(count);
}
public override void Bind(int index)
{
glFunc.BindRenderBuffer(this[index]);
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
public void Store(RenderBufferInternalFormat format, (int width,int height) size)
{
if (size.width > binding.Width || size.height>binding.Height)
{
StgSharp.LogWarning("FrameBuffer is larger than current canvas binding");
}
}
}
}
@@ -1,155 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="texture.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.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.GL
{
public unsafe class TextureGL
{
internal static bool[] unitActivated = new bool[16];
private IntPtr binding;
internal glHandleSet _textureHandle;
internal Image[] sourceList;
public glHandle this[int index]
{
get => _textureHandle[index];
}
internal TextureGL(int n, glRenderStream binding)
{
sourceList = new Image[n];
this.binding = binding.ContextHandle;
_textureHandle = glFunc.GenTextures(n);
}
public static void Activate(TextureUnit unit)
{
glFunc.ActiveTexture((uint)unit);
}
public void Bind2D(int index)
{
glFunc.BindTexture(GLconst.TEXTURE_2D, _textureHandle[index]);
}
/// <summary>
/// </summary>
/// <param name="index"> </param>
/// <param name="i"> </param>
public unsafe void LoadTexture(int index, Image i)
{
sourceList[index] = i;
glArrayHandle handle = sourceList[index].GetArrayHandle();
glFunc.TextureImage2d(
Texture2DTarget.Texture2D, 0, (uint)i.Channel,
(uint)sourceList[index].Width, (uint)sourceList[index].Height,
(uint)i.Channel, ImageChannelLayout.Byte,
pixelArrayHandle: handle
);
handle.Release();
}
#region texture setting
public void Set2dFilterProperty(
Filter onMinify, Filter onMagnify)
{
glFunc.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MIN_FILTER, (int)onMinify);
glFunc.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MAG_FILTER, (int)onMagnify);
}
public void Set2dWrapProperty(
Wrap onHorizontial, Wrap onVertical)
{
glFunc.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_S, (int)onHorizontial);
glFunc.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_T, (int)onVertical);
}
#endregion texture setting
}
#pragma warning disable CA1008
public enum Filter
#pragma warning restore CA1008
{
Nearest = GLconst.NEAREST,
Linear = GLconst.LINEAR,
NearestLinearMipmap = GLconst.NEAREST_MIPMAP_LINEAR,
LinearLinearMipmap = GLconst.LINEAR_MIPMAP_LINEAR,
NearestNearestMipmap = GLconst.NEAREST_MIPMAP_NEAREST,
LinearNearestMipmap = GLconst.LINEAR_MIPMAP_NEAREST,
}
#pragma warning disable CA1008
public enum TextureUnit
#pragma warning restore CA1008
{
Unit0 = GLconst.TEXTURE0,
Unit1 = GLconst.TEXTURE1,
Unit2 = GLconst.TEXTURE2,
Unit3 = GLconst.TEXTURE3,
Unit4 = GLconst.TEXTURE4,
Unit5 = GLconst.TEXTURE5,
Unit6 = GLconst.TEXTURE6,
Unit7 = GLconst.TEXTURE7,
Unit8 = GLconst.TEXTURE8,
Unit9 = GLconst.TEXTURE9,
Unit10 = GLconst.TEXTURE10,
Unit11 = GLconst.TEXTURE11,
Unit12 = GLconst.TEXTURE12,
Unit13 = GLconst.TEXTURE13,
Unit14 = GLconst.TEXTURE14,
Unit15 = GLconst.TEXTURE15,
}
#pragma warning disable CA1008
public enum Wrap
#pragma warning restore CA1008
{
Repeat = GLconst.REPEAT,
MirroredRepeat = GLconst.MIRRORED_REPEAT,
ClampToEdge = GLconst.CLAMP_TO_EDGE,
ClampToBorder = GLconst.CLAMP_TO_BORDER,
}
}
@@ -1,362 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLhandle.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.Data.Common;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics
{
/// <summary>
/// A handle to an OpenGL object,
/// must be indexed from a <see cref="glHandleSet"/>.
/// Direct call will cause <see langword="InvalidOperationException"/>
/// </summary>
public unsafe class glHandle: IDisposable
{
private static uint* zeroHandle = (uint*)Marshal.AllocHGlobal(Marshal.SizeOf<uint>());
internal uint* source;
internal uint* valuePtr;
private glHandle(IntPtr handle)
{
this.valuePtr = (uint*)handle;
source = (uint*)0;
}
private glHandle(uint value)
{
source = (uint*)0;
valuePtr = (uint*)Marshal.AllocHGlobal(sizeof(uint));
*valuePtr = value;
}
internal glHandle(uint* val, glHandleSet set)
{
source = set!=null ? set!.handle:(uint*)0;
valuePtr = val;
}
[Obsolete("Cannot init instance of this type", true)]
public glHandle()
{
}
public IntPtr Handle
{
get=> (IntPtr)valuePtr;
}
public bool IsIsolated
{
get => source == (uint*)0;
}
public uint Value
{
get => *valuePtr;
set => *valuePtr = value;
}
public static glHandle ZeroHandle => FromPtr(IntPtr.Zero);
public static glHandle Zero => Alloc(0);
public static glHandle Alloc(uint value)
{
return new glHandle(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glHandle FromPtr(IntPtr p)
{
return new glHandle(p);
}
~glHandle()
{
if (valuePtr != zeroHandle && IsIsolated)
{
Marshal.FreeHGlobal((IntPtr)valuePtr);
}
}
protected virtual void Dispose(bool disposing)
{
if (IsIsolated)
{
GCHandle.FromIntPtr((IntPtr)valuePtr).Free();
if (disposing)
{
}
}
}
//
// ~glHandle()
// {
// Dispose(disposing: false);
// }
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
public unsafe class glSHandle
{
private static int* zeroHandle = (int*)Marshal.AllocHGlobal(Marshal.SizeOf<int>());
internal int* source;
internal int* valuePtr;
private glSHandle(IntPtr handle)
{
this.valuePtr = (int*)handle;
source = (int*)0;
}
private glSHandle(int value)
{
source = (int*)0;
valuePtr = (int*)Marshal.AllocHGlobal(sizeof(int));
*valuePtr = value;
}
internal glSHandle(int* val, glHandleSet set)
{
source = set != null ? (int*)set!.handle : (int*)0;
valuePtr = val;
}
[Obsolete("Cannot init instance of this type", true)]
public glSHandle()
{
}
public IntPtr Handle
{
get => (IntPtr)valuePtr;
}
public bool IsIsolated
{
get => source == (uint*)0;
}
public int Value
{
get => *valuePtr;
set => *valuePtr = value;
}
public static glSHandle Zero => Alloc(0);
public static glSHandle Alloc(int value)
{
return new glSHandle(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glSHandle FromPtr(IntPtr p)
{
return new glSHandle(p);
}
~glSHandle()
{
if (valuePtr != zeroHandle && IsIsolated)
{
Marshal.FreeHGlobal((IntPtr)valuePtr);
}
}
}
public unsafe class glArrayHandle
{
internal readonly Array a;
internal GCHandle handle;
private bool disposedValue;
internal glArrayHandle(Array array)
{
this.a = array;
handle = GCHandle.Alloc(array, GCHandleType.Pinned);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IntPtr AddressOfArray()
{
if (handle != default)
{
return handle.AddrOfPinnedObject();
}
else
{
throw new InvalidOperationException();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glArrayHandle Alloc<T>(T[] array) where T : struct
{
return new glArrayHandle(array);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glArrayHandle CopyAlloc<T>(T[] array) where T : struct
{
Array copy = new T[array.Length];
array.CopyTo(copy, 0);
return new glArrayHandle(copy);
}
public void Release()
{
handle.Free();
handle = default;
}
}
/// <summary>
/// A handle to an OpenGL object.
/// </summary>
public unsafe class glHandleSet
{
private readonly uint[] _value;
internal uint* handle;
internal int length;
public glHandleSet(int count)
{
_value = new uint[count];
length = count;
handle = (uint*)GCHandle.Alloc(_value, GCHandleType.Pinned).AddrOfPinnedObject();
}
public IntPtr Handle
{
get => (IntPtr)handle;
}
public glHandle this[int index]
{
get
{
if (index > length)
{
throw new IndexOutOfRangeException();
}
return new glHandle(handle + index, this);
}
}
public glSHandle this[uint index]
{
get
{
if (index > length)
{
throw new IndexOutOfRangeException();
}
return new glSHandle(((int*)handle) + index, this);
}
}
public static void Copy(in glHandleSet source, glHandleSet target)
{
if ((source == null) || (target == null))
{
throw new NullReferenceException();
}
if (source.length != target.length)
{
throw new Exception($"Lengths of {nameof(source)} and {nameof(target)} are not equal.");
}
for (int i = 0; i < source.length; i++)
{
target._value[i] = source._value[i];
}
}
public void Pin()
{
if (_value == null)
{
return;
}
handle = (uint*)GCHandle.Alloc(_value, GCHandleType.Pinned).AddrOfPinnedObject();
}
/// <summary>
/// Release all resource in this handle.
/// This will release all resource in this <see cref="glHandle"/>.
/// This <see langword="glHandle"/> will be not usable.
/// </summary>
public void Release()
{
if (_value == null)
{
return;
}
else
{
GCHandle.FromIntPtr((IntPtr)handle).Free();
handle = (uint*)IntPtr.Zero;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetValue(int index, uint value)
{
_value[index] = value;
}
~glHandleSet()
{
}
}
}
@@ -1,35 +0,0 @@
using StgSharp.Graphics.GL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.ShaderEdit
{
public interface IglConvertable
{
/// <summary>
///
/// </summary>
public void SetAllUniforms();
/// <summary>
///
/// </summary>
public void GainAllUniforms(ShaderProgram source, params string[] uniformName);
/// <summary>
///
/// </summary>
public void DisplayGLtypeDefinition();
/// <summary>
///
/// </summary>
/// <returns></returns>
public ShaderStruct GetConvertedGLtype();
}
}
@@ -1,257 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Uniform.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.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics.GL
{
public class Uniform
{
protected IntPtr binding;
internal glSHandle id;
public glSHandle Handle
{
get => id;
}
}
public sealed class Uniform<T> : Uniform
where T : struct
{
internal unsafe Uniform(glSHandle id)
{
this.id = id;
}
internal unsafe Uniform(
ShaderProgram program, string name, glRenderStream binding)
{
this.binding = binding.ContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal unsafe Uniform(
ShaderProgram program, string name, IntPtr binding)
{
this.binding = binding;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal Uniform()
{
}
internal static Uniform<T> FromHandle(glSHandle handle)
{
return new Uniform<T>() { id = handle };
}
}
public sealed class Uniform<T, U>: Uniform
where T : struct
where U : struct
{
internal unsafe Uniform(glSHandle id)
{
this.id = id;
}
internal unsafe Uniform(
ShaderProgram program, string name, glRenderStream binding)
{
this.binding = binding.ContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal unsafe Uniform(
ShaderProgram program, string name, IntPtr binding)
{
this.binding = binding;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal Uniform()
{
}
internal static Uniform<T,U> FromHandle(glSHandle 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
{
internal unsafe Uniform(glSHandle id)
{
this.id = id;
}
internal unsafe Uniform(
ShaderProgram program, string name)
{
this.binding = glFunc.CurrentContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
public unsafe Uniform(ShaderProgram program, string name, glRenderStream binding)
{
this.binding = binding.ContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal Uniform()
{
}
internal static Uniform<T,U,V> FromHandle(glSHandle 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
{
internal unsafe Uniform(glSHandle id)
{
this.id = id;
}
internal unsafe Uniform(ShaderProgram program, string name, glRenderStream binding)
{
this.binding = binding.ContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal unsafe Uniform(
ShaderProgram program, string name)
{
this.binding = glFunc.CurrentContextHandle;
id = glFunc.GetUniformLocation(program.handle, name);
}
internal Uniform()
{
}
internal static Uniform<T, U, V, W> FromHandle(glSHandle handle)
{
return new Uniform<T, U, V, W>() { id = handle };
}
}
internal static partial class glFunc
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static void SetUniformValue
(Uniform<Matrix44> uniform, Matrix44 mat)
{
Matrix44 temp = mat;
Context.glUniformMatrix4fv(uniform.id.Value, 1, false, (float*)&temp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static void SetUniformValue(Uniform<float, float, float, float> uniform, vec4d vec)
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.Value , 4, &temp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static void SetUniformValue(Uniform<vec4d> uniform, vec4d vec)
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.Value , 4, &temp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetUniformValue(Uniform<float> uniform, float v0)
{
Context.glUniform1f(uniform.id.Value , v0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetUniformValue(Uniform<int> uniform, int i0)
{
Context.glUniform1i(uniform.id.Value , i0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetUniformValue(Uniform<float, float> uniform, float v0, float v1)
{
Context.glUniform2f(uniform.id.Value , v0, v1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetUniformValue(Uniform<float, float, float> uniform, float v0, float v1, float v2)
{
Context.glUniform3f(uniform.id.Value , v0, v1, v2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetUniformValue(Uniform<float, float, float, float> uniform, float v0, float v1, float v2, float v3)
{
Context.glUniform4f(uniform.id.Value , v0, v1, v2, v3);
}
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Get.cs"
// file="IGraphicAPIs.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -28,26 +28,17 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Graphics
{
public partial class View
public interface IGraphicAPIs
{
/// <summary>
/// Get the status of a certain key on the keyboard.
/// </summary>
/// <param name="form"></param>
/// <param name="key"></param>
/// <returns></returns>
public static KeyStatus GetKeyStatus(ViewModelBase form, KeyboardKey key)
{
return InternalIO.glfwGetKey(form.WindowID, (int)key);
}
public IntPtr GraphicApiPackageHandle { get; }
}
}
+151 -104
View File
@@ -29,11 +29,12 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Data;
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
@@ -45,37 +46,82 @@ namespace StgSharp.Graphics
{
public class Image : ISSDSerializable, IImageProvider
{
internal byte[] data;
internal ImageInfo info;
private byte[] _data;
private ImageInfo info;
private int _pixelUpdateCount = 0;
internal Image(ImageInfo information)
{
info = information;
data = Array.Empty<byte>();
//int length = info.width * info.height * info.channel;
}
public ref byte[] DataStream
{
get => ref data;
}
public unsafe Image()
internal unsafe Image()
{
info = new ImageInfo();
}
public ImageChannel Channel => info.Channel;
public int ChannelCount => info.ChannelCount;
public int Height => info.Height;
internal Image(ImageInfo information)
{
info = information;
_data = Array.Empty<byte>();
//int length = info.width * info.height * info.channel;
}
internal ref byte[] Data
{
get => ref _data;
}
public (int width, int height) Size
{
get => (info.Width, info.Height);
}
/// <summary>
/// Hash code of time pixels updated last time.
/// </summary>
public int PixelUpdateCount
{
get => _pixelUpdateCount;
internal set => _pixelUpdateCount = value;
}
public byte[] PixelBuffer
{
get
{
if ((_data.Length == 0) || (_data == null))
{
GetBytes();
return _data!;
}
return _data;
}
}
public ImageChannel Channel => info.Channel;
public int ChannelCount => info.ChannelCount;
public int Height
{
get => info.Height;
internal set => info.Height = value;
}
public int Width
{
get => info.Width;
internal set => info.Width = value;
}
public int PixelSize => GlHelper.GetPixelSize(info.pixelLayout, info.Channel);
public PixelChannelLayout PixelLayout
{
get => info.pixelLayout;
private set => info.pixelLayout = value;
}
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.PixelImage;
public int Width => info.Width;
public void FromBytes(byte[] stream)
{
}
public static unsafe Image FromFile(string route, ImageLoader loader)
{
@@ -87,76 +133,57 @@ namespace StgSharp.Graphics
return ret;
}
public static Image FromMemory((int width, int height) size, int channelCount, byte[] stream)
public static Image FromMemory((int width, int height) size, ImageChannel channel, byte[] stream)
{
ImageInfo _info = new ImageInfo
{
Height = size.height,
Width = size.width,
ChannelCount = channelCount,
Channel = channel,
StreamPtr = IntPtr.Zero
};
Image ret = new Image(_info);
ret.data = stream;
ret.PixelLayout = PixelChannelLayout.Byte;
ret._data = stream;
return ret;
}
public glArrayHandle GetArrayHandle()
public static Image FromMemory((int width, int height) size, ImageChannel channel, PixelChannelLayout layout, byte[] stream)
{
if ((data == Array.Empty<byte>()) || (data == null))
ImageInfo _info = new ImageInfo
{
this.GetBytes();
return new glArrayHandle(data);
}
return new glArrayHandle(data);
Height = size.height,
Width = size.width,
Channel = channel,
StreamPtr = IntPtr.Zero
};
Image ret = new Image(_info);
ret.PixelLayout = layout;
ret._data = stream;
return ret;
}
public unsafe byte[] GetBytes()
{
if (data == null)
if (_data.Length == 0)
{
int size = Width * Height * ChannelCount;
data = new byte[size];
int i = 0;
fixed (byte* bptr = data)
{
byte* pptr = bptr;
for (; i < size; i += 16)
{
*(M128*)(pptr + i) = *(M128*)(info.StreamPtr + i);
}
for (; i < size; i++)
{
*(pptr + i) = *(byte*)(info.StreamPtr + i);
}
}
int size = Width * Height * GlHelper.GetPixelSize(PixelLayout, Channel);
_data = new Span<byte>((byte*)info.StreamPtr, size).ToArray();
fixed (ImageInfo* pptr = &info)
{
InternalIO.InternalUnloadImage(pptr);
}
info.StreamPtr = IntPtr.Zero;
}
return data;
return _data;
}
public Image ProvideImage() => this;
public void FromBytes(byte[] stream)
{
}
public Image ProvideImage()
byte[] ISSDSerializable.GetBytes()
{
throw new NotImplementedException();
}
~Image()
{
if (info.StreamPtr != IntPtr.Zero)
{
// Marshal.FreeHGlobal(info.StreamPtr);
}
}
}
[StructLayout(LayoutKind.Sequential)]
@@ -164,53 +191,20 @@ namespace StgSharp.Graphics
{
private ImageChannel channel;
private int channelCount;
private int height;
private int width;
private IntPtr pixelPtr;
internal PixelChannelLayout pixelLayout;
public ImageChannel Channel
{
get => channel;
set
{
channel = value;
switch (channel)
{
case ImageChannel.SingleColor:
channelCount = 1; break;
case ImageChannel.DoubleColor:
channelCount = 2; break;
case ImageChannel.FullColor:
channelCount = 3; break;
case ImageChannel.WithAlphaChannel:
channelCount = 4; break;
default:
throw new InvalidCastException("Unknown color channel decoding setting.");
}
}
set { channel = value; }
}
public int ChannelCount
{
get => channelCount;
set
{
channelCount = value;
switch (channelCount)
{
case 1:
channel = ImageChannel.SingleColor; break;
case 2:
channel = ImageChannel.DoubleColor; break;
case 3:
channel = ImageChannel.FullColor; break;
case 4:
channel = ImageChannel.WithAlphaChannel; break;
default:
throw new InvalidCastException("Unknown color channel decoding setting.");
}
}
get => GlHelper.GetChannelCount(channel);
}
public int Height
@@ -219,15 +213,9 @@ namespace StgSharp.Graphics
set => height = value;
}
public IntPtr StreamPtr
{
get => pixelPtr;
internal set => pixelPtr = value;
}
public int StreamSize
{
get => width * height * channelCount;
get => width * height * GlHelper.GetPixelSize(pixelLayout, channel);
}
public int Width
@@ -236,20 +224,79 @@ namespace StgSharp.Graphics
set => width = value;
}
public IntPtr StreamPtr
{
get => pixelPtr;
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;
return hash;
}
}
public enum ImageChannel : uint
{
SingleColor = GLconst.RED,
DoubleColor = GLconst.RG,
FullColor = GLconst.RGB,
TripleColor = GLconst.RGB,
WithAlphaChannel = GLconst.RGBA,
}
}
namespace StgSharp.Graphics.OpenGL
{
public static partial class GlHelper
{
internal static int GetChannelCount(ImageChannel channel)
{
return channel switch
{
ImageChannel.SingleColor => 1,
ImageChannel.DoubleColor => 2,
ImageChannel.TripleColor => 3,
ImageChannel.WithAlphaChannel => 4,
_ => throw new InvalidCastException("Unknown color channel decoding setting.")
};
}
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"),
};
}
}
}
@@ -0,0 +1,161 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="AutoTexture.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using StgSharp.Collections;
namespace StgSharp.Graphics.OpenGL
{
public sealed class AutoTextureGL
{
private BidirectionalDictionary<Image, int> imageIndexMap = new BidirectionalDictionary<Image, int>();
private Dictionary<Image, int> imageUpdateIndex = new Dictionary<Image, int>();
private int _size, _currentIndex;
private LinkedList<int> usedTextureIndex;
private Queue<int> unusedTextureUnitIndex;
private TextureProperty[] propertyCache;
private TextureGL texturePackage;
private TextureProperty _textureProperty;
private OpenGLFunction GL
{
get => texturePackage.GL;
}
private AutoTextureGL(TextureGL texture)
{
texturePackage = texture;
_size = texture.Count;
imageIndexMap = new BidirectionalDictionary<Image, int>();
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range(0, _size));
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
public AutoTextureGL(int textureObjectSize, [NotNull]glRenderStream binding)
{
this._size = textureObjectSize;
imageIndexMap = new BidirectionalDictionary<Image, int>();
texturePackage = new TextureGL(textureObjectSize, binding);
unusedTextureUnitIndex = new Queue<int>(
Enumerable.Range(0, _size));
usedTextureIndex = new LinkedList<int>();
propertyCache = new TextureProperty[_size];
}
public TextureProperty DefaultTextureProperty
{
get => _textureProperty;
set => _textureProperty = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SelectTextureAndBind(Image i)
{
TextureProperty property = _textureProperty;
SelectTextureAndBind(i, property);
}
public void SelectTextureAndBind([NotNull]Image i, TextureProperty property)
{
//usable texture with image match
if (imageIndexMap.TryGetValue(i, out int index))
{
//prop setting match
if (propertyCache[index] == property)
{
_currentIndex = index; //GL.Assert(true);
texturePackage.Bind2D(index); //GL.Assert(true);
if (i.PixelUpdateCount != imageUpdateIndex[i])
{
texturePackage.LoadTexture(index, i); //GL.Assert(true);
}
}
else
{
_currentIndex = index; //GL.Assert(true);
texturePackage.Bind2D(index); //GL.Assert(true);
texturePackage.Set2dProperty(index, property); //GL.Assert(true);
if (i.PixelUpdateCount != imageUpdateIndex[i])
{
texturePackage.LoadTexture(index, i); //GL.Assert(true);
}
}
}
else
{
if (unusedTextureUnitIndex.TryDequeue(out int newIndex))
{
//has extra unused texture object
imageIndexMap.Add(i, index);
texturePackage.Bind2D(index);
texturePackage.Set2dProperty(index, property);
texturePackage.LoadTexture(index, i);
usedTextureIndex.AddLast(newIndex);
propertyCache[newIndex] = property;
imageUpdateIndex[i] = i.PixelUpdateCount;
}
else
{
//recycle from current
int reusedIndex = usedTextureIndex.First!.Value;
usedTextureIndex.RemoveFirst();
usedTextureIndex.AddLast(reusedIndex);
imageIndexMap[i] = reusedIndex;
propertyCache[newIndex] = property;
imageUpdateIndex[i] = i.PixelUpdateCount;
}
}
}
public static AutoTextureGL ToAuto([NotNull]TextureGL texture)
{
if (texture.IndexOfCurrentTexture != -1)
{
throw new InvalidOperationException("Texture to be converted has been editted.");
}
return new AutoTextureGL(texture);
}
}
}
@@ -28,6 +28,8 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Graphics.OpenGL;
using StgSharp.Math;
using System;
@@ -36,47 +38,45 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics.GL
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.
/// </summary>
public unsafe class ElementBuffer : BufferObjectBase
public sealed unsafe class ElementBuffer : GlBufferObjectBase
{
internal ElementBuffer(int n, glRenderStream binding)
internal ElementBuffer(int n, glRenderStream binding) : base(binding)
{
this.binding = binding;
_bufferHandle = glFunc.GenBuffers(n);
_bufferHandle = GL.GenBuffers(n);
}
public override sealed void Bind(int index)
{
glFunc.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
{
glFunc.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
glFunc.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
{
glFunc.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
glFunc.SetBufferData(BufferType.ElementArrayBuffer, bufferSpan, usage);
GL.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ElementArrayBuffer, bufferSpan, usage);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
{
glFunc.DeleteBuffers(_bufferHandle);
_bufferHandle.Release();
GL.DeleteBuffers(_bufferHandle);
}
}
@@ -0,0 +1,97 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="FBO.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
#pragma warning disable CA1008
#pragma warning disable CA1028
public enum FrameBufferTarget : uint
#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, glRenderStream binding) : base(binding)
{
_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.
/// </summary>
/// <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]);
}
/// <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.
/// </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)
{
GL.BindFrameBuffer(target, _bufferHandle[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindNull()
{
OpenGLFunction.CurrentGL.BindFrameBuffer(FrameBufferTarget.All, GlHandle.Zero);
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,53 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLBufferObjectBase.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public abstract class GlBufferObjectBase : BufferObjectBase
{
private readonly glRenderStream _contextBinding;
protected GlBufferObjectBase(glRenderStream contextBinding)
{
binding = contextBinding;
_contextBinding = contextBinding;
}
protected OpenGLFunction GL => _contextBinding.GL;
}
}
@@ -0,0 +1,71 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="RBO.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Security.Principal;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public sealed class RenderBuffer : GlBufferObjectBase
{
public RenderBuffer(int count, glRenderStream binding) : base(binding)
{
_bufferHandle = GL.GenRenderBuffer(count);
}
public override void Bind(int index)
{
GL.BindRenderBuffer(this[index]);
}
public void Store(RenderBufferInternalFormat format, (int width, int height) size)
{
if ((size.width > binding.Width) || (size.height > binding.Height))
{
StgSharp.LogWarning("FrameBuffer is larger than current canvas binding");
}
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,285 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TextureGL.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;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
public sealed unsafe class TextureGL
{
private int currentEditingTextureIndex;
private OpenGLFunction _gl;
internal GlHandle[] _textureHandle;
internal TextureGL( int count, glRenderStream binding )
{
//sourceList = new Image[count];
this._gl = binding.GL;
_textureHandle = _gl.GenTextures( count );
}
internal OpenGLFunction GL => _gl;
public GlHandle this[ int index ]
{
get => _textureHandle[ index ];
}
public int Count
{
get => _textureHandle.Length;
}
//internal Image[] sourceList;
public int IndexOfCurrentTexture
{
get => currentEditingTextureIndex;
}
public void ActivateAs( TextureUnit unit ) { _gl.ActiveTextureUnit( ( uint )unit ); }
public void Bind2D( int index )
{
currentEditingTextureIndex = index;
_gl.BindTexture( GLconst.TEXTURE_2D, _textureHandle[ index ] );
}
/// <summary>
/// Load an <see cref="Image" /> to certain texture.
/// </summary>
/// <param name="index"> </param>
/// <param name="i"> </param>
public unsafe void LoadTexture( int index, Image i )
{
byte[] handle = i.PixelBuffer;
_gl.TextureImage2d(
Texture2DTarget.Texture2D, 0, ( uint )i.Channel, ( uint )i.Width, ( uint )i.Height,
( uint )i.Channel, i.PixelLayout, pixels: handle );
_gl.GenerateMipmap( Texture2DTarget.Texture2D );
}
#region texture setting
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dFilterProperty(
int index,
TextureFilter onMinify,
TextureFilter onMagnify )
{
#if DEBUG
if( index != currentEditingTextureIndex )
{
throw new InvalidOperationException(
"Texture to be editted is not the one being activated." );
}
#endif
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_MIN_FILTER, ( int )onMinify );
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_MAG_FILTER, ( int )onMagnify );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dWrapProperty(
int index,
TextureWrap onHorizontial,
TextureWrap onVertical )
{
#if DEBUG
if( index != currentEditingTextureIndex )
{
throw new InvalidOperationException(
"Texture to be editted is not the one being activated." );
}
#endif
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_S, ( int )onHorizontial );
_gl.TextureParameter( GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_T, ( int )onVertical );
}
[MethodImpl( MethodImplOptions.AggressiveInlining )]
public void Set2dProperty( int index, TextureProperty property )
{
Set2dFilterProperty( index, property.FilterOnMinify, property.FilterOnMagnify );
Set2dWrapProperty( index, property.WrapOnHorizontial, property.WrapOnVertical );
}
#endregion texture setting
}
[StructLayout( LayoutKind.Explicit )]
public struct TextureProperty
{
[FieldOffset( 0 )] private M128 mask;
[FieldOffset( 0 )] private TextureFilter mag;
[FieldOffset( 4 )] private TextureFilter min;
[FieldOffset( 8 )] private TextureWrap hori;
[FieldOffset( 12 )] private TextureWrap vert;
public TextureProperty(
TextureFilter onMagnify,
TextureFilter onMinify,
TextureWrap onHorizontial,
TextureWrap onVertical )
{
FilterOnMagnify = onMagnify;
FilterOnMinify = onMinify;
WrapOnHorizontial = onHorizontial;
WrapOnVertical = onVertical;
}
public TextureFilter FilterOnMagnify
{
get => mag;
set => mag = value;
}
public TextureFilter FilterOnMinify
{
get => min;
set => min = value;
}
public TextureWrap WrapOnHorizontial
{
get => hori;
set => hori = value;
}
public TextureWrap WrapOnVertical
{
get => vert;
set => vert = value;
}
public override int GetHashCode()
{
return HashCode.Combine(
FilterOnMagnify, FilterOnMagnify, WrapOnHorizontial, WrapOnVertical );
}
public override bool Equals([NotNullWhen(true)] object obj)
{
return base.Equals(obj);
}
public override string ToString()
{
return $"FilterOnMagnify:{FilterOnMagnify}, " +
$"FilterOnMagnify:{FilterOnMagnify}, " +
$"WrapOnHorizontial:{WrapOnHorizontial}, " +
$"WrapOnVertical:{WrapOnVertical}";
}
public static implicit operator TextureProperty(
(
TextureFilter onMagnify, TextureFilter onMinify,
TextureWrap onHorizontial, TextureWrap onVertical
) propertyValueTuple )
{
return new TextureProperty(
propertyValueTuple.onMagnify, propertyValueTuple.onMinify,
propertyValueTuple.onHorizontial, propertyValueTuple.onVertical );
}
public static bool operator ==(TextureProperty left, TextureProperty right)
{
return left.mask == right.mask;
}
public static bool operator !=(TextureProperty left, TextureProperty right)
{
return left.mask != right.mask;
}
}
#pragma warning disable CA1008
public enum TextureFilter
#pragma warning restore CA1008
{
Nearest = GLconst.NEAREST,
Linear = GLconst.LINEAR,
NearestLinearMipmap = GLconst.NEAREST_MIPMAP_LINEAR,
LinearLinearMipmap = GLconst.LINEAR_MIPMAP_LINEAR,
NearestNearestMipmap = GLconst.NEAREST_MIPMAP_NEAREST,
LinearNearestMipmap = GLconst.LINEAR_MIPMAP_NEAREST,
}
#pragma warning disable CA1008
public enum TextureUnit
#pragma warning restore CA1008
{
Unit0 = GLconst.TEXTURE0,
Unit1 = GLconst.TEXTURE1,
Unit2 = GLconst.TEXTURE2,
Unit3 = GLconst.TEXTURE3,
Unit4 = GLconst.TEXTURE4,
Unit5 = GLconst.TEXTURE5,
Unit6 = GLconst.TEXTURE6,
Unit7 = GLconst.TEXTURE7,
Unit8 = GLconst.TEXTURE8,
Unit9 = GLconst.TEXTURE9,
Unit10 = GLconst.TEXTURE10,
Unit11 = GLconst.TEXTURE11,
Unit12 = GLconst.TEXTURE12,
Unit13 = GLconst.TEXTURE13,
Unit14 = GLconst.TEXTURE14,
Unit15 = GLconst.TEXTURE15,
}
#pragma warning disable CA1008
public enum TextureWrap
#pragma warning restore CA1008
{
Repeat = GLconst.REPEAT,
MirroredRepeat = GLconst.MIRRORED_REPEAT,
ClampToEdge = GLconst.CLAMP_TO_EDGE,
ClampToBorder = GLconst.CLAMP_TO_BORDER,
}
}
@@ -35,33 +35,32 @@ using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics.OpenGL
{
public unsafe class VertexArray : BufferObjectBase
public sealed unsafe class VertexArray : GlBufferObjectBase
{
internal VertexArray(int n, glRenderStream binding)
internal VertexArray(int n, glRenderStream binding) : base(binding)
{
this.binding = binding;
_bufferHandle = glFunc.GenVertexArrays(n);
_bufferHandle = GL.GenVertexArrays(n);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override sealed void Bind(int index)
{
glFunc.BindVertexArray(_bufferHandle[index]);
GL.BindVertexArray(_bufferHandle[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindNull()
{
glFunc.BindVertexArray(glHandle.Zero);
OpenGLFunction.CurrentGL.BindVertexArray(GlHandle.Zero);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SetVertexAttribute(uint index, int vertexLength, TypeCode dataType, bool isNomalized, uint stride, int pointer)
public void SetVertexAttribute(uint index, int vertexLength, TypeCode dataType, bool isNomalized, uint stride, int pointer)
{
glFunc.SetVertexAttribute(
GL.SetVertexAttribute(
index, vertexLength, dataType,
isNomalized,
stride, pointer);
@@ -71,8 +70,7 @@ namespace StgSharp.Graphics.GL
{
if (disposing)
{
glFunc.DeleteVertexArrays(_bufferHandle);
_bufferHandle.Release();
GL.DeleteVertexArrays(_bufferHandle);
}
}
@@ -28,7 +28,6 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.GL;
using StgSharp.Math;
using System;
@@ -39,98 +38,19 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics.OpenGL
{
public unsafe class VertexBuffer : BufferObjectBase
public sealed unsafe class VertexBuffer : GlBufferObjectBase
{
internal VertexBuffer(int n, glRenderStream binding)
internal VertexBuffer(int n, glRenderStream binding) : base(binding)
{
this.binding = binding;
_bufferHandle = glFunc.GenBuffers(n);
_bufferHandle = GL.GenBuffers(n);
}
public override sealed void Bind(int index)
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
}
/// <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
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
glFunc.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,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
glFunc.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,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
glFunc.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
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
glFunc.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
{
glFunc.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
glFunc.SetBufferVectorData(BufferType.ArrayBuffer, vectorArray, usage);
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
}
/// <summary>
@@ -139,15 +59,92 @@ namespace StgSharp.Graphics.GL
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Unbind()
{
glFunc.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
{
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,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
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,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
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
{
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
{
GL.BindBuffer(BufferType.ArrayBuffer, _bufferHandle[index]);
GL.SetBufferVectorData(BufferType.ArrayBuffer, vectorArray, usage);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
{
glFunc.DeleteBuffers(_bufferHandle);
_bufferHandle.Release();
GL.DeleteBuffers(_bufferHandle);
}
}
@@ -0,0 +1,75 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GlHandle.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.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
#if Windows
using Microsoft.Win32.SafeHandles;
#endif
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
[StructLayout(LayoutKind.Explicit, Size = 4)]
public struct GlHandle
{
[FieldOffset(0)] public int SignedValue;
[FieldOffset(0)] public uint Value;
public static GlHandle Zero
{
get => new GlHandle { Value = 0 };
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GlHandle Alloc(uint value)
{
return new GlHandle { Value = value };
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GlHandle SignedAlloc(int value)
{
return new GlHandle { SignedValue = value };
}
}
}
@@ -0,0 +1,65 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IglConvertable.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.ShaderEdit
{
public interface IglConvertable
{
/// <summary>
///
/// </summary>
public void DisplayGLtypeDefinition();
/// <summary>
///
/// </summary>
public void GainAllUniforms(ShaderProgram source, params string[] uniformName);
/// <summary>
///
/// </summary>
/// <returns></returns>
public ShaderStruct GetConvertedGLtype();
/// <summary>
///
/// </summary>
public void SetAllUniforms();
}
}
@@ -39,43 +39,45 @@ using System.Runtime.InteropServices;
using System.Text;
using System.Xml.Linq;
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics.OpenGL
{
public abstract partial class glRenderStream : RenderStream
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected sealed override Shader CreateShaderSegment(ShaderType type, int count)
{
return new Shader( glFunc.CreateShaderSet(count, type), type);
}
/// <summary>
/// Create an instance of <see cref="Shader"/> program
/// </summary>
/// <returns>New instance of <see cref="Shader"/> instance. </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected sealed override ShaderProgram CreateShaderProgram()
protected override sealed ShaderProgram CreateShaderProgram()
{
return new ShaderProgram(this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override sealed Shader CreateShaderSegment(ShaderType type, int count)
{
return new Shader(GL.CreateShaderSet(count, type), type, this);
}
}
public class Shader : ISSDSerializable
{
private readonly IntPtr context;
internal readonly glHandleSet handle;
private readonly OpenGLFunction GL;
internal readonly GlHandle[] handle;
public readonly ShaderType type;
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.Shader;
internal unsafe Shader(glHandleSet handle, ShaderType usage)
internal unsafe Shader(GlHandle[] handle, ShaderType usage, glRenderStream stream)
{
this.handle = handle;
context = glFunc.CurrentContextHandle;
GL = stream.GL;
type = usage;
}
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.Shader;
/// <summary>
/// Attach one shader code to a shader program.
/// </summary>
@@ -84,7 +86,45 @@ namespace StgSharp.Graphics.GL
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AttachTo(int index, ShaderProgram target)
{
glFunc.AttachShader(target.handle, handle[index]);
GL.AttachShader(target.handle, handle[index]);
}
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}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Compile(int index, byte[] codeStream)
{
if (codeStream == null)
{
throw new ArgumentNullException(nameof(codeStream));
}
GL.LoadShaderSource(handle[index], codeStream);
GL.CompileShader(handle[index]);
CheckStatus(index, ShaderStatus.CompileStatus);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Compile(int index, string 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);
}
public void FromBytes(byte[] stream)
{
throw new NotImplementedException();
}
public static byte[] FromCodeFile(string fileRoute)
@@ -97,58 +137,21 @@ namespace StgSharp.Graphics.GL
return Encoding.UTF8.GetBytes(str);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Compile(int index, byte[] codeStream)
{
if (codeStream == null)
{
throw new ArgumentNullException(nameof(codeStream));
}
glFunc.LoadShaderSource(handle[index], codeStream);
glFunc.CompileShader(handle[index]);
CheckStatus(index,ShaderStatus.CompileStatus);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Compile(int index, string codeStream)
{
if (codeStream == null)
{
throw new ArgumentNullException(nameof(codeStream));
}
glFunc.LoadShaderSource(handle[index],Encoding.ASCII.GetBytes( codeStream));
glFunc.CompileShader(handle[index]);
CheckStatus(index, ShaderStatus.CompileStatus);
}
public override string ToString()
{
return $"This is a {type} shader, its shader handles are {handle.ToString()}.";
}
public byte[] GetBytes()
{
return Array.Empty<byte>();
}
public void CheckStatus(int index, ShaderStatus status)
{
string log = glFunc.GetShaderStatus(this,index, (int)status);
if (!string.IsNullOrEmpty(log))
{
throw new Exception($"Shader Error \t{status}\n" + log);
}
}
public byte[] GetBytes(out int length)
{
throw new NotImplementedException();
}
public void FromBytes(byte[] stream)
public override string ToString()
{
throw new NotImplementedException();
return $"This is a {type} shader, its shader handles are {handle.ToString()}.";
}
}
public enum ShaderStatus : int
@@ -158,16 +161,17 @@ namespace StgSharp.Graphics.GL
public class ShaderProgram
{
private readonly IntPtr binding;
internal readonly glHandle handle;
private readonly OpenGLFunction GL;
internal readonly GlHandle handle;
/// <summary>
/// Init a program with no shader attached.
/// CustomizeInit a program with no shader attached.
/// </summary>
internal unsafe ShaderProgram(glRenderStream binding)
{
this.binding = binding.ContextHandle;
handle = glFunc.CreateProgram();
GL = binding.GL;
handle = GL.CreateProgram();
}
/// <summary>
@@ -179,7 +183,7 @@ namespace StgSharp.Graphics.GL
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Uniform<T> GetUniform<T>(string name) where T : struct
{
return new Uniform<T>(this, name, binding);
return new Uniform<T>(GL.GetUniformLocation(this.handle, name));
}
/// <summary>
@@ -192,7 +196,7 @@ namespace StgSharp.Graphics.GL
where T : struct
where U : struct
{
return new Uniform<T, U>(this, name, binding);
return new Uniform<T, U>(GL.GetUniformLocation(this.handle, name));
}
/// <summary>
@@ -206,8 +210,9 @@ namespace StgSharp.Graphics.GL
where U : struct
where V : struct
{
return new Uniform<T, U, V>(this, 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.
@@ -220,15 +225,15 @@ namespace StgSharp.Graphics.GL
where V : struct
where W : struct
{
return new Uniform<T, U, V, W>(this, name);
return new Uniform<T, U, V, W>(GL.GetUniformLocation(this.handle, name));
}
/// <summary>
/// Link the shader to current context.
/// Link the shader to current viewPortDisplay.
/// </summary>
public unsafe void Link()
{
if (InternalIO.InternalLinkShaderProgram((GLcontext*)this.binding, handle.Value) == 0)
if (InternalIO.InternalLinkShaderProgram((OpenglContext*)this.GL.ContextHandle, handle.Value) == 0)
{
IntPtr logPtr = InternalIO.InternalReadSSCLog();
try
@@ -247,12 +252,12 @@ namespace StgSharp.Graphics.GL
}
/// <summary>
/// Let the current context use this shader.
/// Let the current viewPortDisplay use this shader.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Use()
{
glFunc.UseProgram(handle);
GL.UseProgram(handle);
}
~ShaderProgram()
@@ -0,0 +1,206 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Uniform.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.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public class Uniform
{
internal GlHandle id;
public GlHandle Handle
{
get => id;
}
}
public sealed class Uniform<T> : Uniform
where T : struct
{
internal Uniform()
{
}
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
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
{
internal Uniform()
{
}
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal static Uniform<T, U> FromHandle(GlHandle handle)
{
return new Uniform<T, U> { id = handle };
}
}
public sealed class Uniform<T, U, V> : Uniform
where T : struct
where U : struct
where V : struct
{
internal Uniform()
{
}
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal static Uniform<T, U, V> FromHandle(GlHandle handle)
{
return new Uniform<T, U, V> { id = handle };
}
}
public sealed class Uniform<T, U, V, W> : Uniform
where T : struct
where U : struct
where V : struct
where W : struct
{
internal Uniform()
{
}
internal unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal static Uniform<T, U, V, W> FromHandle(GlHandle handle)
{
return new Uniform<T, U, V, W> { id = handle };
}
}
public unsafe partial class OpenGLFunction
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue
(Uniform<Matrix44> uniform, Matrix44 mat)
{
Matrix44 temp = mat;
Context.glUniformMatrix4fv(uniform.id.SignedValue, 1, false, (float*)&temp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float, float, float, float> uniform, vec4d vec)
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.SignedValue, 4, &temp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<vec4d> uniform, vec4d vec)
{
vec4d temp = vec;
Context.glUniform1fv(uniform.id.SignedValue, 4, &temp);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float> uniform, float v0)
{
Context.glUniform1f(uniform.id.SignedValue, v0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<int> uniform, int i0)
{
Context.glUniform1i(uniform.id.SignedValue, i0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetUniformValue(Uniform<float, float> uniform, float v0, float v1)
{
Context.glUniform2f(uniform.id.SignedValue, v0, v1);
}
[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);
}
[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);
}
}
}
@@ -0,0 +1,47 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glAPICalling.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class OpenGLAPICallingAttribute : Attribute
{
public OpenGLAPICallingAttribute()
{
}
}
}
@@ -29,6 +29,9 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Math;
using StgSharp.MVVM;
using StgSharp.MVVM.View;
using System;
using System.Collections.Generic;
@@ -37,7 +40,7 @@ using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics.OpenGL
{
public static partial class glManager
{
@@ -45,8 +48,7 @@ namespace StgSharp.Graphics.GL
private const int glExtension = 0x1f03;
private const int glVersion = 0x1f02;
private static readonly string[] glBranch =
new string[] {
private static readonly string[] glBranch = {
"OpenGL ES-CM ",
"OpenGL ES-CL ",
"OpenGL ES ",
@@ -55,17 +57,34 @@ namespace StgSharp.Graphics.GL
private static string glExtensionList;
//--------------------------------------------------------------------------------
/// <summary>
/// Load all supported OpenGL APIs and bind them to given <see cref="ViewPort"/> context.
/// Get the function pointer of given OpenGL api name
/// </summary>
/// <param name="vp">The <see cref="ViewPort"/> used as current OpenGL context</param>
public static unsafe void LoadGLapi(this ViewPort vp)
/// <param name="name">ContextName of the OpenGL api</param>
/// <returns>The funtion pointer of the api in stream of <see cref="IntPtr"/></returns>
public static IntPtr LoadGLfunc(string name)
{
GLcontext* context = (GLcontext*)vp.GraphicHandle;
delegate*<string,IntPtr> loader = &InternalIO.glfwGetProcAddress;
#pragma warning disable CS8909
if (context->glGetString != (delegate*<uint, IntPtr>)IntPtr.Zero)
#pragma warning restore CS8909
IntPtr ret = InternalIO.glfwGetProcAddress(name);
if (ret == default)
{
InternalIO.InternalAppendLog(
$"Cannot load OpenGL api called {name}, this api may not exist or supported.");
return ret;
}
return ret;
}
/// <summary>
/// Load all supported OpenGL APIs and bind them to given <see cref="ViewPort"/>.
/// </summary>
/// <param name="contextHandle">The handle to current OpenGL viewPortDisplay</param>
public static unsafe void LoadOpenGLApiTo(IntPtr contextHandle)
{
OpenglContext* context = (OpenglContext*)contextHandle;
delegate*<string, IntPtr> loader = &InternalIO.glfwGetProcAddress;
if ((IntPtr)context->glGetString != IntPtr.Zero)
{
return;
}
@@ -73,7 +92,7 @@ namespace StgSharp.Graphics.GL
if (proc == IntPtr.Zero)
{
#if DEBUG
Console.WriteLine("Cannot load glFunc.");
Console.WriteLine("Cannot load GL.");
#endif
throw new Exception("Cannot load gl");
}
@@ -84,7 +103,7 @@ namespace StgSharp.Graphics.GL
{
InternalIO.InternalWriteLog("Failed to call glGetString", LogType.Error);
}
coreVersion = Marshal.PtrToStringAnsi(context->glGetString(glVersion));
coreVersion = Marshal.PtrToStringAnsi(context->glGetString(glVersion)) ?? string.Empty;
foreach (string branch in glBranch)
{
@@ -132,20 +151,31 @@ namespace StgSharp.Graphics.GL
}
}
IntPtr strPtr = context->glGetString(glExtension);
string extension;
if (strPtr == IntPtr.Zero)
uint code = context->glGetError();
Console.WriteLine(code);
if (code != 0)
{
throw new GlExecutionException(code);
}
int extensionCount;
context->glGetIntegerv(GLconst.NUM_EXTENSIONS, &extensionCount);
if (extensionCount == 0)
{
InternalIO.InternalWriteLog("No supported OpenGL extensions are found.", LogType.Info);
return;
}
else
List<string> extensions = new List<string>();
for (uint i = 0; i < extensionCount; i++)
{
extension = Marshal.PtrToStringAnsi(strPtr);
byte* strPtr = context->glGetStringi(GLconst.EXTENSIONS, i);
extensions.Add(Marshal.PtrToStringAnsi((IntPtr)strPtr));
}
List<string> extensions =
extension.Split(" ").ToList();
InternalIO.InternalWriteLog($"{$"Find OpenGL extensions:"}{Environment.NewLine}{($"{string.Join(';', extensions)}")}",
LogType.Info);
#region checkGLextensions
@@ -771,28 +801,16 @@ namespace StgSharp.Graphics.GL
#endregion checkGLextensions
InternalIO.InternalWriteLog("Find OpenGL extensions.", LogType.Info);
}
/// <summary>
/// Get the function pointer of given OpenGL api name
/// </summary>
/// <param name="name">ContextName of the OpenGL api</param>
/// <returns>The funtion pointer of the api in stream of <see cref="IntPtr"/></returns>
public static IntPtr LoadGLfunc(string name)
{
IntPtr ret = InternalIO.glfwGetProcAddress(name);
if (ret == default)
{
InternalIO.InternalAppendLog(
$"Cannot load OpenGL api called {name}, this api may not exist or supported.");
return ret;
}
return ret;
}
internal static void CheckCoreVersion(int majorVersion, int minorVersion)
{
if (majorVersion < 3)
{
throw new InvalidOperationException("StgSharp does not support OpenGL immediate mode.");
}
if ((majorVersion >= 1) || ((majorVersion == 1) && (minorVersion == 0)))
{
core10 = true;
@@ -971,7 +989,7 @@ namespace StgSharp.Graphics.GL
}
}
internal static unsafe string GetExtensions(this GLcontext context)
internal static unsafe string GetExtensions(this OpenglContext context)
{
if (context.glGetString == null)
{
@@ -998,7 +1016,7 @@ namespace StgSharp.Graphics.GL
}
}
internal static unsafe void LoadGLcore10(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore10(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core10)
{
@@ -1062,7 +1080,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.0 APIs");
}
internal static unsafe void LoadGLcore11(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore11(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core11)
{
@@ -1092,7 +1110,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.1 APIs");
}
internal static unsafe void LoadGLcore12(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore12(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core12)
{
@@ -1112,7 +1130,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.2 APIs");
}
internal static unsafe void LoadGLcore13(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore13(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core13)
{
@@ -1137,7 +1155,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.3 APIs");
}
internal static unsafe void LoadGLcore14(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore14(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core14)
{
@@ -1162,7 +1180,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.4 APIs");
}
internal static unsafe void LoadGLcore15(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore15(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core15)
{
@@ -1197,7 +1215,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 1.5 APIs");
}
internal static unsafe void LoadGLcore20(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore20(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core20)
{
@@ -1306,7 +1324,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 2.0 APIs");
}
internal static unsafe void LoadGLcore21(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore21(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core21)
{
@@ -1328,7 +1346,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 2.1 APIs");
}
internal static unsafe void LoadGLcore30(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore30(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core30)
{
@@ -1428,7 +1446,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.0 APIs");
}
internal static unsafe void LoadGLcore31(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore31(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core31)
{
@@ -1459,7 +1477,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.1 APIs");
}
internal static unsafe void LoadGLcore32(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore32(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core32)
{
@@ -1494,7 +1512,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.2 APIs");
}
internal static unsafe void LoadGLcore33(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore33(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core33)
{
@@ -1538,7 +1556,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 3.3 APIs");
}
internal static unsafe void LoadGLcore40(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore40(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core40)
{
@@ -1600,7 +1618,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.0 APIs");
}
internal static unsafe void LoadGLcore41(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore41(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core41)
{
@@ -1704,7 +1722,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.1 APIs");
}
internal static unsafe void LoadGLcore42(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore42(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core42)
{
@@ -1732,7 +1750,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.2 APIs");
}
internal static unsafe void LoadGLcore43(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore43(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core43)
{
@@ -1792,7 +1810,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.3 APIs");
}
internal static unsafe void LoadGLcore44(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore44(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core44)
{
@@ -1817,7 +1835,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.4 APIs");
}
internal static unsafe void LoadGLcore45(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore45(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core45)
{
@@ -1943,7 +1961,7 @@ namespace StgSharp.Graphics.GL
InternalIO.InternalAppendLog("Successfully load all OpenGL 4.5 APIs");
}
internal static unsafe void LoadGLcore46(GLcontext* contextPtr, delegate*<string, IntPtr> load)
internal static unsafe void LoadGLcore46(OpenglContext* contextPtr, delegate*<string, IntPtr> load)
{
if (!core46)
{
@@ -32,7 +32,7 @@ using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics.OpenGL
{
public static partial class glManager
{
@@ -0,0 +1,104 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glException.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public sealed class GlExecutionException : Exception
{
public GlExecutionException()
{
}
public GlExecutionException(uint errorCode) : base($"Critical OpenGL error: {errorCode}")
{
}
}
public sealed class GlArrayFormatException : Exception
{
internal GlArrayFormatException(string message) : base(message)
{
}
internal GlArrayFormatException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
internal GlArrayFormatException(string message, Exception innerException) : base(message, innerException)
{
}
public GlArrayFormatException(PixelChannelLayout layout, string arrayname) :
base($"{arrayname} cannot be used as layout of {layout}")
{
}
}
public static partial class GlHelper
{
public static bool CheckArrayFormat(this Array array, PixelChannelLayout layout)
{
return layout switch
{
PixelChannelLayout.Byte or PixelChannelLayout.UByte332 or PixelChannelLayout.UByte233Rev
=> (array is byte[]) || (array is sbyte[]),
PixelChannelLayout.Short => array is short[],
PixelChannelLayout.UShort => array is ushort[],
PixelChannelLayout.Int => array is int[],
PixelChannelLayout.Float => array is float[],
PixelChannelLayout.UShort4444 => (array is ushort[]) || (array is byte[]),
PixelChannelLayout.UByte => (array is byte[]) || (array is sbyte[]),
PixelChannelLayout.UInt => array is uint[],
PixelChannelLayout.UShort565 or
PixelChannelLayout.UShort565Rev or
PixelChannelLayout.UShort4444Rev or
PixelChannelLayout.UShort5551 or
PixelChannelLayout.UShort1555Rev => array is ushort[],
PixelChannelLayout.UInt8888Rev or
PixelChannelLayout.UInt1010102 or
PixelChannelLayout.UInt2101010Rev => array is int[],
PixelChannelLayout.UInt8888 => array is uint[] or byte[],
_ => false,
};
}
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLpack.cs"
// file="glFunction.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -29,13 +29,15 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharp.Math;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Text;
@@ -47,193 +49,174 @@ namespace StgSharp
[DllImport(SSC_libName, EntryPoint = "glCheckShaderStat",
CallingConvention = CallingConvention.Cdecl)]
#pragma warning disable CA5392
internal static extern int glCheckShaderStatus(ref GLcontext context, uint shaderHandle, int key, ref IntPtr logPtr);
internal static extern int glCheckShaderStatus(ref OpenglContext context, uint shaderHandle, int key, ref IntPtr logPtr);
#pragma warning restore CA5392
}
}
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics.OpenGL
{
internal static unsafe partial class glFunc
public unsafe partial class OpenGLFunction
{
private static GLcontext* context;
private static Dictionary<IntPtr, OpenGLFunction> contextToGLMap = new Dictionary<IntPtr, OpenGLFunction>();
private OpenglContext* _context;
public static IntPtr CurrentContextHandle
private OpenGLFunction()
{
get { return (IntPtr)context; }
set { context = (GLcontext*)value; }
textureUnitCountGetter = new Lazy<int>(() => GetMaskInteger(GLconst.MAX_TEXTURE_IMAGE_UNITS));
unusedTextureImageUintInitilizing = new Lazy<ConcurrentQueue<TextureUnit>>(InitializeUnusedTextureImageUint);
}
private static ref GLcontext Context
internal IntPtr ContextHandle => (IntPtr)_context;
internal static OpenGLFunction CurrentGL { get; set; }
protected ref OpenglContext Context
{
get
{
#if DEBUG
if ((IntPtr)context==IntPtr.Zero)
if ((IntPtr)_context == IntPtr.Zero)
{
throw new NullReferenceException();
}
#endif
return ref (*context);
return ref (*_context);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ActiveTexture(uint type)
public void ActiveTextureUnit(uint type)
{
Context.glActiveTexture(type);
}
[Conditional("DEBUG")]
public void Assert(bool shouldReportWhenNormal)
{
try
{
uint code = Context.glGetError();
if (code != GLconst.NO_ERROR)
{
throw new GlExecutionException(code);
}
if (shouldReportWhenNormal)
{
Console.WriteLine("OpenGL runs normally");
}
}
catch (GlExecutionException ex)
{
throw ex;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AttachShader(glHandle program, glHandle shader)
public void AttachShader(GlHandle program, GlHandle shader)
{
Context.glAttachShader(program.Value, shader.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindBuffer(BufferType bufferType, glHandle handle)
public void BindBuffer(BufferType bufferType, GlHandle handle)
{
Context.glBindBuffer((uint)bufferType, handle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void GetTextureImage<T>(Texture2DTarget target, int level, ImageChannel channel, ImageChannelLayout channelLayout, ref T[] dataStream)where T: struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
#pragma warning disable CS8500
fixed (T* tptr = dataStream)
{
Context.glGetTexImage((uint)target, level, (uint)channel, (uint)channelLayout, tptr);
}
#pragma warning restore CS8500
}
/// <summary>
/// Bind a frame buffer to a frame buffer target
/// Same function as <see href="https://docs.gl/gl3/glBindFramebuffer">glBindFramebuffer</see>.
/// Same function as <see href="https://docs._gl/gl3/glBindFramebuffer">glBindFramebuffer</see>.
/// </summary>
/// <param name="target"> The frame buffer target of the binding operation.</param>
/// <param name="handle"> The handle of the frame buffer object to bind.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindFrameBuffer(FrameBufferTarget target, glHandle handle)
public void BindFrameBuffer(FrameBufferTarget target, GlHandle handle)
{
Context.glBindFramebuffer((uint)target, handle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindRenderBuffer(glHandle handle)
public void BindRenderBuffer(GlHandle handle)
{
Context.glBindRenderbuffer(GLconst.RENDERBUFFER, handle.Value);
}
public static void WaitAccomplishment()
{
Context.glFinish();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindTexture(uint type, glHandle texture)
public void BindTexture(uint type, GlHandle texture)
{
Context.glBindTexture(type, texture.Value);
}
public static unsafe int GetMaskInteger(uint statusCode)
{
int ret = 0;
Context.glGetIntegerv(statusCode,&ret);
return ret;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindVertexArray(glHandle handle)
public void BindVertexArray(GlHandle handle)
{
Context.glBindVertexArray(handle.Value);
}
public static void RereadImage(
this Image i, (int X, int Y) beginPosition, FrameBufferChannel format, ImageChannelLayout dataType)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public FrameBufferStatus CheckFrameBufferStatus(FrameBufferTarget target)
{
glArrayHandle handle = i.GetArrayHandle();
Context.glReadPixels(
beginPosition.X, beginPosition.Y, i.Width, i.Height, (uint)format, (uint)dataType, (byte*)handle.AddressOfArray()
);
return (FrameBufferStatus)Context.glCheckFramebufferStatus((uint)target);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void FrameBufferTexture2d(FrameBufferTarget target, uint attachment, Texture2DTarget texTarget,glHandle textureHandle ,int level)
{
Context.glFramebufferTexture2D(
(uint)target, attachment, (uint)texTarget,textureHandle.Value, level
);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ReadPixels(
(int X, int Y) beginPosition, (int width, int height) size, FrameBufferChannel format, ImageChannelLayout dataType, ref byte[] stream
)
{
fixed (byte* bptr = stream)
{
Context.glReadPixels(
beginPosition.X, beginPosition.Y,
size.width, size.height, (uint)format, (uint)dataType, bptr);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Clear(MaskBufferBit mask)
public void Clear(MaskBufferBit mask)
{
Context.glClear((uint)mask);
}
public static void CombineFrameBufferRenderBuffer(glHandle fboHandle, glHandle rboHandle)
{
Context.glFramebufferRenderbuffer(GLconst.FRAMEBUFFER,fboHandle.Value,GLconst.RENDERBUFFER, rboHandle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void ClearColor(float R, float G, float B, float A)
public unsafe void ClearColor(float R, float G, float B, float A)
{
Context.glClearColor(R, G, B, A);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void ClearGraphicError()
public void ClearError()
{
while (Context.glGetError() != 0) { }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void CompileShader(glHandle shaderhandle)
public unsafe void ClearGraphicError()
{
while (Context.glGetError() != 0) { }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CombineFrameBufferRenderBuffer(FrameBufferAttachment attachment, GlHandle rboHandle)
{
Context.glFramebufferRenderbuffer(GLconst.FRAMEBUFFER, (uint)attachment, GLconst.RENDERBUFFER, rboHandle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CompileShader(GlHandle shaderhandle)
{
Context.glCompileShader(shaderhandle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glHandle CreateGraphicProgram()
public unsafe GlHandle CreateGraphicProgram()
{
return glHandle.Alloc(Context.glCreateProgram());
return GlHandle.Alloc(Context.glCreateProgram());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glHandle CreateProgram()
public GlHandle CreateProgram()
{
return glHandle.Alloc(Context.glCreateProgram());
return GlHandle.Alloc(Context.glCreateProgram());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glHandleSet CreateProgram(int count)
public unsafe GlHandle[] CreateProgram(int count)
{
glHandleSet h = new glHandleSet(count);
GlHandle[] h = new GlHandle[count];
for (int i = 0; i < count; i++)
{
h.SetValue(i, Context.glCreateProgram());
@@ -242,9 +225,9 @@ namespace StgSharp.Graphics.GL
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static glHandleSet CreateShaderSet(int count, ShaderType type)
public GlHandle[] CreateShaderSet(int count, ShaderType type)
{
glHandleSet ret = new glHandleSet(count);
GlHandle[] ret = new GlHandle[count];
uint t = (uint)type;
for (int i = 0; i < count; i++)
{
@@ -252,66 +235,66 @@ namespace StgSharp.Graphics.GL
if (id == 0)
{
uint error = Context.glGetError();
InternalIO.InternalWriteLog($"Failed in creating shader: {error}", LogType.Error);
throw new Exception();
throw new InvalidOperationException($"Failed in creating shader: {error}");
}
ret.SetValue(i, id);
ret[i] = GlHandle.Alloc(id);
}
return ret;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void DeleteBuffer(glHandle handle)
public unsafe void DeleteBuffer(GlHandle handle)
{
Context.glDeleteBuffers(1, (uint*)handle.Handle);
Context.glDeleteBuffers(1, (uint*)&handle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void DeleteBuffers(glHandleSet handle)
public unsafe void DeleteBuffers(GlHandle[] handle)
{
Context.glDeleteBuffers(handle.length, (uint*)handle.Handle);
handle.Release();
if ((handle == null) || (handle.Length == 0))
{
throw new ArgumentNullException(nameof(handle));
}
fixed (GlHandle* hptr = handle)
{
uint* iptr = (uint*)hptr;
for (int i = 0; i < handle.Length; i++)
{
Context.glDeleteBuffers(1, iptr + i);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void DeleteVertexArrays(glHandleSet arrays)
public unsafe void DeleteVertexArrays(GlHandle[] arrays)
{
Context.glDeleteVertexArrays(arrays.length, (uint*)arrays.Handle);
arrays.Release();
fixed (GlHandle* hptr = arrays)
{
uint* iptr = (uint*)hptr;
for (int i = 0; i < arrays.Length; i++)
{
Context.glDeleteVertexArrays(1, iptr + i);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void DrawElements(GeometryType mode, uint count, TypeCode type, IntPtr ptr)
public unsafe void DrawElements(GeometryType mode, uint count, TypeCode type, IntPtr ptr)
{
uint a;
switch (type)
a = type switch
{
case TypeCode.UInt32:
a = GLconst.UNSIGNED_INT;
break;
case TypeCode.UInt16:
a = GLconst.UNSIGNED_SHORT;
break;
case TypeCode.Byte:
a = GLconst.UNSIGNED_BYTE;
break;
default:
InternalIO.InternalWriteLog(
$"{$"Parameter error in parameter {nameof(type)} method DrawElements. "}{$"Only {typeof(uint).Name},{typeof(ushort).Name},{typeof(byte).Name} types are supported."}",
LogType.Error);
return;
}
TypeCode.UInt32 => GLconst.UNSIGNED_INT,
TypeCode.UInt16 => GLconst.UNSIGNED_SHORT,
TypeCode.Byte => GLconst.UNSIGNED_BYTE,
_ => throw new ArgumentException(
$"{$"{$"Parameter error in parameter {nameof(type)} method DrawElements. "}"}{$"{$"Only {typeof(uint).Name},{typeof(ushort).Name},{typeof(byte).Name} types are supported."}"}")
};
Context.glDrawElements((uint)mode, count, a, (void*)ptr);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void DrawElementsInstanced(
public void DrawElementsInstanced(
GeometryType mode, uint count, TypeCode type, IntPtr ptr, uint amount
)
{
@@ -340,53 +323,98 @@ namespace StgSharp.Graphics.GL
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Enable(GLOperation operation)
public void Enable(GLOperation operation)
{
Context.glEnable((uint)operation);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glHandleSet GenBuffers(int count)
public void FrameBufferTexture2d(FrameBufferTarget target, uint attachment, Texture2DTarget texTarget, GlHandle textureHandle, int level)
{
glHandleSet h = new glHandleSet(count);
Context.glGenBuffers(count, (uint*)h.Handle);
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glHandleSet GenRenderBuffer(int count)
{
glHandleSet h = new glHandleSet(count);
Context.glGenRenderbuffers(count, (uint*)h.Handle);
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glHandleSet GenTextures(int count)
{
glHandleSet h = new glHandleSet(count);
Context.glGenTextures(count, (uint*)h.Handle);
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetRenderBufferStorage(RenderBufferInternalFormat internalFormat ,(int width, int height) size)
{
Context.glRenderbufferStorage(
GLconst.RENDERBUFFER, (uint)internalFormat,size.width,size.height
Context.glFramebufferTexture2D(
(uint)target, attachment, (uint)texTarget, textureHandle.Value, level
);
}
public static unsafe glHandleSet GenVertexArrays(int count)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe GlHandle[] GenBuffers(int count)
{
glHandleSet h = new glHandleSet(count);
Context.glGenVertexArrays(count, (uint*)h.Handle);
GlHandle[] h = new GlHandle[count];
fixed (GlHandle* hptr = h)
{
for (int i = 0; i < count; i++)
{
Context.glGenBuffers(count, ((uint*)hptr) + i);
}
}
return h;
}
public static string GetShaderStatus(Shader s, int index, int key)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GenerateMipmap(Texture2DTarget target)
{
Context.glGenerateMipmap((uint)target);
}
public unsafe GlHandle[] GenFrameBuffers(int count)
{
GlHandle[] h = new GlHandle[count];
fixed (GlHandle* hptr = h)
{
Context.glGenFramebuffers(1, (uint*)hptr);
}
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe GlHandle[] GenRenderBuffer(int count)
{
GlHandle[] h = new GlHandle[count];
fixed (GlHandle* hptr = h)
{
Context.glGenRenderbuffers(count, (uint*)hptr);
}
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe GlHandle[] GenTextures(int count)
{
GlHandle[] h = new GlHandle[count];
fixed (GlHandle* hptr = h)
{
Context.glGenTextures(count, (uint*)hptr);
}
return h;
}
public unsafe GlHandle[] GenVertexArrays(int count)
{
GlHandle[] h = new GlHandle[count];
fixed (GlHandle* hptr = h)
{
Context.glGenVertexArrays(count, (uint*)hptr);
}
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public uint GetError()
{
return Context.glGetError();
}
public unsafe int GetMaskInteger(uint statusCode)
{
int ret = 0;
Context.glGetIntegerv(statusCode, &ret);
return ret;
}
public string GetShaderStatus(Shader s, int index, int key)
{
IntPtr sptr = IntPtr.Zero;
if (InternalIO.glCheckShaderStatus(ref Context, s.handle[index].Value, key, ref sptr) == 0)
@@ -396,31 +424,48 @@ namespace StgSharp.Graphics.GL
return string.Empty;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void GetTextureImage<T>(Texture2DTarget target, int level, ImageChannel channel, PixelChannelLayout channelLayout, T[] dataStream)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
#pragma warning disable CS8500
fixed (T* tptr = dataStream)
{
Context.glGetTexImage((uint)target, level, (uint)channel, (uint)channelLayout, tptr);
}
#pragma warning restore CS8500
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe glSHandle GetUniformLocation(glHandle program, string name)
public unsafe GlHandle GetUniformLocation(GlHandle program, string name)
{
byte[] code = Encoding.UTF8.GetBytes(name);
fixed (byte* ptr = code)
{
int ret = Context.glGetUniformLocation(program.Value, ptr);
#if DEBUG
if (ret == (int)(GLconst.INVALID_OPERATION) ||
ret == (int)(GLconst.INVALID_VALUE))
if ((ret == GLconst.INVALID_OPERATION) ||
(ret == GLconst.INVALID_VALUE))
{
throw new InvalidOperationException();
}
if (ret == -1 )
if (ret == -1)
{
throw new UniformEmptyReferenceException(nameof(program), name);
}
#endif
return glSHandle.Alloc(ret);
return GlHandle.SignedAlloc(ret);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void LoadShaderSource(glHandle shaderHandle, byte[] codeStream)
public unsafe void LoadShaderSource(GlHandle shaderHandle, byte[] codeStream)
{
fixed (byte* streamPtr = codeStream)
{
@@ -428,8 +473,38 @@ namespace StgSharp.Graphics.GL
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferData<T>(BufferType bufferType, T bufferData, BufferUsage usage)
public void ReadPixels(
(int X, int Y) beginPosition, (int width, int height) size, FrameBufferChannel format, PixelChannelLayout dataType, ref byte[] stream
)
{
fixed (byte* bptr = stream)
{
Context.glReadPixels(
beginPosition.X, beginPosition.Y,
size.width, size.height, (uint)format, (uint)dataType, bptr);
}
}
public void RereadImage(
in Image i, (int X, int Y) beginPosition, FrameBufferChannel format, PixelChannelLayout dataType)
{
byte[] pixels = i.PixelBuffer;
if (!pixels.CheckArrayFormat(dataType))
{
throw new GlArrayFormatException(dataType, "i.PixelArray");
}
fixed (byte* bptr = pixels)
{
Context.glReadPixels(
beginPosition.X, beginPosition.Y, i.Width, i.Height, (uint)format, (uint)dataType, bptr);
}
i.PixelUpdateCount++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void SetBufferData<T>(BufferType bufferType, T bufferData, BufferUsage usage)
where T : struct
{
int size = Marshal.SizeOf<T>();
@@ -444,7 +519,7 @@ namespace StgSharp.Graphics.GL
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
public unsafe void SetBufferData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
@@ -471,7 +546,7 @@ namespace StgSharp.Graphics.GL
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferData<T>(BufferType bufferType, ReadOnlySpan<T> bufferArray, BufferUsage usage)
public unsafe void SetBufferData<T>(BufferType bufferType, ReadOnlySpan<T> bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
@@ -498,7 +573,7 @@ namespace StgSharp.Graphics.GL
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferData<T>(BufferType bufferType, Span<T> bufferArray, BufferUsage usage)
public unsafe void SetBufferData<T>(BufferType bufferType, Span<T> bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
@@ -526,7 +601,7 @@ namespace StgSharp.Graphics.GL
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferVectorData<T>(BufferType bufferType, ReadOnlySpan<T> bufferArray, BufferUsage usage)
public unsafe void SetBufferVectorData<T>(BufferType bufferType, ReadOnlySpan<T> bufferArray, BufferUsage usage)
where T : struct, IVector
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
@@ -547,7 +622,7 @@ namespace StgSharp.Graphics.GL
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void SetBufferVectorData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
public unsafe void SetBufferVectorData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
where T : struct, IVector
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
@@ -568,7 +643,15 @@ namespace StgSharp.Graphics.GL
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SetVertexAttribute(uint index, int size, TypeCode t, bool normalized, uint stride, int pointer)
public unsafe void SetRenderBufferStorage(RenderBufferInternalFormat internalFormat, (int width, int height) size)
{
Context.glRenderbufferStorage(
GLconst.RENDERBUFFER, (uint)internalFormat, size.width, size.height
);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetVertexAttribute(uint index, int size, TypeCode t, bool normalized, uint stride, int pointer)
{
uint type = InternalIO.GLtype[t];
Context.glVertexAttribPointer(index, size, type, normalized ? 1 : 0, stride, (void*)pointer);
@@ -576,47 +659,93 @@ namespace StgSharp.Graphics.GL
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void TextureImage2d(Texture2DTarget target, int level, uint internalformat, uint width, uint height,
uint format, ImageChannelLayout type, glHandle pixels)
public void TextureImage2d<T>(Texture2DTarget target, int level, uint internalformat, uint width, uint height,
uint format, PixelChannelLayout type, T[] pixels) where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
Context.glTexImage2D(
(uint)target, level, internalformat, width, height, 0, format, (uint)type, pixels.valuePtr
);
#pragma warning disable CS8500
fixed (T* tptr = ((pixels == null) || (pixels.Length == 0)) ? null : pixels)
{
Context.glTexImage2D(
(uint)target, level, internalformat, width, height, 0, format, (uint)type, tptr);
}
#pragma warning restore CS8500
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void TextureImage2d(Texture2DTarget target, int level, uint internalformat, uint width, uint height,
uint format, ImageChannelLayout type, glArrayHandle pixelArrayHandle)
public void TextureImage2d<T>(Texture2DTarget target, int level, uint internalformat, uint width, uint height,
uint format, PixelChannelLayout type, Span<T> pixelSpan) where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
Context.glTexImage2D(
(uint)target, level, internalformat, width, height, 0, format, (uint)type, (void*)pixelArrayHandle.handle.AddrOfPinnedObject()
);
#pragma warning disable CS8500
fixed (T* tptr = pixelSpan)
{
Context.glTexImage2D(
(uint)target, level, internalformat, width, height, 0, format, (uint)type, tptr);
}
#pragma warning restore CS8500
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void TextureParameter(int target, uint pname, int param)
public void TextureParameter(int target, uint pname, int param)
{
Context.glTexParameteri((uint)target, pname, param);
}
public static bool TryGetFunctionPackage(IntPtr handle, out OpenGLFunction functionPackage)
{
return contextToGLMap.TryGetValue(handle, out functionPackage);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void UseProgram(glHandle program)
public void UseProgram(GlHandle program)
{
Context.glUseProgram(program.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void VertexAttributeDivisor(uint layoutIndex, uint divisor)
public void VertexAttributeDivisor(uint layoutIndex, uint divisor)
{
Context.glVertexAttribDivisor(layoutIndex, divisor);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Viewport(int x, int y, uint width, uint height)
public void Viewport(int x, int y, uint width, uint height)
{
Context.glViewport(x, y, width, height);
}
public void WaitAccomplishment()
{
Context.glFinish();
}
internal static OpenGLFunction BuildGlFunctionPackage(IntPtr handle)
{
OpenGLFunction pack;
if (contextToGLMap.TryGetValue(handle, out pack))
{
return pack;
}
pack = new OpenGLFunction { _context = (OpenglContext*)handle };
contextToGLMap.Add(handle, pack);
return pack;
}
~OpenGLFunction()
{
contextToGLMap.Remove(ContextHandle);
}
}
}
@@ -28,52 +28,53 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Logic;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics.OpenGL
{
public abstract partial class glRenderStream : RenderStream
{
protected glRenderStream(ViewPort v, (int,int,int) cube) : base(v,cube)
{
}
private OpenGLFunction _context;
protected IntPtr glContextHandle
protected internal OpenGLFunction GL
{
get { return ContextHandle; }
get { return _context; }
}
/// <summary>
/// Init an OpenGl context if current form has not been binded to any context. and set the context binded to
/// current form as current OpenGL context.
/// Initialize an OpenGl viewPortDisplay if current form has not been binded to any viewPortDisplay.
/// and set the viewPortDisplay binded to current form as current OpenGL viewPortDisplay.
/// </summary>
/// <exception cref="Exception">
/// Something goes wrong and StgSharp fails in creating a new OpenGL context.
/// Something goes wrong and StgSharp fails in creating a new OpenGL viewPortDisplay.
/// </exception>
public unsafe void MakeAsCurrentContext()
{
if (ContextHandle == default)
{
ContextHandle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GLcontext)));
GLcontext* contextID = (GLcontext*)ContextHandle;
ContextHandle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(OpenglContext)));
OpenglContext* contextID = (OpenglContext*)ContextHandle;
contextID->glGetString = (delegate*<uint, IntPtr>)IntPtr.Zero;
}
if (glFunc.CurrentContextHandle != ContextHandle)
if (GL == null)
{
glFunc.CurrentContextHandle = ContextHandle;
//Console.WriteLine($"context set as {(ulong)glFunc.CurrentContextHandle}");
_context = OpenGLFunction.BuildGlFunctionPackage(ContextHandle);
}
if (OpenGLFunction.CurrentGL != GL)
{
OpenGLFunction.CurrentGL = GL;
InternalIO.glfwMakeContextCurrent(CanvasHandle);
}
}
@@ -84,25 +85,24 @@ namespace StgSharp.Graphics.GL
InternalIO.glfwSetWindowSizeLimits(this.CanvasHandle, minWidth, minHeight, maxWidth, maxHeight);
}
internal override sealed void InternalDraw(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal override sealed void Draw()
{
MakeAsCurrentContext();
ProcessInput();
Main(in input, in output);
Main();
}
internal override sealed void InternalInit()
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal override sealed void PlatformSpecifiedInitialize()
{
MakeAsCurrentContext();
this.Port.LoadGLapi();
Init();
glManager.LoadOpenGLApiTo(Port.GraphicHandle);
}
internal override sealed void InternalTerminate()
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal override sealed void Terminate()
{
Deinit();
CustomizeDeinit();
}
protected override sealed Uniform<Matrix44> NativeCameraUniform(ShaderProgram source, string name)
@@ -122,16 +122,6 @@ namespace StgSharp.Graphics.GL
NativeCamera.SetViewDirection(position, direction, up);
}
protected static void PollEvents()
{
InternalIO.glfwPollEvents();
}
protected void SwapBuffers()
{
InternalIO.glfwSwapBuffers(CanvasHandle);
}
#region Key Control
protected KeyStatus CheckKey(KeyboardKey key)
@@ -151,5 +141,6 @@ namespace StgSharp.Graphics.GL
#endregion
}
}
@@ -1,6 +1,6 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLresourceGenrator.cs"
// file="glResourceGenrator.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
@@ -35,7 +35,7 @@ using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics.OpenGL
{
public partial class glRenderStream
{
@@ -51,6 +51,12 @@ namespace StgSharp.Graphics.GL
return new ElementBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected FrameBuffer CreateFrameBuffer(int count)
{
return new FrameBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected RenderBuffer CreateRenderBuffer(int count)
@@ -58,12 +64,6 @@ namespace StgSharp.Graphics.GL
return new RenderBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected FrameBuffer CreateFrameBuffer(int count)
{
return new FrameBuffer(count, this);
}
/// <summary>
/// Create a sets of <see cref="TextureGL"/>
/// </summary>
@@ -75,6 +75,13 @@ namespace StgSharp.Graphics.GL
return new TextureGL(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected AutoTextureGL CreateAutoTexture(int count)
{
return new AutoTextureGL(count, this);
}
/// <summary>
/// Create a set of <see cref="VertexArray"/>.
/// </summary>
@@ -97,6 +104,6 @@ namespace StgSharp.Graphics.GL
return new VertexBuffer(count, this);
}
}
}
@@ -0,0 +1,99 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glResourceManager.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the ¡°Software¡±), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ¡°AS IS¡±,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace StgSharp.Graphics.OpenGL
{
public partial class OpenGLFunction
{
private Lazy<int> textureUnitCountGetter;
private Lazy<ConcurrentQueue<TextureUnit>> unusedTextureImageUintInitilizing;
public int TextureUnitCount
{
get => textureUnitCountGetter.Value;
}
private ConcurrentQueue<TextureUnit> UnusedTextureImageUint
{
get => unusedTextureImageUintInitilizing.Value;
}
internal void ReturnAvailableUnit(IEnumerable<TextureUnit> source)
{
int v = GLconst.TEXTURE0 + TextureUnitCount;
foreach (TextureUnit unit in source)
{
if ((int)unit > v)
{
throw new InvalidOperationException("Source contains texture unit beyond context support.");
}
}
}
internal int TryGetAvailableTextureUnit(int count, out IEnumerable<TextureUnit> result)
{
result = new Queue<TextureUnit>();
for (int i = 0; i < count; i++)
{
if (UnusedTextureImageUint.TryDequeue(out TextureUnit unit))
{
(result as Queue<TextureUnit>)!.Enqueue(unit);
}
else
{
return i;
}
}
return count;
}
private ConcurrentQueue<TextureUnit> InitializeUnusedTextureImageUint()
{
ConcurrentQueue<TextureUnit> result = new ConcurrentQueue<TextureUnit>();
for (int index = 0; index < TextureUnitCount; index++)
{
result.Enqueue((TextureUnit)(GLconst.TEXTURE0 + index));
}
return result;
}
}
}

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