MVVM frame work done, under unit test

This commit is contained in:
Nitload
2024-07-25 04:41:24 +08:00
parent 924fe6eef7
commit da75200347
101 changed files with 8435 additions and 847 deletions
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
Binary file not shown.
@@ -14,7 +14,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("BenchMark")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+c0093f7b5c77291172cde7e3e38beabb126adf08")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+924fe6eef7b6b9441b297f211c82b4684f23d002")]
[assembly: System.Reflection.AssemblyProductAttribute("BenchMark")]
[assembly: System.Reflection.AssemblyTitleAttribute("BenchMark")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -14,7 +14,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("BenchMark")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+66efce19fcb461782c49255dc5500144f8c267e6")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+924fe6eef7b6b9441b297f211c82b4684f23d002")]
[assembly: System.Reflection.AssemblyProductAttribute("BenchMark")]
[assembly: System.Reflection.AssemblyTitleAttribute("BenchMark")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -14,7 +14,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("OEM")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+8f9f1c4012e0ba8723569f71754633060f4f0d85")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+924fe6eef7b6b9441b297f211c82b4684f23d002")]
[assembly: System.Reflection.AssemblyProductAttribute("OEM")]
[assembly: System.Reflection.AssemblyTitleAttribute("OEM")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -14,7 +14,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("OEM")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+66efce19fcb461782c49255dc5500144f8c267e6")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+924fe6eef7b6b9441b297f211c82b4684f23d002")]
[assembly: System.Reflection.AssemblyProductAttribute("OEM")]
[assembly: System.Reflection.AssemblyTitleAttribute("OEM")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -1,10 +1,12 @@
#version 460 core
uniform float time;
out vec3 fragColor;
void main()
{
fragColor = vec3( 0.5f,0.336f,0.9961f );
fragColor = vec3( 0.5f,0.336f,mod( (0.9961f + time),1.0f) );
}
@@ -0,0 +1,13 @@
#version 430 core
in vec3 texCoord;
out vec4 fragColor;
uniform sampler2D tex;
void main()
{
fragColor = texture(tex, texCoord.xy);
//fragColor = vec4(0.0f,0.0f,0.0f,0.0f);
}
@@ -0,0 +1,13 @@
#version 330 core
layout(location = 0)in vec3 coord;
layout(location = 1)in vec3 tCoord;
out vec3 texCoord;
void main()
{
gl_Position = vec4(coord.xyz,1.0f);
texCoord = tCoord;
}
@@ -0,0 +1,17 @@
#version 330 core
in vec2 TexCoord;
out vec4 FragColor;
uniform vec4 color;
uniform sampler2D ourTexture;
uniform sampler2D ourTexture2;
void main()
{
vec4 tex1 = texture(ourTexture, TexCoord);
vec4 tex2 = texture(ourTexture2,TexCoord);
FragColor = mix(tex1 * vec4( color.xyz, 1.0), tex2, 0.2) /* *vec4( TexColor,1.0) /**/;
}
@@ -0,0 +1,22 @@
#version 330 core
layout(location = 0) in vec3 aPos;
layout(location = 1) in vec3 aColor;
layout(location = 2) in vec2 aTextCoord;
out vec2 TexCoord;
uniform mat4x4 camera;
void main()
{
TexCoord = aTextCoord;
vec4 temp = vec4(aPos.xyz,1.0);
gl_Position = /**/ camera * /**/ temp;
}
//struct
@@ -0,0 +1,12 @@
#version 460 core
uniform float time;
out vec3 fragColor;
void main()
{
fragColor = vec3( 0.5f,0.336f,mod( (0.9961f + time),1.0f) );
}
@@ -0,0 +1,36 @@
#version 460 core
layout(location = 0) in vec3 singleCoord;
layout(location = 1) in vec3 locations;
layout(location = 2) in float rotation;
layout(location = 3) in float scale;
uniform mat4x4 Camera;
void main()
{
/**/
mat4x4 scalingMat = mat4x4
(
scale,0,0,0,
0,scale,0,0,
0,0,scale,0,
0,0,0,1
);
/**/
/**/
mat4x4 rotationMat = mat4x4
(
cos(rotation),-sin(rotation),0,0,
sin(rotation),cos(rotation),0,0,
0,0,1,0,
0,0,0,1
);
/**/
gl_Position = Camera * ( rotationMat * scalingMat * vec4( singleCoord.xyz , 1) + vec4( locations.xyz , 0));
}
@@ -43,9 +43,9 @@ namespace StgSharp.Controls
{
public class BattleField : ControllingItem
{
public override vec4d[] TextureBox
public override ReadOnlySpan<vec4d> TextureBox
{
get ;
get => throw new NotImplementedException() ;
}
public override IEnumerator<PlainGeometryMesh> GetEnumerator()
@@ -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,36 @@ 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 override ReadOnlySpan<vec4d> TextureBox
{
get => throw new NotSupportedException();
}
public TriggerButton CurrentButton
{
get => current;
}
protected List<TriggerButton> AllButton
{
get => buttonList;
}
public void AddButton(TriggerButton button)
@@ -26,46 +73,79 @@ namespace StgSharp.Controls
buttonList.Add(button);
}
public TriggerButton CurrentButton
{
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 abstract 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;
}
}
}
@@ -20,7 +20,7 @@ namespace StgSharp.Controls
Dictionary<char, PlainGeometryMesh> texIndex;
PlainGeometryMesh _tittleMesh;
public override vec4d[] TextureBox
public override ReadOnlySpan<vec4d> TextureBox
{
get => throw new NotSupportedException();
}
@@ -14,7 +14,7 @@ namespace StgSharp.Controls
public vec2d Position { get; set; }
public Rectangle BoundingBox { get; set; }
public abstract vec4d[] TextureBox { get; }
public abstract ReadOnlySpan<vec4d> TextureBox { get; }
public abstract IEnumerator<PlainGeometryMesh> GetEnumerator();
@@ -13,7 +13,7 @@ namespace StgSharp.Controls
{
private PlainGeometryMesh renderMesh;
public override vec4d[] TextureBox
public override ReadOnlySpan<vec4d> TextureBox
{
get => renderMesh.TextureCoord;
}
@@ -23,9 +23,9 @@ namespace StgSharp.Controls
yield return renderMesh;
}
public DecorationBox(Rectangle bound, Image texture, vec4d[] texCoord)
public DecorationBox(Rectangle bound, Image texture, vec2d[] texCoord)
{
renderMesh = new PlainGeometryMesh(BoundingBox, texture, texCoord);
renderMesh = new PlainGeometryMesh(BoundingBox, new TextureProvider(texture, texCoord));
}
}
}
@@ -12,7 +12,7 @@ namespace StgSharp.Controls
{
public class MarkingLabel : ControllingItem
{
public override vec4d[] TextureBox
public override ReadOnlySpan<vec4d> TextureBox
{
get => marker.TextureCoord;
}
@@ -35,81 +35,148 @@ using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Controls
{
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 delegate void RenderButtonTextureCallback(ButtonStatus status, float beginTime, in TextureProvider texture);
public class TriggerButton : ControllingItem
{
private AnimationBuilder switchAnimationBuilder;
private TextureProvider _texture;
private float _statusBeginTime;
public TriggerButton Left { get; internal set; }
public TriggerButton Right { get; internal set; }
public TriggerButton Up { get; internal set; }
public TriggerButton Down { get; internal set; }
#nullable enable
private Action? enableAction;
private Action? disableAction;
private Action? confirmAction;
private Action? enableCallback;
private Action? disableCallback;
private Action? confirmCallback;
#nullable restore
public override vec4d[] TextureBox
protected ButtonStatus CurrentStatus { get; set; }
private RenderButtonTextureCallback _renderButton;
public event RenderButtonTextureCallback RenderButtonTexture
{
get { return switchAnimationBuilder.TextureFrame.VertexStream; }
add
{
if (_renderButton == null)
{
_renderButton = value;
}
else
{
_renderButton += value;
}
}
remove
{
if (_renderButton != null)
{
_renderButton -= value;
}
}
}
public override ReadOnlySpan<vec4d> TextureBox
{
get => MemoryMarshal.Cast<vec2d, vec4d>(_texture.TextureCoordinate);
}
public bool IsHighLighted { get; internal set; }
public bool IsDisabled { get; internal set; }
public event Action EnableEvent
{
add { enableAction += value; }
remove { enableAction -= value; }
add { enableCallback += value; }
remove { enableCallback -= value; }
}
public event Action DisableEvent
{
add { disableAction += value; }
remove { disableAction -= value; }
add { disableCallback += value; }
remove { disableCallback -= value; }
}
public event Action ConfirmEvent
{
add { confirmAction += value; }
remove { confirmAction -= value; }
add { confirmCallback += value; }
remove { confirmCallback -= value; }
}
public void Enable(AnimationBuilder animation)
public void Enable()
{
if (!IsDisabled)
if (CurrentStatus == ButtonStatus.Disable)
{
CurrentStatus = ButtonStatus.DisableToEnable;
}
else
{
return;
}
if (switchAnimationBuilder == null || switchAnimationBuilder.IsComplete)
{
switchAnimationBuilder = animation;
}
if( enableAction != null)enableAction();
if ( enableCallback != null)enableCallback();
}
public void Disable(AnimationBuilder animation)
public void Disable()
{
if (switchAnimationBuilder == null || switchAnimationBuilder.IsComplete)
CurrentStatus = CurrentStatus switch
{
switchAnimationBuilder = animation;
}
if (disableAction != null) disableAction();
ButtonStatus.Enable => ButtonStatus.EnableToDisable,
ButtonStatus.Highlight => ButtonStatus.HighlightToDisable,
_ => CurrentStatus,
};
if (disableCallback != null) disableCallback();
}
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();
}
public void DeHighlight()
{
if (CurrentStatus == ButtonStatus.Highlight)
{
CurrentStatus = ButtonStatus.HighlightToEnable;
}
if (confirmAction != null) confirmAction();
}
public override IEnumerator<PlainGeometryMesh> GetEnumerator()
{
yield return new PlainGeometryMesh(this.BoundingBox, switchAnimationBuilder.GetAnimationFrame(),
this.TextureBox);
_renderButton(CurrentStatus,_statusBeginTime, in _texture);
yield return new PlainGeometryMesh(this.BoundingBox, _texture);
}
}//----------------------------------- End of class --------------------------------------------
@@ -30,7 +30,7 @@
//-----------------------------------------------------------------------
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -103,10 +103,12 @@ namespace StgSharp
try
{
IntPtr procPtr =
#if Windows
#if WINDOWS
IntPtr.Zero;
#elif Linux
#elif LINUX
#else
IntPtr.Zero;
#endif
return procPtr;
}
@@ -0,0 +1,92 @@
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
{
/// <summary>
/// ViewDesigner provides descriptions of various controls in the view,
/// binds the controls to specific user actions and behaviors,
/// and describes the layout and interactions of each control.
/// </summary>
public abstract class ViewDesigner<TView> where TView:View
{
protected TView _binding;
private KeyboardButtonGroup currentButtonGroup;
private List<ControllingItem> _controlList;
public ViewDesigner()
{
_controlList = new List<ControllingItem>();
}
protected TView Binding
{
get => _binding;
}
public TButtonGroup CreateKeyboardButtonGroup<TButtonGroup>(
ITrigger leftBidning,
ITrigger rightBinding,
ITrigger upBinding,
ITrigger downBinding,
ITrigger confirmBinding
)
where TButtonGroup : KeyboardButtonGroup,new()
{
var ret = new TButtonGroup();
_controlList.Add(ret);
currentButtonGroup = ret;
_binding.Responder[leftBidning] = ret.MoveLeft;
_binding.Responder[rightBinding] = ret.MoveRight;
_binding.Responder[upBinding] = ret.MoveUp;
_binding.Responder[downBinding] = ret.MoveDown;
_binding.Responder[confirmBinding] = ret.Confirm;
return ret;
}
public TriggerButton CreateKeyboardButton(
Rectangle bonding, TextureProvider defaultAnimation, bool isEnable
)
{
var ret = new TriggerButton();
ret.BoundingBox = bonding;
if (isEnable)
{
ret.IsDisabled = false;
ret.Enable();
}
else
{
ret.IsDisabled = true;
ret.Disable();
}
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;
}
public abstract void CustomizedInitialize();
public abstract bool ValidateInitializing();
}//---------------------------------- End of Class -----------------------------------------
}
@@ -0,0 +1,92 @@
using StgSharp.Controlling.UsrActivity;
using StgSharp.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp
{
public abstract class ViewResponder<TView> where TView: View
{
private View _viewbinding;
private Dictionary<ITrigger, Action> keyCallbackIndex;
private Dictionary<string, Action> nameToCallbackMap;
private bool _isInitialized;
protected ViewResponder()
{
keyCallbackIndex = new Dictionary<ITrigger, Action>();
nameToCallbackMap = new Dictionary<string, Action>();
}
internal void ProcessUserInput()
{
foreach (var pair in keyCallbackIndex)
{
ITrigger t = pair.Key;
if (InternalIO.glfwGetKey(_viewbinding.ViewHandle, t.TargetKeyOrButtonID) == t.TriggeredStatus)
{
pair.Value();
}
}
}
public Action this[ITrigger trigger]
{
get => keyCallbackIndex.TryGetValue(trigger, out Action callback) ? callback : null;
set
{
if (keyCallbackIndex.TryGetValue(trigger, out Action callback))
{
callback += value;
}
else
{
keyCallbackIndex.Add(trigger, value);
}
}
}
internal void Init(Func<string, Action> keyGetter)
{
if (_isInitialized)
{
return;
}
CustomizedInitialize(
(trigger, name) =>
{
if (!nameToCallbackMap.TryGetValue(name, out Action ret))
{
ret = keyGetter.Invoke(name)??
throw new InvalidOperationException($"Cannot find method named {name} in binded view model");
}
this[trigger] = ret;
return ret;
}
);
}
public void ProcessInput()
{
foreach (var pair in keyCallbackIndex)
{
if (InternalIO.glfwGetKey(_viewbinding.ViewHandle,(int)pair.Key.TargetKeyOrButtonID) == pair.Key.TriggeredStatus)
{
pair.Value();
}
}
}
public abstract void CustomizedInitialize(Func<ITrigger, string, Action> keyRegister);
public abstract bool ValidateInitializing();
}
}
@@ -74,7 +74,7 @@ namespace StgSharp
}
/// <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)
@@ -8,6 +8,7 @@ using System.Text;
namespace StgSharp.Geometries
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate vec3d GeometryMotionDelegate(TimeSpanProvider timeSource, out float rotation);
public class GeometryMotion
@@ -20,15 +21,7 @@ namespace StgSharp.Geometries
public static GeometryMotion DefaultMotion
{
get
{
return new GeometryMotion
(
true,
null,
null
);
}
get => new GeometryMotion(true, null, null);
}
private static vec3d defaultMotion(TimeSpanProvider provider, out float rotation)
@@ -60,7 +53,7 @@ namespace StgSharp.Geometries
{
movement = motionDelegate;
}
sourceIsStatic = false;
//sourceIsStatic = false;
}
public bool IsIncrement
@@ -71,11 +64,11 @@ namespace StgSharp.Geometries
public unsafe void RunMotion(ref vec3d coord, ref float rotation)
{
float rot = 0;
float rot;
vec3d vec;
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
{
@@ -89,7 +82,7 @@ namespace StgSharp.Geometries
}
else
{
coord = vec.XYZ;
coord = vec;
rotation = rot;
}
}
+12
View File
@@ -0,0 +1,12 @@
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Design", "CA1008:枚举应具有零值", Justification = "<挂起>", Scope = "type", Target = "~T:StgSharp.Graphics.OpenGL.ShaderStatus")]
[assembly: SuppressMessage("Naming", "CA1715:标识符应具有正确的前缀", Justification = "<挂起>", Scope = "member", Target = "~M:StgSharp.Graphics.OpenGL.ShaderProgram.GetUniform``2(System.String)~StgSharp.Graphics.OpenGL.Uniform{``0,``1}")]
[assembly: SuppressMessage("Naming", "CA1715:标识符应具有正确的前缀", Justification = "<挂起>", Scope = "member", Target = "~M:StgSharp.Graphics.OpenGL.ShaderProgram.GetUniform``3(System.String)~StgSharp.Graphics.OpenGL.Uniform{``0,``1,``2}")]
[assembly: SuppressMessage("Naming", "CA1715:标识符应具有正确的前缀", Justification = "<挂起>", Scope = "member", Target = "~M:StgSharp.Graphics.OpenGL.ShaderProgram.GetUniform``4(System.String)~StgSharp.Graphics.OpenGL.Uniform{``0,``1,``2,``3}")]
[assembly: SuppressMessage("Naming", "CA1715:标识符应具有正确的前缀", Justification = "<挂起>", Scope = "type", Target = "~T:StgSharp.Graphics.OpenGL.Uniform`4")]
@@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Graphics
{
public static class ImageHelper
{
public static void Resize(Image i, int width, int height, ImageMovement move)
{
if (i == null)
{
throw new ArgumentNullException(nameof(i));
}
Array.Resize(ref i.data, width * height * i.PixelSize);
i.Height = height;
i.Width = width;
switch (move)
{
case ImageMovement.Discard:
break;
case ImageMovement.Top:
break;
default:
throw new NotSupportedException("Invalid or not supported data remanence");
}
}
}
[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,
}
}
@@ -0,0 +1,82 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="BufferObjectBase.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
{
/// <summary>
/// Interface of all kinds OpenGL buffer objects
/// </summary>
public abstract class BufferObjectBase : IDisposable
{
protected RenderStream binding;
protected GlHandle[] _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];
/// <summary>
/// Bind a buffer instance to OpenGL
/// </summary>
/// <param name="index">Index of handle of the object in this instance to be bind</param>
public abstract void Bind(int index);
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
/// <inheritdoc/>
public override string ToString()
{
return $"This is a {GetType().FullName}, containing {_bufferHandle.Length} buffer handles: {_bufferHandle.ToString()}.";
}
protected abstract void Dispose(bool disposing);
~BufferObjectBase()
{
Dispose(disposing: false);
}
}
}
@@ -28,7 +28,7 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using System;
using System.Runtime.InteropServices;
@@ -31,7 +31,7 @@
using System;
using System.Drawing;
namespace StgSharp.Graphics.GL
namespace StgSharp.Graphics.OpenGL
{
//rename types in style of GLconst
@@ -4850,7 +4850,7 @@ namespace StgSharp.Graphics.GL
public static class glAttachment
{
private static int colorRange =
glFunc.GetMaskInteger((uint)GLconst.MAX_COLOR_ATTACHMENTS);
GlFunction.CurrentGL.GetMaskInteger((uint)GLconst.MAX_COLOR_ATTACHMENTS);
public static uint Color(int i)
{
+27 -14
View File
@@ -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
{
+99 -83
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;
@@ -49,6 +50,17 @@ namespace StgSharp.Graphics
internal byte[] data;
internal ImageInfo info;
public PixelChannelLayout PixelLayout
{
get => info.pixelLayout;
private set => info.pixelLayout = value;
}
internal unsafe Image()
{
info = new ImageInfo();
}
internal Image(ImageInfo information)
{
info = information;
@@ -56,16 +68,6 @@ namespace StgSharp.Graphics
//int length = info.width * info.height * info.channel;
}
public unsafe Image()
{
info = new ImageInfo();
}
public ref byte[] DataStream
{
get => ref data;
}
public (int width, int height) Size
{
get => (info.Width, info.Height);
@@ -78,12 +80,15 @@ namespace StgSharp.Graphics
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 SerializableTypeCode SSDTypeCode => SerializableTypeCode.PixelImage;
public void FromBytes(byte[] stream)
@@ -101,71 +106,68 @@ 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, PixelChannelLayout layout, 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.PixelLayout = layout;
ret.data = stream;
return ret;
}
public glArrayHandle GetArrayHandle()
public static Image FromMemory((int width, int height) size, ImageChannel channel, 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 = PixelChannelLayout.Byte;
ret.data = stream;
return ret;
}
public unsafe byte[] GetBytes()
{
if (data == null)
{
int size = Width * Height * ChannelCount;
data = new byte[size];
int i = 0;
fixed (byte* bptr = data)
if (data.Length == 0)
{
byte* pptr = bptr;
for (; i < size; i += 16)
int size = Width * Height * GlHelper.GetPixelSize(PixelLayout, Channel);
data = new Span<byte>((byte*)info.StreamPtr, size).ToArray();
fixed (ImageInfo* pptr = &info)
{
*(M128*)(pptr + i) = *(M128*)(info.StreamPtr + i);
}
for (; i < size; i++)
{
*(pptr + i) = *(byte*)(info.StreamPtr + i);
InternalIO.InternalUnloadImage(pptr);
}
info.StreamPtr = IntPtr.Zero;
}
fixed (ImageInfo* pptr = &info)
{
InternalIO.InternalUnloadImage(pptr);
}
info.StreamPtr = IntPtr.Zero;
}
return data;
return data;
}
public Image ProvideImage()
public byte[] PixelBuffer
{
get{
if ((data.Length == 0) || (data == null))
{
GetBytes();
return data!;
}
return data;
}
}
public Image ProvideImage() => this;
byte[] ISSDSerializable.GetBytes()
{
throw new NotImplementedException();
}
~Image()
{
if (info.StreamPtr != IntPtr.Zero)
{
// Marshal.FreeHGlobal(info.StreamPtr);
}
}
}
[StructLayout(LayoutKind.Sequential)]
@@ -173,10 +175,10 @@ namespace StgSharp.Graphics
{
private ImageChannel channel;
private int channelCount;
private int height;
private int width;
private IntPtr pixelPtr;
internal PixelChannelLayout pixelLayout;
public ImageChannel Channel
{
@@ -184,42 +186,12 @@ namespace StgSharp.Graphics
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.");
}
}
}
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
@@ -230,7 +202,7 @@ namespace StgSharp.Graphics
public int StreamSize
{
get => width * height * channelCount;
get => width * height * GlHelper.GetPixelSize(pixelLayout, channel);
}
public int Width
@@ -256,9 +228,53 @@ namespace StgSharp.Graphics
{
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,84 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="EBO.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Graphics.OpenGL;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
/// <summary>
/// A collection of handle to Element Buffer Object in OpenglFunc.
/// Each <see langword="uint"/> value indexed from instance of this class this
/// is the only handle to one Element Buffer Object.
/// </summary>
public unsafe class ElementBuffer : GlBufferObjectBase
{
internal ElementBuffer(int n, glRenderStream binding):base(binding)
{
_bufferHandle = GL.GenBuffers(n);
}
public override sealed void Bind(int index)
{
GL.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
}
public void SetValue<T>(int index, T[] bufferArray, BufferUsage usage)
where T : struct, IConvertible
{
GL.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ElementArrayBuffer, bufferArray, usage);
}
public void SetValue<T>(int index, ReadOnlySpan<T> bufferSpan, BufferUsage usage)
where T : struct, IConvertible
{
GL.BindBuffer(BufferType.ElementArrayBuffer, _bufferHandle[index]);
GL.SetBufferData(BufferType.ElementArrayBuffer, bufferSpan, usage);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
{
GL.DeleteBuffers(_bufferHandle);
}
}
}
}
@@ -0,0 +1,65 @@
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 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 unsafe override void Bind(int index)
{
GL.BindFrameBuffer(FrameBufferTarget.All,_bufferHandle[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindNull()
{
GlFunction.CurrentGL.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>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Bind(FrameBufferTarget target, int index)
{
GL.BindFrameBuffer(target, _bufferHandle[index]);
}
protected override void Dispose(bool disposing)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,22 @@
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 GlFunction GL => _contextBinding.GL;
}
}
@@ -0,0 +1,39 @@
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.Security.Principal;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public 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]);
}
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");
}
}
}
}
@@ -0,0 +1,156 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// 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.OpenGL
{
public unsafe class TextureGL
{
private GlFunction GL;
internal static bool[] unitActivated = new bool[16];
internal GlHandle[] _textureHandle;
internal Image[] sourceList;
public GlHandle this[int index]
{
get => _textureHandle[index];
}
internal TextureGL(int n, glRenderStream binding)
{
sourceList = new Image[n];
this.GL = binding.GL;
_textureHandle = GL.GenTextures(n);
}
public void ActivateAs(TextureUnit unit)
{
GL.ActiveTexture((uint)unit);
}
public void Bind2D(int 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)
{
sourceList[index] = i;
var handle = sourceList[index].PixelBuffer;
GL.TextureImage2d(
Texture2DTarget.Texture2D, 0, (uint)i.Channel,
(uint)sourceList[index].Width, (uint)sourceList[index].Height,
(uint)i.Channel, i.PixelLayout,
pixels: handle
);
GL.GenerateMipmap(Texture2DTarget.Texture2D);
}
#region texture setting
public void Set2dFilterProperty(
Filter onMinify, Filter onMagnify)
{
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MIN_FILTER, (int)onMinify);
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MAG_FILTER, (int)onMagnify);
}
public void Set2dWrapProperty(
Wrap onHorizontial, Wrap onVertical)
{
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_S, (int)onHorizontial);
GL.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,
}
}
@@ -0,0 +1,78 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="VAO.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.Runtime.CompilerServices;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public unsafe class VertexArray : GlBufferObjectBase
{
internal VertexArray(int n, glRenderStream binding):base(binding)
{
_bufferHandle = GL.GenVertexArrays(n);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override sealed void Bind(int index)
{
GL.BindVertexArray(_bufferHandle[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindNull()
{
GlFunction.CurrentGL.BindVertexArray(GlHandle.Zero);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetVertexAttribute(uint index, int vertexLength, TypeCode dataType, bool isNomalized, uint stride, int pointer)
{
GL.SetVertexAttribute(
index, vertexLength, dataType,
isNomalized,
stride, pointer);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
{
GL.DeleteVertexArrays(_bufferHandle);
}
}
}
}
@@ -0,0 +1,152 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="VBO.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.Net.Security;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
public unsafe class VertexBuffer : GlBufferObjectBase
{
internal VertexBuffer(int n, glRenderStream binding):base(binding)
{
_bufferHandle = GL.GenBuffers(n);
}
public override sealed void Bind(int index)
{
GL.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
{
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);
}
/// <summary>
///
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Unbind()
{
GL.BindBuffer(BufferType.ArrayBuffer, GlHandle.Zero);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
{
GL.DeleteBuffers(_bufferHandle);
}
}
}
}
@@ -0,0 +1,102 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="GLresourceGenrator.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.OpenGL
{
public partial class glRenderStream
{
/// <summary>
/// Create a set of <see cref="ElementBuffer"/>.
/// </summary>
/// <param name="count">Amount of EBO to be created.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected ElementBuffer CreateElementBuffer(int count)
{
return new ElementBuffer(count, this);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected RenderBuffer CreateRenderBuffer(int count)
{
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>
/// <param name="count">Amount of textures to be created.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected TextureGL CreateTexture(int count)
{
return new TextureGL(count, this);
}
/// <summary>
/// Create a set of <see cref="VertexArray"/>.
/// </summary>
/// <param name="count">Amount of VAO to be created.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected VertexArray CreateVertexArray(int count)
{
return new VertexArray(count, this);
}
/// <summary>
/// Create a set of <see cref="VertexBuffer"/>.
/// </summary>
/// <param name="count">Amount of Object to be created.</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected VertexBuffer CreateVertexBuffer(int count)
{
return new VertexBuffer(count, this);
}
}
}
@@ -0,0 +1,59 @@
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 GlArrayFormatException : Exception
{
public GlArrayFormatException(PixelChannelLayout layout, string arrayname):
base($"{arrayname} cannot be used as layout of {layout}")
{
}
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 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,
};
}
}
}
@@ -0,0 +1,74 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// 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 uint Value;
[FieldOffset(0)] public int SignedValue;
[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 };
}
public static GlHandle Zero
{
get => new GlHandle() { Value = 0 };
}
}
}
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Graphics.OpenGL
{
[AttributeUsage(AttributeTargets.Method)]
public sealed class OpenGLAPICallingAttribute:Attribute
{
public OpenGLAPICallingAttribute()
{
}
}
}
@@ -0,0 +1,35 @@
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 SetAllUniforms();
/// <summary>
///
/// </summary>
public void GainAllUniforms(ShaderProgram source, params string[] uniformName);
/// <summary>
///
/// </summary>
public void DisplayGLtypeDefinition();
/// <summary>
///
/// </summary>
/// <returns></returns>
public ShaderStruct GetConvertedGLtype();
}
}
@@ -0,0 +1,264 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Shader.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp;
using StgSharp.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml.Linq;
namespace StgSharp.Graphics.OpenGL
{
public abstract partial class glRenderStream : RenderStream
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected sealed override Shader CreateShaderSegment(ShaderType type, int count)
{
return new Shader( GL.CreateShaderSet(count, type), type, this);
}
/// <summary>
/// Create an instance of <see cref="Shader"/> program
/// </summary>
/// <returns>New instance of <see cref="Shader"/> instance. </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected sealed override ShaderProgram CreateShaderProgram()
{
return new ShaderProgram(this);
}
}
public class Shader : ISSDSerializable
{
private readonly GlFunction GL;
internal readonly GlHandle[] handle;
public readonly ShaderType type;
public SerializableTypeCode SSDTypeCode => SerializableTypeCode.Shader;
internal unsafe Shader(GlHandle[] handle, ShaderType usage, glRenderStream stream)
{
this.handle = handle;
GL = stream.GL;
type = usage;
}
/// <summary>
/// Attach one shader code to a shader program.
/// </summary>
/// <param name="target">Shader program to attach</param>
/// <param name="index">Index of shader code in current shader code set.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AttachTo(int index, ShaderProgram target)
{
GL.AttachShader(target.handle, handle[index]);
}
public static byte[] FromCodeFile(string fileRoute)
{
string str = File.ReadAllText(fileRoute);
if (string.IsNullOrEmpty(str))
{
throw new InvalidOperationException($"Cannot load and GLSL code from {fileRoute}");
}
return Encoding.UTF8.GetBytes(str);
}
[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 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 = GL.GetShaderStatus(this,index, (int)status);
if (!string.IsNullOrEmpty(log))
{
throw new Exception($"Shader Error \t{status}\n" + log);
}
}
public byte[] GetBytes(out int length)
{
throw new NotImplementedException();
}
public void FromBytes(byte[] stream)
{
throw new NotImplementedException();
}
}
public enum ShaderStatus : int
{
CompileStatus = GLconst.COMPILE_STATUS,
}
public class ShaderProgram
{
private readonly GlFunction GL;
internal readonly GlHandle handle;
/// <summary>
/// CustomizeInit a program with no shader attached.
/// </summary>
internal unsafe ShaderProgram(glRenderStream binding)
{
GL = binding.GL;
handle = GL.CreateProgram();
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Uniform<T> GetUniform<T>(string name) where T : struct
{
return new Uniform<T>(GL.GetUniformLocation(this.handle, name));
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <returns></returns>
public unsafe Uniform<T, U> GetUniform<T, U>(string name)
where T : struct
where U : struct
{
return new Uniform<T, U>(GL.GetUniformLocation(this.handle,name));
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <returns></returns>
public unsafe Uniform<T, U, V> GetUniform<T, U, V>(string name)
where T : struct
where U : struct
where V : struct
{
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.
/// </summary>
/// <param name="name">ContextName of the Uniform in shader code</param>
/// <returns></returns>
public unsafe Uniform<T, U, V, W> GetUniform<T, U, V, W>(string name)
where T : struct
where U : struct
where V : struct
where W : struct
{
return new Uniform<T, U, V, W>(GL.GetUniformLocation(this.handle, name));
}
/// <summary>
/// Link the shader to current viewPortDisplay.
/// </summary>
public unsafe void Link()
{
if (InternalIO.InternalLinkShaderProgram((GLcontext*)this.GL.ContextHandle, handle.Value) == 0)
{
IntPtr logPtr = InternalIO.InternalReadSSCLog();
try
{
byte[] logByte = new byte[512];
Marshal.Copy(logPtr, logByte, 0, 512);
string log = Encoding.UTF8.GetString(logByte);
log = log.Replace("\0", string.Empty);
InternalIO.InternalWriteLog(log, LogType.Error);
}
catch (Exception ex)
{
InternalIO.InternalWriteLog(ex.Message, LogType.Error);
}
}
}
/// <summary>
/// Let the current viewPortDisplay use this shader.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Use()
{
GL.UseProgram(handle);
}
~ShaderProgram()
{
//handle.Dispose();
}
}
}
@@ -0,0 +1,203 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// 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 unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
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 unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
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 unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
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 unsafe Uniform(GlHandle id)
{
this.id = id;
}
internal Uniform()
{
}
internal static Uniform<T, U, V, W> FromHandle(GlHandle handle)
{
return new Uniform<T, U, V, W>() { id = handle };
}
}
public unsafe partial class GlFunction
{
[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);
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,689 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glApiManagerConst.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
{
public static partial class glManager
{
#region coreVersion
private static bool core10 = false;
private static bool core11 = false;
private static bool core12 = false;
private static bool core13 = false;
private static bool core14 = false;
private static bool core15 = false;
private static bool core20 = false;
private static bool core21 = false;
private static bool core30 = false;
private static bool core31 = false;
private static bool core32 = false;
private static bool core33 = false;
private static bool core40 = false;
private static bool core41 = false;
private static bool core42 = false;
private static bool core43 = false;
private static bool core44 = false;
private static bool core45 = false;
private static bool core46 = false;
#endregion
#region extension
private static bool _3DFX_tbuffer;
private static bool _3DFX_texture_compression_FXT1;
private static bool _4DFX_multisample;
private static bool AMD_blend_minmax_factor;
private static bool AMD_conservative_depth;
private static bool AMD_debug_output;
private static bool AMD_depth_clamp_separate;
private static bool AMD_draw_buffers_blend;
private static bool AMD_framebuffer_multisample_advanced;
private static bool AMD_framebuffer_sample_positions;
private static bool AMD_gcn_shader;
private static bool AMD_gpu_shader_half_float;
private static bool AMD_gpu_shader_int16;
private static bool AMD_gpu_shader_int64;
private static bool AMD_interleaved_elements;
private static bool AMD_multi_draw_indirect;
private static bool AMD_name_gen_delete;
private static bool AMD_occlusion_query_event;
private static bool AMD_performance_monitor;
private static bool AMD_pinned_memory;
private static bool AMD_query_buffer_object;
private static bool AMD_sample_positions;
private static bool AMD_seamless_cubemap_per_texture;
private static bool AMD_shader_atomic_counter_ops;
private static bool AMD_shader_ballot;
private static bool AMD_shader_explicit_vertex_parameter;
private static bool AMD_shader_gpu_shader_half_float_fetch;
private static bool AMD_shader_image_load_store_lod;
private static bool AMD_shader_stencil_export;
private static bool AMD_shader_trinary_minmax;
private static bool AMD_sparse_texture;
private static bool AMD_stencil_operation_extended;
private static bool AMD_texture_gather_bias_lod;
private static bool AMD_texture_texture4;
private static bool AMD_transform_feedback3_lines_triangles;
private static bool AMD_transform_feedback4;
private static bool AMD_vertex_shader_layer;
private static bool AMD_vertex_shader_tessellator;
private static bool AMD_vertex_shader_viewport_index;
private static bool APPLE_aux_depth_stencil;
private static bool APPLE_client_storage;
private static bool APPLE_element_array;
private static bool APPLE_fence;
private static bool APPLE_float_pixels;
private static bool APPLE_flush_buffer_range;
private static bool APPLE_object_purgeable;
private static bool APPLE_rgb_422;
private static bool APPLE_row_bytes;
private static bool APPLE_specular_vector;
private static bool APPLE_texture_range;
private static bool APPLE_transform_hint;
private static bool APPLE_vertex_array_object;
private static bool APPLE_vertex_array_range;
private static bool APPLE_vertex_program_evaluators;
private static bool APPLE_ycbcr_422;
private static bool ARB_arrays_of_arrays;
private static bool ARB_base_instance;
private static bool ARB_bindless_texture;
private static bool ARB_blend_func_extended;
private static bool ARB_buffer_storage;
private static bool ARB_cl_event;
private static bool ARB_clear_buffer_object;
private static bool ARB_clear_texture;
private static bool ARB_clip_control;
private static bool ARB_color_buffer_float;
private static bool ARB_compatibility;
private static bool ARB_compressed_texture_pixel_storage;
private static bool ARB_compute_shader;
private static bool ARB_compute_variable_group_size;
private static bool ARB_conditional_render_inverted;
private static bool ARB_conservative_depth;
private static bool ARB_copy_buffer;
private static bool ARB_copy_image;
private static bool ARB_cull_distance;
private static bool ARB_debug_output;
private static bool ARB_depth_buffer_float;
private static bool ARB_depth_clamp;
private static bool ARB_depth_texture;
private static bool ARB_derivative_control;
private static bool ARB_direct_state_access;
private static bool ARB_draw_buffers;
private static bool ARB_draw_buffers_blend;
private static bool ARB_draw_elements_base_vertex;
private static bool ARB_draw_indirect;
private static bool ARB_draw_instanced;
private static bool ARB_enhanced_layouts;
private static bool ARB_ES2_compatibility;
private static bool ARB_ES3_1_compatibility;
private static bool ARB_ES3_2_compatibility;
private static bool ARB_ES3_compatibility;
private static bool ARB_explicit_attrib_location;
private static bool ARB_explicit_uniform_location;
private static bool ARB_fragment_coord_conventions;
private static bool ARB_fragment_layer_viewport;
private static bool ARB_fragment_program;
private static bool ARB_fragment_program_shadow;
private static bool ARB_fragment_shader;
private static bool ARB_fragment_shader_interlock;
private static bool ARB_framebuffer_no_attachments;
private static bool ARB_framebuffer_object;
private static bool ARB_framebuffer_sRGB;
private static bool ARB_geometry_shader4;
private static bool ARB_get_program_binary;
private static bool ARB_get_texture_sub_image;
private static bool ARB_gl_spirv;
private static bool ARB_gpu_shader_fp64;
private static bool ARB_gpu_shader_int64;
private static bool ARB_gpu_shader5;
private static bool ARB_half_float_pixel;
private static bool ARB_half_float_vertex;
private static bool ARB_imaging;
private static bool ARB_indirect_parameters;
private static bool ARB_instanced_arrays;
private static bool ARB_internalformat_query;
private static bool ARB_internalformat_query2;
private static bool ARB_invalidate_subdata;
private static bool ARB_map_buffer_alignment;
private static bool ARB_map_buffer_range;
private static bool ARB_matrix_palette;
private static bool ARB_multi_bind;
private static bool ARB_multi_draw_indirect;
private static bool ARB_multisample;
private static bool ARB_multitexture;
private static bool ARB_occlusion_query;
private static bool ARB_occlusion_query2;
private static bool ARB_parallel_shader_compile;
private static bool ARB_pipeline_statistics_query;
private static bool ARB_pixel_buffer_object;
private static bool ARB_point_parameters;
private static bool ARB_point_sprite;
private static bool ARB_polygon_offset_clamp;
private static bool ARB_post_depth_coverage;
private static bool ARB_program_interface_query;
private static bool ARB_provoking_vertex;
private static bool ARB_query_buffer_object;
private static bool ARB_robust_buffer_access_behavior;
private static bool ARB_robustness;
private static bool ARB_robustness_isolation;
private static bool ARB_sample_locations;
private static bool ARB_sample_shading;
private static bool ARB_sampler_objects;
private static bool ARB_seamless_cube_map;
private static bool ARB_seamless_cubemap_per_texture;
private static bool ARB_separate_shader_objects;
private static bool ARB_shader_atomic_counter_ops;
private static bool ARB_shader_atomic_counters;
private static bool ARB_shader_ballot;
private static bool ARB_shader_bit_encoding;
private static bool ARB_shader_clock;
private static bool ARB_shader_draw_parameters;
private static bool ARB_shader_group_vote;
private static bool ARB_shader_image_load_store;
private static bool ARB_shader_image_size;
private static bool ARB_shader_objects;
private static bool ARB_shader_precision;
private static bool ARB_shader_stencil_export;
private static bool ARB_shader_storage_buffer_object;
private static bool ARB_shader_subroutine;
private static bool ARB_shader_texture_image_samples;
private static bool ARB_shader_texture_lod;
private static bool ARB_shader_viewport_layer_array;
private static bool ARB_shading_language_100;
private static bool ARB_shading_language_420pack;
private static bool ARB_shading_language_include;
private static bool ARB_shading_language_packing;
private static bool ARB_shadow;
private static bool ARB_shadow_ambient;
private static bool ARB_sparse_buffer;
private static bool ARB_sparse_texture;
private static bool ARB_sparse_texture_clamp;
private static bool ARB_sparse_texture2;
private static bool ARB_spirv_extensions;
private static bool ARB_stencil_texturing;
private static bool ARB_sync;
private static bool ARB_tessellation_shader;
private static bool ARB_texture_barrier;
private static bool ARB_texture_border_clamp;
private static bool ARB_texture_buffer_object;
private static bool ARB_texture_buffer_object_rgb32;
private static bool ARB_texture_buffer_range;
private static bool ARB_texture_compression;
private static bool ARB_texture_compression_bptc;
private static bool ARB_texture_compression_rgtc;
private static bool ARB_texture_cube_map;
private static bool ARB_texture_cube_map_array;
private static bool ARB_texture_env_add;
private static bool ARB_texture_env_combine;
private static bool ARB_texture_env_crossbar;
private static bool ARB_texture_env_dot3;
private static bool ARB_texture_filter_anisotropic;
private static bool ARB_texture_filter_minmax;
private static bool ARB_texture_float;
private static bool ARB_texture_gather;
private static bool ARB_texture_mirror_clamp_to_edge;
private static bool ARB_texture_mirrored_repeat;
private static bool ARB_texture_multisample;
private static bool ARB_texture_non_power_of_two;
private static bool ARB_texture_query_levels;
private static bool ARB_texture_query_lod;
private static bool ARB_texture_rectangle;
private static bool ARB_texture_rg;
private static bool ARB_texture_rgb10_a2ui;
private static bool ARB_texture_stencil8;
private static bool ARB_texture_storage;
private static bool ARB_texture_storage_multisample;
private static bool ARB_texture_swizzle;
private static bool ARB_texture_view;
private static bool ARB_timer_query;
private static bool ARB_transform_feedback_instanced;
private static bool ARB_transform_feedback_overflow_query;
private static bool ARB_transform_feedback2;
private static bool ARB_transform_feedback3;
private static bool ARB_transpose_matrix;
private static bool ARB_uniform_buffer_object;
private static bool ARB_vertex_array_bgra;
private static bool ARB_vertex_array_object;
private static bool ARB_vertex_attrib_64bit;
private static bool ARB_vertex_attrib_binding;
private static bool ARB_vertex_blend;
private static bool ARB_vertex_buffer_object;
private static bool ARB_vertex_program;
private static bool ARB_vertex_shader;
private static bool ARB_vertex_type_10f_11f_11f_rev;
private static bool ARB_vertex_type_2_10_10_10_rev;
private static bool ARB_viewport_array;
private static bool ARB_window_pos;
private static bool ATI_draw_buffers;
private static bool ATI_element_array;
private static bool ATI_envmap_bumpmap;
private static bool ATI_fragment_shader;
private static bool ATI_map_object_buffer;
private static bool ATI_meminfo;
private static bool ATI_pixel_format_float;
private static bool ATI_pn_triangles;
private static bool ATI_separate_stencil;
private static bool ATI_text_fragment_shader;
private static bool ATI_texture_env_combine3;
private static bool ATI_texture_float;
private static bool ATI_texture_mirror_once;
private static bool ATI_vertex_array_object;
private static bool ATI_vertex_attrib_array_object;
private static bool ATI_vertex_streams;
private static bool EXT_422_pixels;
private static bool EXT_abgr;
private static bool EXT_bgra;
private static bool EXT_bindable_uniform;
private static bool EXT_blend_color;
private static bool EXT_blend_equation_separate;
private static bool EXT_blend_func_separate;
private static bool EXT_blend_logic_op;
private static bool EXT_blend_minmax;
private static bool EXT_blend_subtract;
private static bool EXT_clip_volume_hint;
private static bool EXT_cmyka;
private static bool EXT_color_subtable;
private static bool EXT_compiled_vertex_array;
private static bool EXT_convolution;
private static bool EXT_coordinate_frame;
private static bool EXT_copy_texture;
private static bool EXT_cull_vertex;
private static bool EXT_debug_label;
private static bool EXT_debug_marker;
private static bool EXT_depth_bounds_test;
private static bool EXT_direct_state_access;
private static bool EXT_draw_buffers2;
private static bool EXT_draw_instanced;
private static bool EXT_draw_range_elements;
private static bool EXT_EGL_image_storage;
private static bool EXT_EGL_sync;
private static bool EXT_external_buffer;
private static bool EXT_fog_coord;
private static bool EXT_framebuffer_blit;
private static bool EXT_framebuffer_blit_layers;
private static bool EXT_framebuffer_multisample;
private static bool EXT_framebuffer_multisample_blit_scaled;
private static bool EXT_framebuffer_object;
private static bool EXT_framebuffer_sRGB;
private static bool EXT_geometry_shader4;
private static bool EXT_gpu_program_parameters;
private static bool EXT_gpu_shader4;
private static bool EXT_histogram;
private static bool EXT_index_array_formats;
private static bool EXT_index_func;
private static bool EXT_index_material;
private static bool EXT_index_texture;
private static bool EXT_light_texture;
private static bool EXT_memory_object;
private static bool EXT_memory_object_fd;
private static bool EXT_memory_object_win32;
private static bool EXT_misc_attribute;
private static bool EXT_multi_draw_arrays;
private static bool EXT_multisample;
private static bool EXT_multiview_tessellation_geometry_shader;
private static bool EXT_multiview_texture_multisample;
private static bool EXT_multiview_timer_query;
private static bool EXT_packed_depth_stencil;
private static bool EXT_packed_float;
private static bool EXT_packed_pixels;
private static bool EXT_paletted_texture;
private static bool EXT_pixel_buffer_object;
private static bool EXT_pixel_transform;
private static bool EXT_pixel_transform_color_table;
private static bool EXT_point_parameters;
private static bool EXT_polygon_offset;
private static bool EXT_polygon_offset_clamp;
private static bool EXT_post_depth_coverage;
private static bool EXT_provoking_vertex;
private static bool EXT_raster_multisample;
private static bool EXT_rescale_normal;
private static bool EXT_secondary_color;
private static bool EXT_semaphore;
private static bool EXT_semaphore_fd;
private static bool EXT_semaphore_win32;
private static bool EXT_separate_shader_objects;
private static bool EXT_separate_specular_color;
private static bool EXT_shader_framebuffer_fetch;
private static bool EXT_shader_framebuffer_fetch_non_coherent;
private static bool EXT_shader_image_load_formatted;
private static bool EXT_shader_image_load_store;
private static bool EXT_shader_integer_mix;
private static bool EXT_shader_samples_identical;
private static bool EXT_shadow_funcs;
private static bool EXT_shared_texture_palette;
private static bool EXT_sparse_texture2;
private static bool EXT_stencil_clear_tag;
private static bool EXT_stencil_two_side;
private static bool EXT_stencil_wrap;
private static bool EXT_subtexture;
private static bool EXT_texture;
private static bool EXT_texture_array;
private static bool EXT_texture_buffer_object;
private static bool EXT_texture_compression_latc;
private static bool EXT_texture_compression_rgtc;
private static bool EXT_texture_compression_s3tc;
private static bool EXT_texture_cube_map;
private static bool EXT_texture_env_add;
private static bool EXT_texture_env_combine;
private static bool EXT_texture_env_dot3;
private static bool EXT_texture_filter_anisotropic;
private static bool EXT_texture_filter_minmax;
private static bool EXT_texture_integer;
private static bool EXT_texture_lod_bias;
private static bool EXT_texture_mirror_clamp;
private static bool EXT_texture_object;
private static bool EXT_texture_perturb_normal;
private static bool EXT_texture_shadow_lod;
private static bool EXT_texture_shared_exponent;
private static bool EXT_texture_snorm;
private static bool EXT_texture_sRGB;
private static bool EXT_texture_sRGB_decode;
private static bool EXT_texture_sRGB_R8;
private static bool EXT_texture_sRGB_RG8;
private static bool EXT_texture_storage;
private static bool EXT_texture_swizzle;
private static bool EXT_texture3D;
private static bool EXT_timer_query;
private static bool EXT_transform_feedback;
private static bool EXT_vertex_array;
private static bool EXT_vertex_array_bgra;
private static bool EXT_vertex_attrib_64bit;
private static bool EXT_vertex_shader;
private static bool EXT_vertex_weighting;
private static bool EXT_win32_keyed_mutex;
private static bool EXT_window_rectangles;
private static bool EXT_x11_sync_object;
private static bool GREMEDY_frame_terminator;
private static bool GREMEDY_string_marker;
private static bool HP_convolution_border_modes;
private static bool HP_image_transform;
private static bool HP_occlusion_test;
private static bool HP_texture_lighting;
private static bool IBM_cull_vertex;
private static bool IBM_multimode_draw_arrays;
private static bool IBM_rasterpos_clip;
private static bool IBM_static_data;
private static bool IBM_texture_mirrored_repeat;
private static bool IBM_vertex_array_lists;
private static bool INGR_blend_func_separate;
private static bool INGR_color_clamp;
private static bool INGR_interlace_read;
private static bool INTEL_blackhole_render;
private static bool INTEL_conservative_rasterization;
private static bool INTEL_fragment_shader_ordering;
private static bool INTEL_framebuffer_CMAA;
private static bool INTEL_map_texture;
private static bool INTEL_parallel_arrays;
private static bool INTEL_performance_query;
private static bool KHR_blend_equation_advanced;
private static bool KHR_blend_equation_advanced_coherent;
private static bool KHR_context_flush_control;
private static bool KHR_debug;
private static bool KHR_no_error;
private static bool KHR_parallel_shader_compile;
private static bool KHR_robust_buffer_access_behavior;
private static bool KHR_robustness;
private static bool KHR_shader_subgroup;
private static bool KHR_texture_compression_astc_hdr;
private static bool KHR_texture_compression_astc_ldr;
private static bool KHR_texture_compression_astc_sliced_3d;
private static bool MESA_framebuffer_flip_x;
private static bool MESA_framebuffer_flip_y;
private static bool MESA_framebuffer_swap_xy;
private static bool MESA_pack_invert;
private static bool MESA_program_binary_formats;
private static bool MESA_resize_buffers;
private static bool MESA_shader_integer_functions;
private static bool MESA_tile_raster_order;
private static bool MESA_window_pos;
private static bool MESA_ycbcr_texture;
private static bool MESAX_texture_stack;
private static bool NV_alpha_to_coverage_dither_control;
private static bool NV_bindless_multi_draw_indirect;
private static bool NV_bindless_multi_draw_indirect_count;
private static bool NV_bindless_texture;
private static bool NV_blend_equation_advanced;
private static bool NV_blend_equation_advanced_coherent;
private static bool NV_blend_minmax_factor;
private static bool NV_blend_square;
private static bool NV_clip_space_w_scaling;
private static bool NV_command_list;
private static bool NV_compute_program5;
private static bool NV_compute_shader_derivatives;
private static bool NV_conditional_render;
private static bool NV_conservative_raster;
private static bool NV_conservative_raster_dilate;
private static bool NV_conservative_raster_pre_snap;
private static bool NV_conservative_raster_pre_snap_triangles;
private static bool NV_conservative_raster_underestimation;
private static bool NV_copy_depth_to_color;
private static bool NV_copy_image;
private static bool NV_deep_texture3D;
private static bool NV_depth_buffer_float;
private static bool NV_depth_clamp;
private static bool NV_draw_texture;
private static bool NV_draw_vulkan_image;
private static bool NV_evaluators;
private static bool NV_explicit_multisample;
private static bool NV_fence;
private static bool NV_fill_rectangle;
private static bool NV_float_buffer;
private static bool NV_fog_distance;
private static bool NV_fragment_coverage_to_color;
private static bool NV_fragment_program;
private static bool NV_fragment_program_option;
private static bool NV_fragment_program2;
private static bool NV_fragment_program4;
private static bool NV_fragment_shader_barycentric;
private static bool NV_fragment_shader_interlock;
private static bool NV_framebuffer_mixed_samples;
private static bool NV_framebuffer_multisample_coverage;
private static bool NV_geometry_program4;
private static bool NV_geometry_shader_passthrough;
private static bool NV_geometry_shader4;
private static bool NV_gpu_multicast;
private static bool NV_gpu_program4;
private static bool NV_gpu_program5;
private static bool NV_gpu_program5_mem_extended;
private static bool NV_gpu_shader5;
private static bool NV_half_float;
private static bool NV_internalformat_sample_query;
private static bool NV_light_max_exponent;
private static bool NV_memory_attachment;
private static bool NV_memory_object_sparse;
private static bool NV_mesh_shader;
private static bool NV_multisample_coverage;
private static bool NV_multisample_filter_hint;
private static bool NV_occlusion_query;
private static bool NV_packed_depth_stencil;
private static bool NV_parameter_buffer_object;
private static bool NV_parameter_buffer_object2;
private static bool NV_path_rendering;
private static bool NV_path_rendering_shared_edge;
private static bool NV_pixel_data_range;
private static bool NV_point_sprite;
private static bool NV_present_video;
private static bool NV_primitive_restart;
private static bool NV_primitive_shading_rate;
private static bool NV_query_resource;
private static bool NV_query_resource_tag;
private static bool NV_register_combiners;
private static bool NV_register_combiners2;
private static bool NV_representative_fragment_test;
private static bool NV_robustness_video_memory_purge;
private static bool NV_sample_locations;
private static bool NV_sample_mask_override_coverage;
private static bool NV_scissor_exclusive;
private static bool NV_shader_atomic_counters;
private static bool NV_shader_atomic_float;
private static bool NV_shader_atomic_float64;
private static bool NV_shader_atomic_fp16_vector;
private static bool NV_shader_atomic_int64;
private static bool NV_shader_buffer_load;
private static bool NV_shader_buffer_store;
private static bool NV_shader_storage_buffer_object;
private static bool NV_shader_subgroup_partitioned;
private static bool NV_shader_texture_footprint;
private static bool NV_shader_thread_group;
private static bool NV_shader_thread_shuffle;
private static bool NV_shading_rate_image;
private static bool NV_stereo_view_rendering;
private static bool NV_tessellation_program5;
private static bool NV_texgen_emboss;
private static bool NV_texgen_reflection;
private static bool NV_texture_barrier;
private static bool NV_texture_compression_vtc;
private static bool NV_texture_env_combine4;
private static bool NV_texture_expand_normal;
private static bool NV_texture_multisample;
private static bool NV_texture_rectangle;
private static bool NV_texture_rectangle_compressed;
private static bool NV_texture_shader;
private static bool NV_texture_shader2;
private static bool NV_texture_shader3;
private static bool NV_timeline_semaphore;
private static bool NV_transform_feedback;
private static bool NV_transform_feedback2;
private static bool NV_uniform_buffer_std430_layout;
private static bool NV_uniform_buffer_unified_memory;
private static bool NV_vdpau_interop;
private static bool NV_vdpau_interop2;
private static bool NV_vertex_array_range;
private static bool NV_vertex_array_range2;
private static bool NV_vertex_attrib_integer_64bit;
private static bool NV_vertex_buffer_unified_memory;
private static bool NV_vertex_program;
private static bool NV_vertex_program1_1;
private static bool NV_vertex_program2;
private static bool NV_vertex_program2_option;
private static bool NV_vertex_program3;
private static bool NV_vertex_program4;
private static bool NV_video_capture;
private static bool NV_viewport_array2;
private static bool NV_viewport_swizzle;
private static bool NVX_blend_equation_advanced_multi_draw_buffers;
private static bool NVX_conditional_render;
private static bool NVX_gpu_memory_info;
private static bool NVX_gpu_multicast2;
private static bool NVX_linked_gpu_multicast;
private static bool NVX_progress_fence;
private static bool OES_byte_coordinates;
private static bool OES_compressed_paletted_texture;
private static bool OES_fixed_point;
private static bool OES_query_matrix;
private static bool OES_read_format;
private static bool OES_single_precision;
private static bool OML_interlace;
private static bool OML_resample;
private static bool OML_subsample;
private static bool OVR_multiview;
private static bool OVR_multiview2;
private static bool PGI_misc_hints;
private static bool PGI_vertex_hints;
private static bool REND_screen_coordinates;
private static bool S3_s3tc;
private static bool SGI_color_matrix;
private static bool SGI_color_table;
private static bool SGI_texture_color_table;
private static bool SGIS_detail_texture;
private static bool SGIS_fog_function;
private static bool SGIS_generate_mipmap;
private static bool SGIS_multisample;
private static bool SGIS_pixel_texture;
private static bool SGIS_point_line_texgen;
private static bool SGIS_point_parameters;
private static bool SGIS_sharpen_texture;
private static bool SGIS_texture_border_clamp;
private static bool SGIS_texture_color_mask;
private static bool SGIS_texture_edge_clamp;
private static bool SGIS_texture_filter4;
private static bool SGIS_texture_lod;
private static bool SGIS_texture_select;
private static bool SGIS_texture4D;
private static bool SGIX_async;
private static bool SGIX_async_histogram;
private static bool SGIX_async_pixel;
private static bool SGIX_blend_alpha_minmax;
private static bool SGIX_calligraphic_fragment;
private static bool SGIX_clipmap;
private static bool SGIX_convolution_accuracy;
private static bool SGIX_depth_pass_instrument;
private static bool SGIX_depth_texture;
private static bool SGIX_flush_raster;
private static bool SGIX_fog_offset;
private static bool SGIX_fragment_lighting;
private static bool SGIX_framezoom;
private static bool SGIX_igloo_interface;
private static bool SGIX_instruments;
private static bool SGIX_interlace;
private static bool SGIX_ir_instrument1;
private static bool SGIX_list_priority;
private static bool SGIX_pixel_texture;
private static bool SGIX_pixel_tiles;
private static bool SGIX_polynomial_ffd;
private static bool SGIX_reference_plane;
private static bool SGIX_resample;
private static bool SGIX_scalebias_hint;
private static bool SGIX_shadow;
private static bool SGIX_shadow_ambient;
private static bool SGIX_sprite;
private static bool SGIX_subsample;
private static bool SGIX_tag_sample_buffer;
private static bool SGIX_texture_add_env;
private static bool SGIX_texture_coordinate_clamp;
private static bool SGIX_texture_lod_bias;
private static bool SGIX_texture_multi_buffer;
private static bool SGIX_texture_scale_bias;
private static bool SGIX_vertex_preclip;
private static bool SGIX_ycrcb;
private static bool SGIX_ycrcb_subsample;
private static bool SGIX_ycrcba;
private static bool SUN_convolution_border_modes;
private static bool SUN_global_alpha;
private static bool SUN_mesh_array;
private static bool SUN_slice_accum;
private static bool SUN_triangle_list;
private static bool SUN_vertex;
private static bool SUNX_constant_data;
private static bool WIN_phong_shading;
private static bool WIN_specular_fog;
#endregion
}
}
@@ -0,0 +1,723 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glFunction.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.Logic;
using StgSharp.Math;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp
{
internal static unsafe partial class InternalIO
{
[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);
#pragma warning restore CA5392
}
}
namespace StgSharp.Graphics.OpenGL
{
public unsafe partial class GlFunction
{
private static Dictionary<IntPtr, GlFunction> contextToGLMap = new Dictionary<IntPtr, GlFunction>();
private GLcontext* _context;
private GlFunction()
{
}
internal static GlFunction CurrentGL { get; set; }
internal IntPtr ContextHandle => (IntPtr)_context;
protected ref GLcontext Context
{
get
{
#if DEBUG
if ((IntPtr)_context == IntPtr.Zero)
{
throw new NullReferenceException();
}
#endif
return ref (*_context);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ActiveTexture(uint type)
{
Context.glActiveTexture(type);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AttachShader(GlHandle program, GlHandle shader)
{
Context.glAttachShader(program.Value, shader.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void BindBuffer(BufferType bufferType, GlHandle handle)
{
Context.glBindBuffer((uint)bufferType, handle.Value);
}
/// <summary>
/// Bind a frame buffer to a frame buffer target
/// 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 void BindFrameBuffer(FrameBufferTarget target, GlHandle handle)
{
Context.glBindFramebuffer((uint)target, handle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void BindRenderBuffer(GlHandle handle)
{
Context.glBindRenderbuffer(GLconst.RENDERBUFFER, handle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void BindTexture(uint type, GlHandle texture)
{
Context.glBindTexture(type, texture.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void BindVertexArray(GlHandle handle)
{
Context.glBindVertexArray(handle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public FrameBufferStatus CheckFrameBufferStatus(FrameBufferTarget target)
{
return (FrameBufferStatus)Context.glCheckFramebufferStatus((uint)target);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear(MaskBufferBit mask)
{
Context.glClear((uint)mask);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void ClearColor(float R, float G, float B, float A)
{
Context.glClearColor(R, G, B, A);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ClearError()
{
while (Context.glGetError() != 0) { }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GenerateMipmap(Texture2DTarget target)
{
Context.glGenerateMipmap((uint)target);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void ClearGraphicError()
{
while (Context.glGetError() != 0) { }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CombineFrameBufferRenderBuffer(GlHandle fboHandle, GlHandle rboHandle)
{
Context.glFramebufferRenderbuffer(GLconst.FRAMEBUFFER, fboHandle.Value, GLconst.RENDERBUFFER, rboHandle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CompileShader(GlHandle shaderhandle)
{
Context.glCompileShader(shaderhandle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe GlHandle CreateGraphicProgram()
{
return GlHandle.Alloc(Context.glCreateProgram());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public GlHandle CreateProgram()
{
return GlHandle.Alloc(Context.glCreateProgram());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe GlHandle[] CreateProgram(int count)
{
GlHandle[] h = new GlHandle[count];
for (int i = 0; i < count; i++)
{
h.SetValue(i, Context.glCreateProgram());
}
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public GlHandle[] CreateShaderSet(int count, ShaderType type)
{
GlHandle[] ret = new GlHandle[count];
uint t = (uint)type;
for (int i = 0; i < count; i++)
{
uint id = Context.glCreateShader(t);
if (id == 0)
{
uint error = Context.glGetError();
throw new InvalidOperationException($"Failed in creating shader: {error}");
}
ret[i] = GlHandle.Alloc(id);
}
return ret;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void DeleteBuffer(GlHandle handle)
{
Context.glDeleteBuffers(1, (uint*)&handle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void DeleteBuffers(GlHandle[] handle)
{
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 unsafe void DeleteVertexArrays(GlHandle[] arrays)
{
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 unsafe void DrawElements(GeometryType mode, uint count, TypeCode type, IntPtr ptr)
{
uint a;
a = type switch
{
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 void DrawElementsInstanced(
GeometryType mode, uint count, TypeCode type, IntPtr ptr, uint amount
)
{
uint a;
switch (type)
{
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;
}
Context.glDrawElementsInstanced((uint)mode, count, a, (void*)ptr, amount);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Enable(GLOperation operation)
{
Context.glEnable((uint)operation);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public 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 unsafe GlHandle[] GenBuffers(int count)
{
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 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)
{
return Marshal.PtrToStringAnsi(sptr);
}
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 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 == GLconst.INVALID_OPERATION) ||
(ret == GLconst.INVALID_VALUE))
{
throw new InvalidOperationException();
}
if (ret == -1)
{
throw new UniformEmptyReferenceException(nameof(program), name);
}
#endif
return GlHandle.SignedAlloc(ret);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void LoadShaderSource(GlHandle shaderHandle, byte[] codeStream)
{
fixed (byte* streamPtr = codeStream)
{
Context.glShaderSource(shaderHandle.Value, 1, &streamPtr, (void*)0);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
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);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void SetBufferData<T>(BufferType bufferType, T bufferData, BufferUsage usage)
where T : struct
{
int size = Marshal.SizeOf<T>();
#pragma warning disable CS8500
T* p = &bufferData;
#pragma warning restore CS8500
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)p,
(uint)usage);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void SetBufferData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = bufferArray)
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void SetBufferData<T>(BufferType bufferType, ReadOnlySpan<T> bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = bufferArray)
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void SetBufferData<T>(BufferType bufferType, Span<T> bufferArray, BufferUsage usage)
where T : struct,
#if NET8_0_OR_GREATER
INumber
#else
IConvertible
#endif
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = &bufferArray.GetPinnableReference())
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void SetBufferVectorData<T>(BufferType bufferType, ReadOnlySpan<T> bufferArray, BufferUsage usage)
where T : struct, IVector
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = &bufferArray.GetPinnableReference())
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void SetBufferVectorData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
where T : struct, IVector
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
{
return;
}
#pragma warning disable CS8500
fixed (void* bufferPtr = bufferArray)
#pragma warning restore CS8500
{
Context.glBufferData(
(uint)bufferType,
(IntPtr)size,
(IntPtr)bufferPtr,
(uint)usage);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
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);
Context.glEnableVertexAttribArray(index);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
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
{
#pragma warning disable CS8500
fixed (T* tptr = ((pixels == null) || (pixels.Length == 0)) ? pixels : null)
{
Context.glTexImage2D(
(uint)target, level, internalformat, width, height, 0, format, (uint)type, tptr);
}
#pragma warning restore CS8500
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
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
{
#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 void TextureParameter(int target, uint pname, int param)
{
Context.glTexParameteri((uint)target, pname, param);
}
public static bool TryGetFunctionPackage(IntPtr handle, out GlFunction functionPackage)
{
return contextToGLMap.TryGetValue(handle, out functionPackage);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void UseProgram(GlHandle program)
{
Context.glUseProgram(program.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void VertexAttributeDivisor(uint layoutIndex, uint divisor)
{
Context.glVertexAttribDivisor(layoutIndex, divisor);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Viewport(int x, int y, uint width, uint height)
{
Context.glViewport(x, y, width, height);
}
public void WaitAccomplishment()
{
Context.glFinish();
}
internal static GlFunction BuildGlFunctionPackage(IntPtr handle)
{
GlFunction pack;
if (contextToGLMap.TryGetValue(handle, out pack))
{
return pack;
}
pack = new GlFunction { _context = (GLcontext*)handle };
contextToGLMap.Add(handle, pack);
return pack;
}
~GlFunction()
{
contextToGLMap.Remove(ContextHandle);
}
}
}
@@ -0,0 +1,145 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="glRenderStream.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.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.OpenGL
{
public abstract partial class glRenderStream : RenderStream
{
private GlFunction _context;
internal protected GlFunction GL
{
get { return _context; }
}
/// <summary>
/// Init 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 viewPortDisplay.
/// </exception>
public unsafe void MakeAsCurrentContext()
{
if (ContextHandle == default)
{
ContextHandle = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GLcontext)));
GLcontext* contextID = (GLcontext*)ContextHandle;
contextID->glGetString = (delegate*<uint, IntPtr>)IntPtr.Zero;
}
if (GL == null)
{
_context = GlFunction.BuildGlFunctionPackage(ContextHandle);
}
if (GlFunction.CurrentGL != GL)
{
GlFunction.CurrentGL = GL;
InternalIO.glfwMakeContextCurrent(CanvasHandle);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void SetSizeLimit(int minWidth, int minHeight, int maxWidth, int maxHeight)
{
InternalIO.glfwSetWindowSizeLimits(this.CanvasHandle, minWidth, minHeight, maxWidth, maxHeight);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal override sealed void Draw()
{
MakeAsCurrentContext();
Main();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal override sealed void PlatformSpecifiedInit()
{
MakeAsCurrentContext();
glManager.LoadOpenGLApiTo(Port.GraphicHandle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal override sealed void Terminate()
{
CustomizeDeinit();
}
protected override sealed Uniform<Matrix44> NativeCameraUniform(ShaderProgram source, string name)
{
NativeCamera.GainAllUniforms(source, name);
return NativeCamera.convertedUniform;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override sealed void NativeCameraViewRange(Radius fieldOfRange, vec2d offset, (float frontDepth, float backDepth) viewDepth)
{
NativeCamera.SetViewRange(fieldOfRange, this.Size, offset, viewDepth);
}
protected override sealed void NativeCameraViewTarget(vec3d position, vec3d direction, vec3d up)
{
NativeCamera.SetViewDirection(position, direction, up);
}
#region Key Control
protected KeyStatus CheckKey(KeyboardKey key)
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
}
protected KeyStatus CheckKey(Mouse key)
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
}
protected KeyStatus CheckKey(Joystick key)
{
return InternalIO.glfwGetKey(this.CanvasHandle, (int)key);
}
#endregion
}
}
+30
View File
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics
{
public interface IPixel
{
internal int Size { get; }
public float Red { get; set; }
public float Green { get; set; }
public float Blue { get; set; }
public float Alpha { get; set; }
}
[StructLayout(LayoutKind.Explicit,Size = 32)]
public unsafe struct Pixel32
{
[FieldOffset(0)]private unsafe fixed byte data[4];
internal int Size => 4;
}
}
@@ -3,7 +3,9 @@ using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace StgSharp.Graphics
@@ -11,11 +13,11 @@ namespace StgSharp.Graphics
public class PlainGeometryMesh
{
private PlainGeometry _shape;
private Image _texture;
private vec4d[] textureCoord;
private TextureProvider _texture;
//private Image _texture;
public PlainGeometryMesh(
PlainGeometry shape, Image texture, vec4d[] texCoord
PlainGeometry shape, Image texture, vec2d[] texCoord
)
{
if (shape==null)
@@ -27,19 +29,25 @@ namespace StgSharp.Graphics
throw new ArgumentNullException(nameof(texCoord));
}
_shape = shape;
_texture = texture;
if (shape.VertexCount > texCoord.Length)
{
throw new ArgumentException(paramName: nameof(texCoord), message: "Amount of texture coordination is too less");
}
textureCoord = texCoord;
return;
_texture = new TextureProvider(texture,texCoord);
}
public PlainGeometryMesh([NotNull]PlainGeometry shape, [NotNull]TextureProvider texture)
{
if (shape.VertexCount > texture.TextureCoordinate.Length)
{
throw new ArgumentException(paramName: nameof(texture), message: "Amount of texture coordination is too less");
}
_shape = shape;
}
public PlainGeometryMesh Resize(PlainGeometry newShape)
{
return new PlainGeometryMesh(newShape, _texture, textureCoord);
return new PlainGeometryMesh(newShape, _texture);
}
public ReadOnlySpan<int> MeshIndices => _shape.VertexIndices;
@@ -48,10 +56,10 @@ namespace StgSharp.Graphics
public Image TextureImage
{
get => _texture;
internal set => _texture = value;
get => _texture.ProvideImage();
internal set => _texture.ReadImage( value);
}
public vec4d[] TextureCoord => textureCoord;
public ReadOnlySpan<vec4d> TextureCoord => MemoryMarshal.Cast<vec2d,vec4d>( _texture.TextureCoordinate);
}
}
+39 -42
View File
@@ -28,7 +28,7 @@
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using StgSharp.Logic;
using StgSharp.Math;
@@ -43,30 +43,18 @@ using System.Threading.Tasks;
namespace StgSharp.Graphics
{
public abstract class RenderStream : IConvertableToBlueprintNode
public abstract class RenderStream
{
private protected (int x, int y, int z) _coordStretch;
private Camera nativeCamera;
private ViewPort primeArgs;
private protected ViewPort primeArgs;
internal TimeSpanProvider timeProvider;
public RenderStream(ViewPort v, (int, int, int) unitCubeSize)
{
if (v == null)
{
throw new ArgumentNullException(nameof(v));
}
primeArgs = v;
_coordStretch = unitCubeSize;
nativeCamera = new Camera();
}
public (int width, int height) Size
{
get => (Width, Height);
@@ -78,12 +66,6 @@ namespace StgSharp.Graphics
}
}
public string[] InputInterfacesName => InputPortsName;
public string[] OutputInterfacesName => OutputPortsName;
public int Height
{
get => primeArgs.Height;
@@ -102,6 +84,11 @@ namespace StgSharp.Graphics
internal set => primeArgs.Monitor = value;
}
public abstract bool IsContextSharable
{
get;
}
public string Name
{
get => primeArgs.Name;
@@ -131,10 +118,13 @@ namespace StgSharp.Graphics
get => timeProvider.CurrentSpan;
}
protected abstract string[] InputPortsName { get; }
protected abstract string[] OutputPortsName { get; }
protected float TimePassed
{
get => timeProvider.CurrentSecond;
}
protected float FramePassed
{
get => timeProvider.CurrentSpan;
}
@@ -154,7 +144,7 @@ namespace StgSharp.Graphics
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public abstract void SetSizeLimit(int minWidth, int minHeight, int maxWidth, int maxHeight);
public static TTarget ShareContextWith<TSource, TTarget>(TSource source)
public static TTarget ShareContextFrom<TSource, TTarget>(TSource source)
where TSource : RenderStream
where TTarget : RenderStream
{
@@ -168,15 +158,10 @@ namespace StgSharp.Graphics
);
}
target.timeProvider = source.timeProvider;
target.InternalInit();
target.PlatformSpecifiedInit();
return target;
}
public void ExecuteMain(in Dictionary<string, BlueprintPipeline> input, in Dictionary<string, BlueprintPipeline> output)
{
InternalDraw(in input, in output);
}
internal protected static void PollEvents()
{
InternalIO.glfwPollEvents();
@@ -191,7 +176,7 @@ namespace StgSharp.Graphics
protected abstract void NativeCameraViewRange(Radius fieldOfRange, vec2d offset, (float frontDepth, float backDepth) viewDepth);
protected abstract void NativeCameraViewTarget(vec3d position, vec3d direction, vec3d up);
/// <summary>
/// Get <see cref="Uniform{T}"/>(T is <see cref="Matrix44"/>) uniform from a shader.
/// Get <see cref="Uniform{T}"/>(TView is <see cref="Matrix44"/>) uniform from a shader.
/// This uniform will be used as projection matrix of this camera.
/// Additionally, for multi-shader rendering, each shader requires a uniform,
/// so do not ignore return value of this method.
@@ -199,26 +184,38 @@ namespace StgSharp.Graphics
/// <param name="source">Shader using this camera</param>
/// <param name="name">ContextName of projection camera named in shader</param>
/// <returns>
/// <see cref="Uniform{T}"/>(T is <see cref="Matrix44"/>) representing
/// <see cref="Uniform{T}"/>(TView is <see cref="Matrix44"/>) representing
/// projection matrix in shader program.
/// </returns>
protected abstract Uniform<Matrix44> NativeCameraUniform(ShaderProgram source, string name);
#endregion
#region internal operation
internal abstract void InternalDraw(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output);
internal abstract void InternalInit();
internal abstract void InternalTerminate();
internal abstract void Draw();
public void Init(ViewPort v, (int, int, int) unitCubeSize)
{
if (v == null)
{
throw new ArgumentNullException(nameof(v));
}
primeArgs = v;
_coordStretch = unitCubeSize;
nativeCamera = new Camera();
PlatformSpecifiedInit();
CustomizeInit();
}
internal abstract void PlatformSpecifiedInit();
internal abstract void Terminate();
#endregion
#region public operation
protected abstract void Deinit();
protected abstract void Init();
protected abstract void Main(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output);
protected abstract void CustomizeDeinit();
protected abstract void CustomizeInit();
protected abstract void Main();
#endregion
@@ -29,7 +29,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using StgSharp.Math;
using System;
@@ -51,7 +51,7 @@ namespace StgSharp.Graphics.ShaderEdit
{
ShaderParameter p = new ShaderParameter(name,ShaderParameter.TypeMarshal<T>());
uniformDefine.Add(index,p);
//return new Uniform<T>();
//return new Uniform<TView>();
throw new NotImplementedException();
}
@@ -1,4 +1,4 @@
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
@@ -16,11 +16,11 @@ namespace StgSharp.Graphics.ShaderEdit
public class ShaderStruct
{
internal Dictionary<glSHandle, ShaderStructMember> uniformPair;
internal Dictionary<GlHandle, ShaderStructMember> uniformPair;
public ShaderStruct(params (glSHandle, ShaderStructMember)[] uniformPairs)
public ShaderStruct(params (GlHandle, ShaderStructMember)[] uniformPairs)
{
uniformPair = new Dictionary<glSHandle, ShaderStructMember>();
uniformPair = new Dictionary<GlHandle, ShaderStructMember>();
if (uniformPairs.Length == 0)
{
return;
@@ -38,10 +38,10 @@ namespace StgSharp.Graphics.ShaderEdit
public unsafe void SetAllUniforms()
{
GLcontext* gl = (GLcontext*) glFunc.CurrentContextHandle;
GLcontext* gl = (GLcontext*)OpenGL.GlFunction.CurrentGL.ContextHandle;
foreach (var uniform in uniformPair)
{
int id = uniform.Key.Value;
int id = uniform.Key.SignedValue;
ShaderStructMember s = uniform.Value;
switch (s.type)
{
@@ -0,0 +1,42 @@
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace StgSharp.Graphics
{
public class TextureProvider : IImageProvider
{
private Image _tex;
private vec2d[] _texCoord;
public Span<vec2d> TextureCoordinate
{
get => new Span<vec2d>(_texCoord);
}
public Image ProvideImage()
{
return _tex;
}
public TextureProvider(Image image, vec2d[] coord)
{
_tex = image;
_texCoord = coord;
}
public ref vec2d this[int index]
{
get => ref _texCoord[index];
}
public void ReadImage(IImageProvider provider)
{
_tex = provider.ProvideImage();
}
}
}
+104 -11
View File
@@ -31,6 +31,8 @@
using StgSharp.Logic;
using StgSharp.Math;
using StgSharpDebug.Logic;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -39,37 +41,66 @@ using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace StgSharp.Graphics
{
/// <summary>
///
/// View is the base type for all view types, providing context binding and control element binding.
/// A complete view should contain one complete <see cref="ViewDesigner{T}"/>, <see cref="ViewRender{TView}"/>, and <see cref="ViewResponder"/>,
/// which provide layout descriptions of control elements, user responses, and rendering implementations in the view.
/// Data between instances of <see cref="ViewDesigner{T}"/>, <see cref="ViewRender{TView}"/>, and <see cref="ViewResponder{T}"/> is shared through <see cref="ViewBase"/>.
/// </summary>
public unsafe partial class View
public abstract unsafe partial class View
{
private delegate bool GetDataBindingEntryDelegate(string name, out DataBindingEntry entry);
private (int x, int y, int z) unitCubeSize;
private TimeSpanProvider time;
private ViewPort context;
private GetDataBindingEntryDelegate getDataBindingEntry;
private ViewPortDesigner design;
private ViewPort context;
private ViewDesigner<View> _design;
private ViewRender<View> _render;
private ViewResponder<View> _responder;
public View(ViewPort vp, ViewPortDesigner design)
public View()
{
}
public View(ViewPort vp)
{
context = vp;
unitCubeSize = (1, 1, 1);
localLogic = new Logic.Blueprint();
this.design = design;
SelfName = string.Empty;
}
public View(ViewPort vp, ViewPortDesigner design, (int, int, int) cubeSize)
public View(ViewPort vp, (int, int, int) cubeSize)
{
context = vp;
unitCubeSize = cubeSize;
localLogic = new Logic.Blueprint();
SelfName = string.Empty;
}
public DataBindingEntry this[string name]
{
get
{
if (TryGetObjectReference(name, out DataBindingEntry entry))
{
return entry;
}
if (getDataBindingEntry(name, out entry))
{
return entry;
}
throw new KeyNotFoundException();
}
}
public (int x, int y, int z) UnitCubeSize
@@ -82,13 +113,13 @@ namespace StgSharp.Graphics
public int Height
{
get => context.Height;
internal set { context.Height = value; }
private set { context.Height = value; }
}
public int Width
{
get => context.Width;
internal set { context.Width = value; }
private set { context.Width = value; }
}
public IntPtr Monitor => context.Monitor;
@@ -99,11 +130,73 @@ namespace StgSharp.Graphics
public string SelfName { get; set; }
public ViewDesigner<View> Designer
{
get => _design;
protected set => _design = value;
}
public ViewPort Port
{
get => context;
}
public ViewRender<View> Render
{
get => _render;
protected set => _render = value;
}
public ViewResponder<View> Responder
{
get => _responder;
protected set => _responder = value;
}
/// <summary>
/// Get the status of a certain key on the keyboard.
/// </summary>
/// <param name="key"></param>
/// <returns><see cref="KeyStatus"/> representing if a key is pressed or released.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public KeyStatus GetKeyStatus(KeyboardKey key)
{
return InternalIO.glfwGetKey(context.ViewPortID, (int)key);
}
public abstract bool TryGetObjectReference(string name, out DataBindingEntry entry);
private int usedFrame = 0;
public void Use()
{
if (usedFrame == 0)
{
ValidateInitialization();
}
}
internal TimeSpanProvider TimeProvider
{
get => time;
}
public bool ValidateInitialization()
{
return _design != null && _render != null && getDataBindingEntry != null && _responder != null;
}
internal protected abstract void Show();
public void InternalInitialize(ViewModelBase viewModelBinding)
{
getDataBindingEntry = viewModelBinding.TryGetObjectReference;
context = viewModelBinding.ViewPortBinding;
time = viewModelBinding.frameTimeProvider;
}
public abstract void CustomizedInitialize(ViewModelBase viewModelBinding);
}
}
@@ -0,0 +1,95 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="FormThreading.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.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace StgSharp.Graphics
{
public abstract class ViewRender<TView>
where TView:View
{
private TView _binding;
protected ViewModelBase ModelBinding { get; set; }
private Dictionary<string, RenderStream> _render;
public TView Binding => _binding;
protected ViewDesigner<TView> Design => _binding.Designer as ViewDesigner<TView>;
protected ViewResponder<TView> Responder => _binding.Responder as ViewResponder<TView>;
protected Dictionary<string, RenderStream> Render
{
get => _render;
}
protected ViewPort ContextBinding;
public T BuildNewRenderStream<T>(ViewPort arg, (int x, int y, int z) unitCubeSize) where T : RenderStream,new()
{
T ret = new T();
ret.Init(arg, unitCubeSize);
ret.timeProvider = this.Binding.TimeProvider;
return ret;
}
public RenderStream this[string renderName]
{
get => _render.TryGetValue(renderName, out RenderStream stream) ? stream : null;
internal set
{
if (_render.ContainsKey(renderName))
{
_render[renderName] = value;
}
else
{
_render.Add(renderName, value);
}
}
}
public abstract void CustomizedInitialize();
public abstract bool ValidateInitializing();
}
}
+6 -1
View File
@@ -36,7 +36,6 @@ namespace StgSharp
{
public class TimeFunction
{
private float _beginning, _ending;
private Func<float, float> _timeRelatedCalculation;
private TimeSpanProvider _timeProvider;
@@ -106,6 +105,12 @@ namespace StgSharp
return new TimeFunction(_timeProvider, func, range);
}
public virtual TimeFunction Reverse()
{
float range = _ending - _beginning;
return new TimeFunction(_timeProvider, p => _timeRelatedCalculation(range - p) ,range);
}
public void Reset()
{
float range = _ending - _beginning;
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace StgSharpDebug.Logic
{
#nullable enable
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate ref object BindingDataGetter();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void BindingDataSetter(ref object value);
public unsafe struct DataBindingEntry
{
private IntPtr getterPtr, setterPtr;
public DataBindingEntry(
[NotNull] BindingDataGetter gettingCallback,
[NotNull] BindingDataSetter settingCallback)
{
getterPtr = Marshal.GetFunctionPointerForDelegate(gettingCallback);
setterPtr = Marshal.GetFunctionPointerForDelegate(settingCallback);
}
public ref object GetValue()
{
return ref ((delegate* unmanaged[Cdecl]<ref object>)getterPtr)();
}
public void SetData(ref object value)
{
((delegate* unmanaged[Cdecl]<ref object, void>)setterPtr)(ref value);
}
public static DataBindingEntry NullBinding
{
get => new DataBindingEntry();
}
public bool ExactEqual(DataBindingEntry other)
{
return getterPtr == other.getterPtr && setterPtr == other.setterPtr;
}
}
#nullable restore
}
@@ -9,40 +9,35 @@ namespace StgSharp.Logic
{
public abstract partial class ViewModelBase
{
public void ShowViewPort()
{
private View _nextView, _currentView;
protected View CurrentView
{
get => _currentView;
set => _nextView = value;
}
private Blueprint renderLogic;
/// <summary>
/// Render logic for every frame with no relation to <see cref="View"/>.
/// </summary>
public Blueprint GeneralRenderLogic
protected void UseViewInNextFrame(string name)
{
get => renderLogic;
set => renderLogic = value;
if (allView.TryGetValue(name, out View v))
{
throw new KeyNotFoundException($"Cannot find View named {name} " +
$"in current View Model of {this.GetType().FullName}");
}
CurrentView = v;
}
/// <summary>
/// Init this form and render it on screen, and respond with operation
/// CustomizeInit this form and render it on screen, and respond with operation
/// </summary>
public unsafe void Show()
{
BuildGlobalKeyControl();
CustomizeInitialize();
//BuildGlobalKeyControl();
while(0 == InternalIO.glfwWindowShouldClose(this.viewPortDisplay.ViewPortID))
{
viewPortDisplay.FlushSize();
foreach (var item in this._globalKeyAction)
{
if (InternalIO.glfwGetKey(this.viewPortDisplay.ViewPortID, (int)item.Key.TargetKeyOrButtonID)
== item.Key.TriggeredStatus)
{
item.Value();
}
}
BlueprintRunner.Run(renderLogic, ()=>ShouldClose);
CurrentView.Use();
RenderStream.PollEvents();
frameTimeProvider.WaitNextSpan();
Interlocked.Add(ref _frameCount, 1);
@@ -53,36 +48,10 @@ namespace StgSharp.Logic
{
if(0 == InternalIO.glfwWindowShouldClose(this.viewPortDisplay.ViewPortID))
{
frameTimeProvider.WaitNextSpan();
Interlocked.Add(ref _frameCount, 1);
viewPortDisplay.FlushSize();
foreach (var item in this._globalKeyAction)
{
if (InternalIO.glfwGetKey(this.viewPortDisplay.ViewPortID, (int)item.Key.TargetKeyOrButtonID)
== item.Key.TriggeredStatus)
{
item.Value();
}
}
BlueprintRunner.Run(renderLogic, () => ShouldClose);
CurrentView.Use();
RenderStream.PollEvents();
}
}
public T BuildNewRenderStream<T>(View arg, (int x, int y, int z) unitCubeSize) where T : RenderStream
{
if (arg.ContextName == this.Name)
{
}
T? ret = Activator.CreateInstance(typeof(T), arg) as T;
if (ret == null)
{
throw new InvalidOperationException("Failed in building a new RenderStream when calling AsMainStreamOf");
}
ret!.InternalInit();
ret.timeProvider = this.frameTimeProvider;
return ret;
}
}
}
@@ -1,31 +1,40 @@
using StgSharp.Graphics;
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Text;
namespace StgSharp.Logic
{
public partial class ViewModelBase
{
private List<View> allView;
private Dictionary<string,View> allView;
public View BuildNewView(
ViewPortDesigner designer, (int x, int y, int z) unitCubeSize
)
public T BuildNewView<T>(string name,(int x, int y, int z) unitCubeSize)
where T : View,new()
{
View ret = new View(this.viewPortDisplay, designer,unitCubeSize);
allView.Add(ret);
var ret = new T();
ret.SelfName = name;
ret.InternalInitialize(this);
allView.Add(name, ret);
return ret;
}
public T BuildRenderStream<T>(View view) where T : RenderStream
{
T ret = Activator.CreateInstance(typeof(T), view.Port, view.UnitCubeSize) as T ??
throw new InvalidOperationException("Cannot build new render stream.");
#nullable enable
T? ret = Activator.CreateInstance(typeof(T), view.Port, view.UnitCubeSize) as T;
#nullable restore
if (ret == null)
{
throw new InvalidOperationException(
$"Failed in creating a new {typeof(T).Name} instance when calling ShareContextWith."
);
}
ret.timeProvider = this.frameTimeProvider;
ret.InternalInit();
ret.PlatformSpecifiedInit();
return ret;
}
}
+115 -62
View File
@@ -30,13 +30,16 @@
//-----------------------------------------------------------------------
using StgSharp.Controlling.UsrActivity;
using StgSharp.Graphics;
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using StgSharp.Math;
using StgSharpDebug.Logic;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
@@ -64,7 +67,7 @@ namespace StgSharp.Logic
size: (800, 600),
monitor: IntPtr.Zero
);
allView = new List<View>();
allView = new();
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
@@ -77,13 +80,35 @@ namespace StgSharp.Logic
() =>
{
};
_globalKeyAction = new Dictionary<KeyTrigger, Action>();
}
protected ViewModelBase(float frameLength)
{
viewPortDisplay = new ViewPort(
name: "Hello, Stg#!",
size: (800, 600),
monitor: IntPtr.Zero
);
allView = new();
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
fpsCountProvider.SpanRefreshCallback = CountFps;
long _frameLength = (FrameSpeed > 0) ? ((long)(1000 * frameLength)) : 0;
frameTimeProvider = new TimeSpanProvider(
_frameLength, TimeSpanProvider.DefaultProvider
);
frameTimeProvider.SpanRefreshCallback =
() =>
{
};
}
public ViewModelBase(ViewPort vbinding, int framespeed)
{
viewPortDisplay = vbinding;
allView = new List<View>();
allView = new();
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
@@ -96,12 +121,11 @@ namespace StgSharp.Logic
() =>
{
};
_globalKeyAction = new Dictionary<KeyTrigger, Action>();
viewPortDisplay.FrameSizeCallback = (handle, width, height)
=>
{
InternalIO.glfwMakeContextCurrent(viewPortDisplay.ViewPortID);
glFunc.Viewport(0, 0, width, height);
GlFunction.CurrentGL.Viewport(0, 0, width, height);
PrivateShow();
};
viewPortDisplay.FramePostionCallback = (handle, xpos, ypos)
@@ -111,14 +135,41 @@ namespace StgSharp.Logic
};
}
private void CountFps()
public ViewModelBase(ViewPort vbinding, float frameLength)
{
/**/
Console.Clear();
Console.WriteLine(FrameSpeed);
/**/
Interlocked.Exchange(ref _frameSpeed, _frameCount);
Interlocked.Exchange(ref _frameCount, 0);
viewPortDisplay = vbinding;
allView = new();
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
fpsCountProvider.SpanRefreshCallback = CountFps;
long _frameLength = (frameLength > 0) ? ((long)(1000 * frameLength)) : 0;
frameTimeProvider = new TimeSpanProvider(
_frameLength, TimeSpanProvider.DefaultProvider
);
frameTimeProvider.SpanRefreshCallback =
() =>
{
};
viewPortDisplay.FrameSizeCallback = (handle, width, height)
=>
{
InternalIO.glfwMakeContextCurrent(viewPortDisplay.ViewPortID);
GlFunction.CurrentGL.Viewport(0, 0, width, height);
PrivateShow();
};
viewPortDisplay.FramePostionCallback = (handle, xpos, ypos)
=>
{
PrivateShow();
};
}
public bool ShouldClose
{
get => InternalIO.glfwWindowShouldClose(viewPortDisplay.ViewPortID) != 0;
set => InternalIO.glfwSetWindowShouldClose(viewPortDisplay.ViewPortID, value ? 1 : 0);
}
public int CurrentFrameCount => frameTimeProvider.CurrentSpan;
@@ -134,17 +185,37 @@ namespace StgSharp.Logic
set { viewPortDisplay.Height = value; }
}
/// <summary>
/// Width of this form, represent in <see cref="int"/>
/// </summary>
public int Width
{
get => viewPortDisplay.Width;
set
{
viewPortDisplay.Width = value;
if (WindowID != IntPtr.Zero)
{
InternalIO.glfwSetWindowSize(viewPortDisplay.ViewPortID, Width, Height);
}
}
}
public ViewPort ViewPortBinding
{
get => viewPortDisplay;
}
public unsafe IntPtr WindowID
{
get => viewPortDisplay.ViewPortID;
}
public string Name
{
get => viewPortDisplay.Name;
}
public bool ShouldClose
{
get => InternalIO.glfwWindowShouldClose(viewPortDisplay.ViewPortID) != 0;
set => InternalIO.glfwSetWindowShouldClose(viewPortDisplay.ViewPortID, value ? 1 : 0);
}
/// <summary>
/// Width of this form, represent in <see cref="int"/>
/// </summary>
@@ -162,28 +233,6 @@ namespace StgSharp.Logic
}
}
/// <summary>
/// Width of this form, represent in <see cref="int"/>
/// </summary>
public int Width
{
get => viewPortDisplay.Width;
set
{
viewPortDisplay.Width = value;
if (WindowID != IntPtr.Zero)
{
InternalIO.glfwSetWindowSize(viewPortDisplay.ViewPortID, Width, Height);
}
}
}
public unsafe IntPtr WindowID
{
get => viewPortDisplay.ViewPortID;
}
#pragma warning disable CA1044
protected FrameBufferSizeHandler FrameSizeCallback
{
@@ -196,6 +245,14 @@ namespace StgSharp.Logic
#pragma warning restore CA1044
public abstract bool TryGetObjectReference(string name,out DataBindingEntry entry);
public Action MethodLookup(string methodName)
{
MethodInfo method = GetType().GetMethod(methodName);
return (method != null) ? ((Action)Delegate.CreateDelegate(typeof(Action), this, method)) : null;
}
/// <summary>
/// Resize the current form
/// </summary>
@@ -209,7 +266,6 @@ namespace StgSharp.Logic
InternalIO.glfwSetWindowSize(this.viewPortDisplay.ViewPortID, (int)size.X, (int)size.Y);
}
/// <summary>
/// Set the size limit of current form
/// </summary>
@@ -244,33 +300,30 @@ namespace StgSharp.Logic
InternalIO.glfwSetWindowSizeLimits(this.viewPortDisplay.ViewPortID, minWidth, minHeight, maxWidth, maxHeight);
}
#region Key Control
protected KeyStatus CheckKey(KeyboardKey key)
private void CountFps()
{
return InternalIO.glfwGetKey(this.WindowID, (int)key);
/**/
Console.Clear();
Console.WriteLine(FrameSpeed);
/**/
Interlocked.Exchange(ref _frameSpeed, _frameCount);
Interlocked.Exchange(ref _frameCount, 0);
}
protected KeyStatus CheckKey(Mouse key)
public DataBindingEntry this[string name]
{
return InternalIO.glfwGetKey(this.WindowID, (int)key);
get
{
if (this.TryGetObjectReference(name, out DataBindingEntry entry))
{
return entry;
}
throw new KeyNotFoundException();
}
}
protected KeyStatus CheckKey(Joystick key)
{
return InternalIO.glfwGetKey(this.WindowID, (int)key);
}
public abstract void CustomizeInitialize();
#endregion
protected abstract void BuildGlobalKeyControl();
private Dictionary<KeyTrigger, Action> _globalKeyAction;
protected Dictionary<KeyTrigger, Action> GlobalKeyAction
{
get => _globalKeyAction;
}
}
}
+3 -3
View File
@@ -29,7 +29,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using StgSharp.Graphics.ShaderEdit;
using StgSharp.Math;
@@ -116,7 +116,7 @@ namespace StgSharp.Graphics
{
if (uniformName.Length != 1)
{
throw new ArgumentException();
throw new ArgumentException("Camera needs only one uniform.", nameof(uniformName));
}
convertedUniform = source.GetUniform<Matrix44>(uniformName[0]);
}
@@ -143,7 +143,7 @@ namespace StgSharp.Graphics
public unsafe void SetAllUniforms()
{
//Console.WriteLine(Projection * View);
glFunc.SetUniformValue(convertedUniform, Projection * View);
OpenGL.GlFunction.CurrentGL.SetUniformValue(convertedUniform, Projection * View);
}
public void SetViewDirection(vec3d position, vec3d target, vec3d up)
+50 -75
View File
@@ -31,7 +31,7 @@
using StgSharp.Data;
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using StgSharp.Logic;
using StgSharp.Math;
@@ -45,23 +45,12 @@ using System.Threading.Tasks;
namespace StgSharp.Stg
{
public class CollisionTextureInput : BlueprintPipelineArgs
public interface IOneDimensionalCollisionTexture2D
{
#pragma warning disable CS8618
public CollisionTextureInput()
#pragma warning restore CS8618
{
}
public new List<IInstancingBuffer> Value
{
get; set;
}
public void Init(Radius angleStride, string name);
}
public class OneDimensionalCollisionTexture2D : glRenderStream
public sealed class OneDimensionalCollisionTexture2D_GL :glRenderStream, IOneDimensionalCollisionTexture2D
{
private const string inputName = "InstanceBufferList";
@@ -75,44 +64,22 @@ namespace StgSharp.Stg
VertexBuffer vbo;
ElementBuffer ebo;
public OneDimensionalCollisionTexture2D(ViewPort args) : base(args,(1,1,1))
public OneDimensionalCollisionTexture2D_GL()
{
throw new InvalidOperationException(
$"Collision TextureGL unit cannot share context with other render stream or set as mainstream of a form," +
$"and cannot be inited by {typeof(ViewPort).Name} as well."
);
}
#pragma warning disable CS8618
public OneDimensionalCollisionTexture2D(Radius angleStride, string name) :
#pragma warning restore CS8618
base( new ViewPort()
{
Height = 1,
Width = (int)((new Radius(Scaler.Pi)) / angleStride),
Name = name,
},(1, 1, 1))
{
InternalInit();
}
public override bool IsContextSharable => false;
protected override string[] InputPortsName =>
[
inputName,
];
protected override string[] OutputPortsName =>
[
outputName,
];
#pragma warning disable CS8618
protected override void Deinit()
protected override void CustomizeDeinit()
{
throw new NotImplementedException();
}
protected override void Init()
protected override void CustomizeInit()
{
generatingShader = CreateShaderProgram();
@@ -133,51 +100,45 @@ namespace StgSharp.Stg
fbo = CreateFrameBuffer(1);
RenderBuffer rbo = CreateRenderBuffer(1);
glFunc.SetRenderBufferStorage(
rbo = CreateRenderBuffer(1);
GL.SetRenderBufferStorage(
RenderBufferInternalFormat.Depth24_Stencil8, this.Size);
t = CreateTexture(1);
t.Bind2D(0);
glFunc.TextureImage2d(Texture2DTarget.Texture2D, 0, (int)ImageChannel.WithAlphaChannel,
(uint)Width, (uint)Height, (int)ImageChannel.WithAlphaChannel, ImageChannelLayout.Byte, glHandle.ZeroHandle);
GL.TextureImage2d<byte>(Texture2DTarget.Texture2D, 0, (int)ImageChannel.WithAlphaChannel,
(uint)Width, (uint)Height, (int)ImageChannel.WithAlphaChannel, PixelChannelLayout.Byte, Array.Empty<byte>());
t.Set2dWrapProperty(Wrap.Repeat, Wrap.Repeat);
t.Set2dFilterProperty(Filter.Nearest, Filter.Nearest);
glFunc.FrameBufferTexture2d(FrameBufferTarget.All, glAttachment.Color(0),
GL.FrameBufferTexture2d(FrameBufferTarget.All, glAttachment.Color(0),
Texture2DTarget.Texture2D, t[0], 0);
glFunc.CombineFrameBufferRenderBuffer(fbo[0], rbo[0]);
GL.CombineFrameBufferRenderBuffer(fbo[0], rbo[0]);
textureOutput = new float[this.Width];
}
TextureGL t;
RenderBuffer rbo;
float[] textureOutput;
protected override void Main(
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output)
protected override void Main()
{
throw new NotSupportedException();
}
public void GenerateCollisionTexture(IEnumerable<IInstancingBuffer> bufferEnumeration)
{
if (input == null)
{
throw new InvalidOperationException($"Unknown operation lead to null ref of {nameof(input)}");
}
if (input[inputName].Args is not CollisionTextureInput inpipeline || inpipeline.Value == null || inpipeline.Value.Count == 0)
{
throw new InvalidOperationException();
}
List<IInstancingBuffer> bufferList = inpipeline.Value;
fbo.Bind(0);
glFunc.ClearColor(0, 0, 0, 1);
glFunc.Clear(MaskBufferBit.DEPTH|MaskBufferBit.COLOR);
GL.ClearColor(0, 0, 0, 1);
GL.Clear(MaskBufferBit.DEPTH | MaskBufferBit.COLOR);
generatingShader.Use();
vao.Bind(0);
foreach (IInstancingBuffer item in bufferList)
foreach (IInstancingBuffer item in bufferEnumeration)
{
IGeometry g = item.TypicalShape;
@@ -187,26 +148,40 @@ namespace StgSharp.Stg
}
ebo.Bind(0);
ebo.SetValue<int>(0,g.VertexIndices,BufferUsage.StreamDraw);
ebo.SetValue<int>(0, g.VertexIndices, BufferUsage.StreamDraw);
vbo.WriteVectorData<vec4d>(0,item.CoordAndRotationSpan,BufferUsage.StreamDraw);
VertexArray.SetVertexAttribute(1,3,TypeCode.Single,false, 4 * sizeof(float), 0);
VertexArray.SetVertexAttribute(2,1, TypeCode.Single,false,4*sizeof(float), 3 * sizeof(float));
vbo.WriteVectorData<vec4d>(0, item.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.WriteScalerData<float>(2, item.ScalingSpan, BufferUsage.StreamDraw);
VertexArray.SetVertexAttribute(3, 1, TypeCode.Single, false, sizeof(float), 0);
vao.SetVertexAttribute(3, 1, TypeCode.Single, false, sizeof(float), 0);
vbo.WriteVectorData(1,g.VertexStream,BufferUsage.StreamDraw);
VertexArray.SetVertexAttribute(0,3,TypeCode.Single,false,4*sizeof(float),0);
vbo.WriteVectorData(1, g.VertexStream, BufferUsage.StreamDraw);
vao.SetVertexAttribute(0, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
glFunc.DrawElementsInstanced(GeometryType.TRIANGLES,(uint)g.VertexIndices.Length / 3,
TypeCode.UInt32,IntPtr.Zero,(uint)item.ScalingSpan.Length);
GL.DrawElementsInstanced(GeometryType.TRIANGLES, (uint)g.VertexIndices.Length / 3,
TypeCode.UInt32, IntPtr.Zero, (uint)item.ScalingSpan.Length);
}
t.Bind2D(0);
glFunc.GetTextureImage(Texture2DTarget.Texture2D,0,ImageChannel.SingleColor,ImageChannelLayout.Float,ref textureOutput);
GL.GetTextureImage(Texture2DTarget.Texture2D, 0, ImageChannel.SingleColor, PixelChannelLayout.Float, textureOutput);
VertexArray.BindNull();
}
public void Init(Radius angleStride, string name)
{
primeArgs = new ViewPort()
{
Height = 1,
Width = (int)((new Radius(Scaler.Pi)) / angleStride),
Name = name,
};
_coordStretch = (1, 1, 1);
PlatformSpecifiedInit();
CustomizeInit();
}
}
}
+3 -3
View File
@@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<LangVersion>preview</LangVersion>
<LangVersion>Preview</LangVersion>
<ProduceReferenceAssembly>True</ProduceReferenceAssembly>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<Platforms>AnyCPU;x64</Platforms>
@@ -98,13 +98,13 @@
</PropertyGroup>
<PropertyGroup Condition="'$(IsWindows)'=='true'">
<DefineConstants>Windows</DefineConstants>
<DefineConstants>WINDOWS</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(IsOSX)'=='true'">
<DefineConstants>OSX</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(IsLinux)'=='true'">
<DefineConstants>Linux</DefineConstants>
<DefineConstants>LINUX</DefineConstants>
</PropertyGroup>
<ItemGroup>
@@ -14,7 +14,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("StgSharp")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+8f9f1c4012e0ba8723569f71754633060f4f0d85")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+924fe6eef7b6b9441b297f211c82b4684f23d002")]
[assembly: System.Reflection.AssemblyProductAttribute("StgSharp")]
[assembly: System.Reflection.AssemblyTitleAttribute("StgSharp")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
+46
View File
@@ -0,0 +1,46 @@
//using StgSharp.Environment.Win32;
using StgSharp.Controlling.UsrActivity;
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharp.Math;
using StgSharpDebug.Logic;
using System;
using System.Runtime.CompilerServices;
using System.Xml.XPath;
namespace StgSharp
{
internal static class Program
{
internal static unsafe void Main(string[] args)
{
try
{
//StgSharp.TryCreatWindow();
/**/
StgSharp.Init();
StgSharp.InitGL(4, 6);
StgSharp.GlobalSetting.VSyncActivated = false;
StgSharp.Terminate();
/**/
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\n" + ex.StackTrace);
InternalIO.InternalWriteLog(
ex.Message + "\n" + ex.StackTrace,
LogType.Error);
}
}
}
}
@@ -0,0 +1,312 @@
using StgSharp.Controls;
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Graphics.OpenGL;
using StgSharp.Logic;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp
{
public class ParticleRenderStream : glRenderStream
{
ElementBuffer ebo;
FrameBuffer fbo;
Image i;
PlainInstancingBuffer<ParticleOnPlain> buffer;
RenderBuffer rbo;
ShaderProgram s;
TextureGL t;
VertexArray vao;
VertexBuffer vbo;
Uniform<float> time;
protected override void CustomizeDeinit()
{
}
internal static vec3d DefaultRotation(TimeSpanProvider provider, out float rotation)
{
rotation = provider.SpanLengthLowPrecession * 2 * Scaler.Pi;
float angle = provider.CurrentSecond * 2 * Scaler.Pi;
return new vec3d(
Scaler.Cos(rotation),
Scaler.Sin(rotation),
0
) * provider.SpanLengthLowPrecession;
}
ShaderProgram frameMainShader;
protected override void CustomizeInit()
{
buffer = new PlainInstancingBuffer<ParticleOnPlain>();
for (int i = 0; i < 10; i++)
{
float ai = Scaler.Abs(i - 5.0f);
for (int t = 0; t < 10; t++)
{
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)
;
}
}
//SetSizeLimit(800, 800, 800, 800);
s = CreateShaderProgram();
frameMainShader = CreateShaderProgram();
Shader pvs = CreateShaderSegment(ShaderType.Vertex, 2);
Shader pfs = CreateShaderSegment(ShaderType.Fragment, 2);
pvs.Compile(0, Shader.FromCodeFile("Shader\\particle.vert"));
pvs.AttachTo(0, s);
pfs.Compile(0, Shader.FromCodeFile("Shader\\particle.frag"));
pfs.AttachTo(0, s);
s.Link();
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();
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
);
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));
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);
GL.VertexAttributeDivisor(3, 1);
vbo.Unbind();
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");
s.Use();
fbo = CreateFrameBuffer(1);
rbo = CreateRenderBuffer(1);
fbo.Bind(0);
rbo.Bind(0);
GL.SetRenderBufferStorage(
RenderBufferInternalFormat.Depth24_Stencil8, this.Size);
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.FrameBufferTexture2d(FrameBufferTarget.All, glAttachment.Color(0),
Texture2DTarget.Texture2D, t[0], 0);
GL.CombineFrameBufferRenderBuffer(fbo[0], rbo[0]);
int streamLength = this.Width * this.Height * 4;
byte[] imageStream = new byte[streamLength];
i = Image.FromMemory(this.Size, ImageChannel.WithAlphaChannel, imageStream);
time = s.GetUniform<float>("time");
vec2d[] coordArray = {
(0f, 1f),
(1f, 1f),
(1f, 0f),
(0f, 0f)
};
buttonTextureProvider = new TextureProvider(i,coordArray);
f_vao.Bind(0);
f_ebo.Bind(0);
f_ebo.SetValue(0, rec.VertexIndices, BufferUsage.StaticDraw);
f_vbo.Bind(0);
f_vbo.WriteVectorData(0, rec.VertexStream, BufferUsage.StaticDraw);
f_vao.SetVertexAttribute(0, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
f_vbo.Bind(1);
f_vbo.WriteVectorData(1, coordArray, BufferUsage.StaticDraw);
f_vao.SetVertexAttribute(1, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
t = CreateTexture(1);
t.Bind2D(0);
t.Set2dWrapProperty(Wrap.Repeat, Wrap.Repeat);
t.Set2dFilterProperty(Filter.Nearest, Filter.Nearest);
t.ActivateAs(TextureUnit.Unit0);
texUniform = frameMainShader.GetUniform<int>("tex");
GL.SetUniformValue(texUniform, 1);
}
VertexBuffer f_vbo;
VertexArray f_vao;
ElementBuffer f_ebo;
Uniform<int> texUniform;
public void RenderButton(ButtonStatus status, float statusBegin, in TextureProvider provider)
{
provider.ReadImage(i);
}
protected override void Main()
{
//GL.ClearError();
//Console.Clear();
//Console.WriteLine($"{Width} {Height}");
buffer.UpdateAllParticles();
//Console.WriteLine(GL.CheckFrameBufferStatus(FrameBufferTarget.All));
fbo.Bind(0); // Console.Write($"{GL.GetError()}\t");
vao.Bind(0); // Console.Write($"{GL.GetError()}\t");
t.Bind2D(0); // Console.Write($"{GL.GetError()}\t");
/**/
GL.TextureImage2d(Texture2DTarget.Texture2D, 0, (int)ImageChannel.WithAlphaChannel,
(uint)Width, (uint)Height, (int)ImageChannel.WithAlphaChannel, PixelChannelLayout.Byte, new byte[1]);
/**/
//Console.Write($"{GL.GetError()}\t");
GL.ClearColor((0.6f + TimePassed) % 1.0f, 0.1f, 0.3f, 1);
GL.Clear(MaskBufferBit.COLOR | MaskBufferBit.DEPTH);
//Console.Write($"{GL.GetError()}\t");
vbo.Bind(1);
vbo.WriteVectorData<vec4d>(1, buffer.CoordAndRotationSpan, BufferUsage.StreamDraw);
s.Use();
NativeCamera.SetAllUniforms();
GL.SetUniformValue(time, TimePassed);
GL.DrawElementsInstanced(
GeometryType.TRIANGLES, 6, TypeCode.UInt32, IntPtr.Zero, 100
);
//Console.WriteLine(TimePassed);
//Console.Write($"{GL.GetError()}\t");
GL.WaitAccomplishment();
GL.BindVertexArray(GlHandle.Zero);
/**/
//Console.Write($"{GL.GetError()}\t");
ImageHelper.Resize(i, this.Width, this.Height, ImageMovement.Discard);
//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");
}
/**/
//Console.Write($"{GL.GetError()}\t");
//Array.Fill<byte>(i.PixelBuffer, 24);
GL.BindFrameBuffer(FrameBufferTarget.All, GlHandle.Zero);
//Console.Write($"{GL.GetError()}\t");
/**/
/*
//BlueprintPipeline.SkipAll(output);
SwapBuffers();
PollEvents();
/**/
}
public void AnotherMain(IEnumerable<PlainGeometryMesh> items)
{
GL.BindFrameBuffer(FrameBufferTarget.All, GlHandle.Zero); //Console.Write($"{GL.GetError()}\t");
GL.ClearColor(0.4f, TimePassed % 1.0f, 0f, 1.0f); //Console.Write($"{GL.GetError()}\t");
GL.Clear(MaskBufferBit.COLOR /**/| MaskBufferBit.DEPTH/**/); //Console.Write($"{GL.GetError()}\t");
vao.Bind(0); //Console.Write($"{GL.GetError()}\t");
foreach (PlainGeometryMesh mesh in items)
{
t.LoadTexture(0, mesh.TextureImage);
}
//Console.Write($"{GL.GetError()}\t");
s.Use(); //Console.Write($"{GL.GetError()}\t");
GL.DrawElements(GeometryType.TRIANGLES, 6, TypeCode.UInt32, IntPtr.Zero);
//Console.Write($"{GL.GetError()}\t");
//GL.DrawElements(GeometryType.LINES, 6, TypeCode.UInt32, IntPtr.Zero);
//BlueprintPipeline.SkipAll(output);
SwapBuffers();
}
TextureProvider buttonTextureProvider;
public override bool IsContextSharable => true;
}
}
@@ -0,0 +1,25 @@
using StgSharp.Controlling.UsrActivity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp
{
public class Control : ViewResponder<ViewMain>
{
public override void CustomizedInitialize(Func<ITrigger, string, Action> keyRegister)
{
}
public override bool ValidateInitializing()
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,36 @@
using StgSharp.Graphics;
using StgSharp.Controlling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StgSharp.Controls;
namespace StgSharp
{
internal class Design : ViewDesigner<ViewMain>
{
DemoButtonGroup group;
public override sealed void CustomizedInitialize()
{
group = new DemoButtonGroup();
}
public override bool ValidateInitializing()
{
return true;
}
}
public class DemoButtonGroup : KeyboardButtonGroup
{
public override sealed void Confirm()
{
return;
}
}
}
@@ -0,0 +1,24 @@
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()
{
}
}
}
@@ -0,0 +1,40 @@
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharpDebug.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp
{
public class ViewMain : View
{
public DemoButtonGroup DemoGroup
{
get; set;
}
public override void CustomizedInitialize(ViewModelBase viewModelBinding)
{
Designer = new Design();
Responder = new Control();
Render = new Render();
DemoGroup = new DemoButtonGroup();
}
public override bool TryGetObjectReference(string name, out DataBindingEntry entry)
{
throw new NotImplementedException();
}
internal protected override void Show()
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,48 @@
using StgSharp.Graphics;
using StgSharp.Logic;
using StgSharpDebug.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp
{
public class ViewModelMain : ViewModelBase
{
public ViewModelMain(ViewPort vp):base(vp,60)
{
dataBindingEntryIndexmap = new Dictionary<string, DataBindingEntry>();
}
Dictionary<string, DataBindingEntry> dataBindingEntryIndexmap;
public override bool TryGetObjectReference(string name, out DataBindingEntry entry)
{
if (dataBindingEntryIndexmap.TryGetValue(name, out entry))
{
return true;
}
entry = name switch
{
_ => DataBindingEntry.NullBinding,
};
if (entry.ExactEqual(DataBindingEntry.NullBinding))
{
return false;
}
dataBindingEntryIndexmap.Add(name, entry);
return true;
}
public override void CustomizeInitialize()
{
}
}//------------------------------------- End of Class ------------------------------------------
}
+3 -1
View File
@@ -1,10 +1,12 @@
#version 460 core
uniform float time;
out vec3 fragColor;
void main()
{
fragColor = vec3( 0.5f,0.336f,0.9961f );
fragColor = vec3( 0.5f,0.336f,mod( (0.9961f + time),1.0f) );
}
+14 -10
View File
@@ -22,43 +22,43 @@
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<Optimize>False</Optimize>
<Optimize>True</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Benchmark|AnyCPU'">
<Optimize>False</Optimize>
<Optimize>True</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Toollist|AnyCPU'">
<Optimize>False</Optimize>
<Optimize>True</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RealDebug|AnyCPU'">
<Optimize>False</Optimize>
<Optimize>True</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Optimize>False</Optimize>
<Optimize>True</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Benchmark|x64'">
<Optimize>False</Optimize>
<Optimize>True</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Toollist|x64'">
<Optimize>False</Optimize>
<Optimize>True</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='RealDebug|x64'">
<Optimize>False</Optimize>
<Optimize>True</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<Optimize>False</Optimize>
<Optimize>True</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Optimize>False</Optimize>
<Optimize>True</Optimize>
</PropertyGroup>
<PropertyGroup>
@@ -77,6 +77,9 @@
<PropertyGroup Condition="'$(IsLinux)'=='true'">
<DefineConstants>Linux</DefineConstants>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Test\MainRenderStream.cs" />
</ItemGroup>
<ItemGroup>
<None Remove="SSG_errorlog.log" />
@@ -86,6 +89,7 @@
<Folder Include="Entities\" />
<Folder Include="Geometries\SpaceGeometry\" />
<Folder Include="Math\LinearHP\" />
<Folder Include="Test\" />
</ItemGroup>
<ItemGroup>
@@ -31,7 +31,7 @@
using StgSharp;
using StgSharp.Geometries;
using StgSharp.Graphics;
using StgSharp.Graphics.GL;
using StgSharp.Graphics.OpenGL;
using StgSharp.Logic;
using StgSharp.Math;
@@ -43,7 +43,7 @@ using System.Threading.Tasks;
namespace StgSharp
{
public class MainRenderStream : glRenderStream
{
@@ -65,7 +65,7 @@ namespace StgSharp
protected override string[] OutputPortsName => ["output_1"];
protected override void Deinit()
protected override void CustomizeDeinit()
{
/**/
vao.Dispose();
@@ -74,7 +74,7 @@ namespace StgSharp
/**/
}
protected override sealed void Init()
protected override sealed void CustomizeInit()
{
//SetSizeLimit(800, 800, 800, 800);
@@ -130,10 +130,10 @@ namespace StgSharp
ebo.SetValue(0, rec.VertexIndices, BufferUsage.StaticDraw);
vbo.WriteVectorData(0, rec.VertexStream, BufferUsage.StaticDraw);
VertexArray.SetVertexAttribute(0, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
vao.SetVertexAttribute(0, 3, TypeCode.Single, false, 4 * sizeof(float), 0);
vbo.WriteScalerData(1, texCoord, BufferUsage.StaticDraw);
VertexArray.SetVertexAttribute(2, 2, TypeCode.Single, false, 2 * sizeof(float), 0);
vao.SetVertexAttribute(2, 2, TypeCode.Single, false, 2 * sizeof(float), 0);
/**/
vbo.Unbind();
@@ -153,9 +153,9 @@ namespace StgSharp
/**/
color = shader.GetUniform<float, float, float, float>("color");
ourTexture = shader.GetUniform<int>("ourTexture");
glFunc.SetUniformValue(ourTexture, 0);
GL.SetUniformValue(ourTexture, 0);
ourTexture2 = shader.GetUniform<int>("ourTexture2");
glFunc.SetUniformValue(ourTexture2, 1);
GL.SetUniformValue(ourTexture2, 1);
/**/
NativeCameraViewTarget(
@@ -167,9 +167,9 @@ namespace StgSharp
NativeCameraUniform(shader, "camera");
TextureGL.Activate(TextureUnit.Unit0);
texture.ActivateAs(TextureUnit.Unit0);
texture.Bind2D(0);
TextureGL.Activate(TextureUnit.Unit1);
texture.ActivateAs(TextureUnit.Unit1);
texture.Bind2D(1);
}
@@ -179,9 +179,9 @@ namespace StgSharp
in Dictionary<string, BlueprintPipeline> output
)
{
glFunc.ClearColor(0.333f, 0.555f, 0.555f, 1.0f);
GL.ClearColor(0.333f, 0.555f, 0.555f, 1.0f);
//Console.WriteLine(1);
glFunc.Clear(MaskBufferBit.COLOR /**/| MaskBufferBit.DEPTH /**/ );
GL.Clear(MaskBufferBit.COLOR /**/| MaskBufferBit.DEPTH /**/ );
/**/
vao.Bind(0);
@@ -194,7 +194,7 @@ namespace StgSharp
float time = /* CurrentFrameCount, / /**/ 0.003f;
glFunc.SetUniformValue(color,
GL.SetUniformValue(color,
0.5f + MathF.Cos(time),
0.5f + MathF.Sin((time * 0.66667f) + ((2 * Scaler.Pi) / 3)),
0.5f + MathF.Sin((time * 0.33333f) + (Scaler.Pi / 3)),
@@ -206,7 +206,7 @@ namespace StgSharp
//Console.WriteLine(NativeCamera.Projection);
glFunc.DrawElements(GeometryType.TRIANGLES, 6, TypeCode.UInt32, IntPtr.Zero);
GL.DrawElements(GeometryType.TRIANGLES, 6, TypeCode.UInt32, IntPtr.Zero);
VertexArray.BindNull();
/**/
@@ -255,4 +255,5 @@ namespace StgSharp
}
/**/
}
}
@@ -14,7 +14,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("StgSharpDebug")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+8f9f1c4012e0ba8723569f71754633060f4f0d85")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+924fe6eef7b6b9441b297f211c82b4684f23d002")]
[assembly: System.Reflection.AssemblyProductAttribute("StgSharpDebug")]
[assembly: System.Reflection.AssemblyTitleAttribute("StgSharpDebug")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -1 +1 @@
{"documents":{"D:\\NitloadIndustry\\研究项目\\1-Flagship\\TH2020\\ProjectFile\\*":"https://raw.githubusercontent.com/Nitload-NSI/CCD_Github/8f9f1c4012e0ba8723569f71754633060f4f0d85/*"}}
{"documents":{"D:\\NitloadIndustry\\研究项目\\1-Flagship\\TH2020\\ProjectFile\\*":"https://raw.githubusercontent.com/Nitload-NSI/CCD_Github/924fe6eef7b6b9441b297f211c82b4684f23d002/*"}}
@@ -14,7 +14,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("StgSharpDebug")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+66efce19fcb461782c49255dc5500144f8c267e6")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+924fe6eef7b6b9441b297f211c82b4684f23d002")]
[assembly: System.Reflection.AssemblyProductAttribute("StgSharpDebug")]
[assembly: System.Reflection.AssemblyTitleAttribute("StgSharpDebug")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -1,8 +1,6 @@
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\StgSharpDebug.exe
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\Shader\awesomeface.png
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\Shader\fragment.frag
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\Shader\Image1.png
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\Shader\vertex.vert
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\StgSharpDebug.deps.json
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\StgSharpDebug.runtimeconfig.json
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\StgSharpDebug.dll
@@ -17,3 +15,9 @@ D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\StgSharp
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\StgSharpDebug\obj\x64\Release\net6.0\StgSharpDebug.xml
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\StgSharpDebug\obj\x64\Release\net6.0\StgSharpDebug.pdb
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\StgSharpDebug\obj\x64\Release\net6.0\StgSharpDebug.genruntimeconfig.cache
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\Shader\fbo.frag
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\Shader\fbo.vert
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\Shader\main.frag
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\Shader\main.vert
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\Shader\particle.frag
D:\NitloadIndustry\研究项目\1-Flagship\TH2020\ProjectFile\源代码\Output\x64\Release\net6.0\Shader\particle.vert
@@ -1 +1 @@
{"documents":{"D:\\NitloadIndustry\\研究项目\\1-Flagship\\TH2020\\ProjectFile\\*":"https://raw.githubusercontent.com/Nitload-NSI/CCD_Github/66efce19fcb461782c49255dc5500144f8c267e6/*"}}
{"documents":{"D:\\NitloadIndustry\\研究项目\\1-Flagship\\TH2020\\ProjectFile\\*":"https://raw.githubusercontent.com/Nitload-NSI/CCD_Github/924fe6eef7b6b9441b297f211c82b4684f23d002/*"}}
@@ -14,7 +14,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("StgsharpEnvDebug")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+8f9f1c4012e0ba8723569f71754633060f4f0d85")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+924fe6eef7b6b9441b297f211c82b4684f23d002")]
[assembly: System.Reflection.AssemblyProductAttribute("StgsharpEnvDebug")]
[assembly: System.Reflection.AssemblyTitleAttribute("StgsharpEnvDebug")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]

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