daily update on 20240403 by nitload youmu

This commit is contained in:
YoumuLiu
2024-04-03 08:56:33 +08:00
parent b207f16616
commit 127fcdbfd3
631 changed files with 23499 additions and 2664 deletions
+279 -262
View File
@@ -48,22 +48,21 @@ namespace StgSharp.Graphics
{
private int client;
private int source;
private int major, minor, revision;
private IntPtr destroy;
private delegate*<byte*> extensionSupported;
private GLFWbool forward, debug, noerror;
private int profile;
private int robustness;
private int release;
//PFNGLGETSTRINGIPROC GetStringi;
private IntPtr GetStringi;
//PFNGLGETINTEGERVPROC GetIntegerv;
private IntPtr GetIntegerv;
private delegate*<delegate*<void>, void> getProcAddress;
//PFNGLGETSTRINGPROC GetString;
private IntPtr GetString;
//PFNGLGETSTRINGIPROC GetStringi;
private IntPtr GetStringi;
private int major, minor, revision;
/*
void (* makeCurrent) (GLFWwindow*);
void (* swapBuffers) (GLFWwindow*);
@@ -74,15 +73,18 @@ namespace StgSharp.Graphics
*/
private delegate*<GLFWwindow*> makeCurrent;
private int profile;
private int release;
private int robustness;
private int source;
private delegate*<GLFWwindow*> swapBuffer;
private delegate*<int> swapInterval;
private delegate*<byte*> extensionSupported;
private delegate*<delegate*<void>, void> getProcAddress;
private IntPtr destroy;
internal struct egl
{
private void* client;
/*
EGLConfig config;
EGLContext handle;
@@ -91,19 +93,19 @@ namespace StgSharp.Graphics
private void* config;
private void* handle;
private void* surface;
private void* client;
}
internal struct osmesa
{
private void* buffer;
//OSMesaContext handle;
private void* handle;
private int height;
private int width;
private int height;
private void* buffer;
}
@@ -115,24 +117,25 @@ namespace StgSharp.Graphics
public unsafe struct GLFWvidmode
{
/*! The width, in screen coordinates, of the video mode.
/*! The refresh rate, in Hz, of the video mode.
*/
public int width;
private int refreshRate;
/*! The bit depth of the blue channel of the video mode.
*/
public int blueBits;
/*! The bit depth of the green channel of the video mode.
*/
public int greenBits;
/*! The height, in screen coordinates, of the video mode.
*/
public int height;
/*! The bit depth of the red channel of the video mode.
*/
public int redBits;
/*! The bit depth of the green channel of the video mode.
/*! The width, in screen coordinates, of the video mode.
*/
public int greenBits;
/*! The bit depth of the blue channel of the video mode.
*/
public int blueBits;
/*! The refresh rate, in Hz, of the video mode.
*/
private int refreshRate;
public int width;
}
@@ -140,15 +143,16 @@ namespace StgSharp.Graphics
public unsafe struct GLFWgammaramp
{
/*! An array of value describing the response of the red channel.
*/
private ushort* red;
/*! An array of value describing the response of the green channel.
*/
private ushort* green;
/*! An array of value describing the response of the blue channel.
*/
private ushort* blue;
/*! An array of value describing the response of the green channel.
*/
private ushort* green;
/*! An array of value describing the response of the red channel.
*/
private ushort* red;
/*! The number of elements in each array.
*/
private uint size;
@@ -159,9 +163,6 @@ namespace StgSharp.Graphics
public unsafe struct GLFWimage
{
/*! The width, in pixels, of this image.
*/
private int width;
/*! The height, in pixels, of this image.
*/
private int height;
@@ -169,21 +170,26 @@ namespace StgSharp.Graphics
*/
private byte* pixels;
/*! The width, in pixels, of this image.
*/
private int width;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct GLFWgamepadstate
{
/*! The states of each [gamepad button](@ref gamepad_buttons), `GLFW_PRESS`
* or `GLFW_RELEASE`.
*/
public fixed byte buttons[15];
/*! The states of each [gamepad axis](@ref gamepad_axes), in the range -1.0
* to 1.0 inclusive.
*/
public fixed float axes[6];
/*! The states of each [gamepad button](@ref gamepad_buttons), `GLFW_PRESS`
* or `GLFW_RELEASE`.
*/
public fixed byte buttons[15];
}
[StructLayout(LayoutKind.Sequential)]
@@ -193,12 +199,12 @@ namespace StgSharp.Graphics
//GLFWallocatefun allocate;
private IntPtr allocate;
//GLFWreallocatefun reallocate;
private IntPtr reallocate;
//GLFWdeallocatefun deallocate;
private IntPtr deallocate;
//GLFWreallocatefun reallocate;
private IntPtr reallocate;
private void* user;
}
@@ -207,7 +213,17 @@ namespace StgSharp.Graphics
public unsafe struct GLFWmonitor
{
private GLFWvidmode currentMode;
private GLFWgammaramp currentRamp;
private int modeCount;
//GLFWvidmode* modes;
private IntPtr modes;
private byte[] name = new byte[128];
private GLFWgammaramp originalRamp;
private void* userPointer;
// Physical dimensions in millimeters.
@@ -217,15 +233,6 @@ namespace StgSharp.Graphics
//GLFWwindow* window;
private IntPtr window;
//GLFWvidmode* modes;
private IntPtr modes;
private int modeCount;
private GLFWvidmode currentMode;
private GLFWgammaramp originalRamp;
private GLFWgammaramp currentRamp;
// not transformed
//GLFW_PLATFORM_MONITOR_STATE;
@@ -238,39 +245,40 @@ namespace StgSharp.Graphics
public unsafe struct GLFWwindow
{
//struct GLFWwindow* next in GLFW
public GLFWwindow* next;
private int resizable;
private int decorated;
private int autoIconify;
private fixed long callBacks[17];
private GLFWcursor* cursor = (GLFWcursor*)0;
private int cursorMode = 0;
private int decorated;
private bool doubleBuffer;
private int floating;
private int focusOnShow;
private int mousePassthrough;
internal int shouldClose;
private void* userPointer = (void*)0;
private bool doubleBuffer;
private GLFWvidmode videoMode = default;
private IntPtr monitor = IntPtr.Zero; //public GLFWmonitor* monitor;
private GLFWcursor* cursor = (GLFWcursor*)0;
private fixed byte keys[349];
private int lockKeyMods;
private int maxWidth = 0, maxHeight = 0;
private int minWidth = 0, minHeight = 0;
private int maxWidth = 0, maxHeight = 0;
private IntPtr monitor = IntPtr.Zero; //public GLFWmonitor* monitor;
private fixed byte mouseButtons[8];
private int mousePassthrough;
private int numer = 0, denom = 0;
private int rawMouseMotion;
private int resizable;
private int stickyKeys;
private int stickyMouseButtons;
private int lockKeyMods;
private int cursorMode = 0;
private fixed byte mouseButtons[8];
private fixed byte keys[349];
// Virtual cursor position when cursor is disabled
public double virtualCursorPosX = 0, virtualCursorPosY = 0;
private int rawMouseMotion;
private void* userPointer = (void*)0;
private GLFWvidmode videoMode = default;
internal int shouldClose;
public GLFWcontext context = default;
private fixed long callBacks[17];
//struct GLFWwindow* next in GLFW
public GLFWwindow* next;
// Virtual cursor position when cursor is disabled
public double virtualCursorPosX = 0, virtualCursorPosY = 0;
public GLFWwindow()
{
@@ -369,8 +377,9 @@ namespace StgSharp.Graphics
public unsafe struct GLFWinitconfig
{
private GLFWbool hatButtons;
private int angleType;
private GLFWbool hatButtons;
private int platformID;
//PFN_vkGetInstanceProcAddr vulkanLoader;
@@ -382,31 +391,32 @@ namespace StgSharp.Graphics
public unsafe struct GLFWwndconfig
{
private GLFWbool autoIconify;
private GLFWbool centerCursor;
private GLFWbool decorated;
private GLFWbool floating;
private GLFWbool focused;
private GLFWbool focusOnShow;
private int height;
private GLFWbool maximized;
private GLFWbool mousePassthrough;
private GLFWbool resizable;
private GLFWbool scaleToMonitor;
private byte* title;
private GLFWbool visible;
private int width;
private int xpos;
private int ypos;
private int width;
private int height;
private byte* title;
private GLFWbool resizable;
private GLFWbool visible;
private GLFWbool decorated;
private GLFWbool focused;
private GLFWbool autoIconify;
private GLFWbool floating;
private GLFWbool maximized;
private GLFWbool centerCursor;
private GLFWbool focusOnShow;
private GLFWbool mousePassthrough;
private GLFWbool scaleToMonitor;
internal Ns ns = new Ns();
internal X11 x11 = new X11();
internal Win32 win32 = new Win32();
internal Wl wl = new Wl();
internal X11 x11 = new X11();
public GLFWwndconfig()
{
}
@@ -460,18 +470,18 @@ namespace StgSharp.Graphics
{
private int client;
private int source;
private GLFWbool debug;
private GLFWbool forward;
private int major;
private int minor;
private GLFWbool forward;
private GLFWbool debug;
private GLFWbool noerror;
private int profile;
private int robustness;
private int release;
private int robustness;
//GLFWwindow* share;
private IntPtr share;
private int source;
internal Nsgl nsgl = new Nsgl();
@@ -492,23 +502,24 @@ namespace StgSharp.Graphics
public unsafe struct GLFWfbconfig
{
private int redBits;
private int greenBits;
private int blueBits;
private int alphaBits;
private int depthBits;
private int stencilBits;
private int accumRedBits;
private int accumGreenBits;
private int accumBlueBits;
private int accumAlphaBits;
private int accumBlueBits;
private int accumGreenBits;
private int accumRedBits;
private int alphaBits;
private int auxBuffers;
private GLFWbool stereo;
private int blueBits;
private int depthBits;
private GLFWbool doublebuffer;
private int greenBits;
private uintptr_t handle;
private int redBits;
private int samples;
private GLFWbool sRGB;
private GLFWbool doublebuffer;
private int stencilBits;
private GLFWbool stereo;
private GLFWbool transparent;
private uintptr_t handle;
}
@@ -516,46 +527,47 @@ namespace StgSharp.Graphics
internal unsafe struct GLFWlibrary
{
private GLFWbool initialized;
private GLFWallocator allocator;
private GLFWplatform platform;
internal Hints hints = new Hints();
//GLFWerror* errorListHead;
private IntPtr errorListHead;
private GLFWls contextSlot;
//GLFWcursor* cursorListHead;
private IntPtr cursorListHead;
//GLFWwindow* windowListHead;
private IntPtr windowListHead;
//GLFWerror* errorListHead;
private IntPtr errorListHead;
private GLFWmutex errorLock;
//GLFWmonitor** monitors;
private IntPtr monitors;
private GLFWls errorSlot;
private int monitorCount;
private GLFWbool joysticksInitialized;
private GLFWbool initialized;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = GLconst.GLFW_JOYSTICK_LAST + 1)]
private GLFWjoystick[] joysticks = new GLFWjoystick[GLconst.GLFW_JOYSTICK_LAST + 1];
//GLFWmapping* mappings;
private IntPtr mappings;
private GLFWbool joysticksInitialized;
private int mappingCount;
private GLFWls errorSlot;
private GLFWls contextSlot;
private GLFWmutex errorLock;
//GLFWmapping* mappings;
private IntPtr mappings;
private int monitorCount;
//GLFWmonitor** monitors;
private IntPtr monitors;
private GLFWplatform platform;
//GLFWwindow* windowListHead;
private IntPtr windowListHead;
internal Callbacks callbacks = new Callbacks();
internal Egl egl = new Egl();
internal Osmesa osmesa = new Osmesa();
internal Hints hints = new Hints();
internal Callbacks callbacks = new Callbacks();
internal Osmesa osmesa = new Osmesa();
public GLFWlibrary()
{
@@ -564,11 +576,12 @@ namespace StgSharp.Graphics
internal unsafe struct Hints
{
private GLFWinitconfig init;
private GLFWfbconfig framebuffer;
private GLFWwndconfig window;
private GLFWctxconfig context;
private GLFWfbconfig framebuffer;
private GLFWinitconfig init;
private int refreshRate;
private GLFWwndconfig window;
}
@@ -585,80 +598,82 @@ namespace StgSharp.Graphics
internal unsafe struct Egl
{
internal int platform;
internal bool ANGLE_platform_angle;
internal bool ANGLE_platform_angle_d3d;
internal bool ANGLE_platform_angle_metal;
internal bool ANGLE_platform_angle_opengl;
internal bool ANGLE_platform_angle_vulkan;
internal IntPtr BindAPI;
internal IntPtr CreateContext;
internal IntPtr CreatePlatformWindowSurfaceEXT;
internal IntPtr CreateWindowSurface;
internal IntPtr DestroyContext;
internal IntPtr DestroySurface;
internal void* display;
internal int major, minor;
internal bool prefix;
internal bool KHR_create_context;
internal bool KHR_create_context_no_error;
internal bool KHR_colorSpace;
internal bool KHR_get_all_proc_addresses;
internal bool KHR_context_flush_control;
internal bool EXT_client_extensions;
internal bool EXT_platform_base;
internal bool EXT_platform_x11;
internal bool EXT_platform_wayland;
internal bool EXT_platform_x11;
internal bool EXT_present_opaque;
internal bool ANGLE_platform_angle;
internal bool ANGLE_platform_angle_opengl;
internal bool ANGLE_platform_angle_d3d;
internal bool ANGLE_platform_angle_vulkan;
internal bool ANGLE_platform_angle_metal;
internal void* handle;
internal IntPtr GetConfigAttrib;
internal IntPtr GetConfigs;
internal IntPtr GetDisplay;
internal IntPtr GetError;
internal IntPtr Initialize;
internal IntPtr Terminate;
internal IntPtr BindAPI;
internal IntPtr CreateContext;
internal IntPtr DestroySurface;
internal IntPtr DestroyContext;
internal IntPtr CreateWindowSurface;
internal IntPtr MakeCurrent;
internal IntPtr SwapBuffers;
internal IntPtr SwapInterval;
internal IntPtr QueryString;
internal IntPtr GetProcAddress;
internal IntPtr GetPlatformDisplayEXT;
internal IntPtr CreatePlatformWindowSurfaceEXT;
internal IntPtr GetProcAddress;
internal void* handle;
internal IntPtr Initialize;
internal bool KHR_colorSpace;
internal bool KHR_context_flush_control;
internal bool KHR_create_context;
internal bool KHR_create_context_no_error;
internal bool KHR_get_all_proc_addresses;
internal int major, minor;
internal IntPtr MakeCurrent;
internal int platform;
internal bool prefix;
internal IntPtr QueryString;
internal IntPtr SwapBuffers;
internal IntPtr SwapInterval;
internal IntPtr Terminate;
}
internal unsafe struct Osmesa
{
private void* handle;
private IntPtr CreateContextAttribs;
private IntPtr CreateContextExt;
private IntPtr CreateContextAttribs;
private IntPtr DestroyContext;
private IntPtr MakeCurrent;
private IntPtr GetColorBuffer;
private IntPtr GetDepthBuffer;
private IntPtr GetProcAddress;
private void* handle;
private IntPtr MakeCurrent;
}
internal unsafe struct vk
{
private GLFWbool available;
private void* handle;
private GLFWbool EXT_metal_surface;
private fixed ulong extensions[2];
private IntPtr GetInstanceProcAddr;
private void* handle;
private GLFWbool KHR_surface;
private GLFWbool KHR_win32_surface;
private GLFWbool MVK_macos_surface;
private GLFWbool EXT_metal_surface;
private GLFWbool KHR_xlib_surface;
private GLFWbool KHR_xcb_surface;
private GLFWbool KHR_wayland_surface;
private GLFWbool KHR_win32_surface;
private GLFWbool KHR_xcb_surface;
private GLFWbool KHR_xlib_surface;
private GLFWbool MVK_macos_surface;
public vk()
{
@@ -669,9 +684,10 @@ namespace StgSharp.Graphics
internal unsafe struct Callbacks
{
private IntPtr monitor;
private IntPtr joystick;
private IntPtr monitor;
}
}
@@ -680,10 +696,11 @@ namespace StgSharp.Graphics
public unsafe struct GLFWmapelement
{
private byte type;
private byte index;
private sbyte axisScale;
private sbyte axisOffset;
private sbyte axisScale;
private byte index;
private byte type;
}
@@ -691,14 +708,14 @@ namespace StgSharp.Graphics
public unsafe struct GLFWmapping
{
private fixed byte name[128];
private fixed byte guid[33];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
private GLFWmapelement[] axes = new GLFWmapelement[6];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 15)]
private GLFWmapelement[] buttons = new GLFWmapelement[15];
private fixed byte guid[33];
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
private GLFWmapelement[] axes = new GLFWmapelement[6];
private fixed byte name[128];
public GLFWmapping()
{ }
@@ -710,19 +727,19 @@ namespace StgSharp.Graphics
{
private GLFWbool allocated;
private GLFWbool connected;
private float* axes;
private int axisCount;
private byte* buttons;
private int buttonCount;
private byte* hats;
private int hatCount;
private fixed byte name[128];
private void* userPointer;
private byte* buttons;
private GLFWbool connected;
private fixed byte guid[33];
private int hatCount;
private byte* hats;
//GLFWmapping* mapping;
private IntPtr mapping;
private fixed byte name[128];
private void* userPointer;
// This is defined in platform.h
// not completed in transforming
@@ -745,14 +762,73 @@ namespace StgSharp.Graphics
public unsafe struct GLFWplatform
{
private int platformID;
// init
//GLFWbool(*init)(void);
private IntPtr init;
private int platformID;
//void (* terminate) (void);
private IntPtr terminate;
internal IntPtr createCursor;
internal IntPtr createStandardCursor;
// window
internal IntPtr createWindow;
internal IntPtr destroyCursor;
internal IntPtr destroyWindow;
internal IntPtr focusWindow;
internal IntPtr framebufferTransparent;
// monitor
internal IntPtr freeMonitor;
internal IntPtr getClipboardString;
internal IntPtr getEGLNativeDisplay;
internal IntPtr getEGLNativeWindow;
// EGL
//EGLenum(*getEGLPlatform)(EGLint**);
//EGLNativeDisplayType(*getEGLNativeDisplay)(void);
//EGLNativeWindowType(*getEGLNativeWindow)(GLFWwindow*);
internal IntPtr getEGLPlatform;
internal IntPtr getFramebufferSize;
internal IntPtr getGammaRamp;
internal IntPtr getKeyScancode;
internal IntPtr getMappingName;
internal IntPtr getMonitorContentScale;
internal IntPtr getMonitorPos;
internal IntPtr getMonitorWorkarea;
// vulkan
//void (* getRequiredInstanceExtensions) (byte**);
//GLFWbool(*getPhysicalDevicePresentationSupport)(VkInstance, VkPhysicalDevice, uint32_t);
//VkResult(*createWindowSurface)(VkInstance, GLFWwindow*,const VkAllocationCallbacks*, VkSurfaceKHR*);
internal IntPtr getRequiredInstanceExtensions;
internal IntPtr getScancodeName;
internal IntPtr getVideoMode;
internal IntPtr getVideoModes;
internal IntPtr getWindowContentScale;
internal IntPtr getWindowFrameSize;
internal IntPtr getWindowOpacity;
internal IntPtr getWindowPos;
internal IntPtr getWindowSize;
internal IntPtr GLFWwindow;
internal IntPtr hideWindow;
internal IntPtr iconifyWindow;
internal IntPtr initJoysticks;
internal IntPtr maximizeWindow;
internal IntPtr pollEvents;
internal IntPtr pollJoystick;
internal IntPtr postEmptyEvent;
internal IntPtr rawMouseMotionSupported;
internal IntPtr requestWindowAttention;
internal IntPtr restoreWindow;
internal IntPtr setClipboardString;
internal IntPtr setCursor;
internal IntPtr setCursorMode;
#region input
/* void (* getCursorPos) (GLFWwindow*, double*, double*);
@@ -824,91 +900,32 @@ namespace StgSharp.Graphics
#endregion
internal IntPtr setCursorPos;
internal IntPtr setCursorMode;
internal IntPtr setRawMouseMotion;
internal IntPtr rawMouseMotionSupported;
internal IntPtr createCursor;
internal IntPtr createStandardCursor;
internal IntPtr destroyCursor;
internal IntPtr setCursor;
internal IntPtr getScancodeName;
internal IntPtr getKeyScancode;
internal IntPtr setClipboardString;
internal IntPtr getClipboardString;
internal IntPtr initJoysticks;
internal IntPtr terminateJoysticks;
internal IntPtr pollJoystick;
internal IntPtr getMappingName;
internal IntPtr updateGamepadGUID;
// monitor
internal IntPtr freeMonitor;
internal IntPtr getMonitorPos;
internal IntPtr getMonitorContentScale;
internal IntPtr getMonitorWorkarea;
internal IntPtr getVideoModes;
internal IntPtr getVideoMode;
internal IntPtr getGammaRamp;
internal IntPtr setGammaRamp;
// window
internal IntPtr createWindow;
internal IntPtr destroyWindow;
internal IntPtr setWindowTitle;
internal IntPtr setWindowIcon;
internal IntPtr getWindowPos;
internal IntPtr setWindowPos;
internal IntPtr getWindowSize;
internal IntPtr setWindowSize;
internal IntPtr setWindowSizeLimits;
internal IntPtr setRawMouseMotion;
internal IntPtr setWindowAspectRatio;
internal IntPtr getFramebufferSize;
internal IntPtr getWindowFrameSize;
internal IntPtr getWindowContentScale;
internal IntPtr iconifyWindow;
internal IntPtr restoreWindow;
internal IntPtr maximizeWindow;
internal IntPtr showWindow;
internal IntPtr hideWindow;
internal IntPtr requestWindowAttention;
internal IntPtr focusWindow;
internal IntPtr setWindowMonitor;
internal IntPtr windowFocused;
internal IntPtr windowIconified;
internal IntPtr windowVisible;
internal IntPtr windowMaximized;
internal IntPtr windowHovered;
internal IntPtr framebufferTransparent;
internal IntPtr getWindowOpacity;
internal IntPtr setWindowResizable;
internal IntPtr setWindowDecorated;
internal IntPtr setWindowFloating;
internal IntPtr setWindowOpacity;
internal IntPtr setWindowIcon;
internal IntPtr setWindowMonitor;
internal IntPtr setWindowMousePassthrough;
internal IntPtr pollEvents;
internal IntPtr waitEvents;
internal IntPtr waitEventsTimeout;
internal IntPtr postEmptyEvent;
// EGL
//EGLenum(*getEGLPlatform)(EGLint**);
//EGLNativeDisplayType(*getEGLNativeDisplay)(void);
//EGLNativeWindowType(*getEGLNativeWindow)(GLFWwindow*);
internal IntPtr getEGLPlatform;
internal IntPtr getEGLNativeDisplay;
internal IntPtr getEGLNativeWindow;
// vulkan
//void (* getRequiredInstanceExtensions) (byte**);
//GLFWbool(*getPhysicalDevicePresentationSupport)(VkInstance, VkPhysicalDevice, uint32_t);
//VkResult(*createWindowSurface)(VkInstance, GLFWwindow*,const VkAllocationCallbacks*, VkSurfaceKHR*);
internal IntPtr getRequiredInstanceExtensions;
internal IntPtr setWindowOpacity;
internal IntPtr setWindowPos;
internal IntPtr setWindowResizable;
internal IntPtr setWindowSize;
internal IntPtr setWindowSizeLimits;
internal IntPtr setWindowTitle;
internal IntPtr showWindow;
internal IntPtr terminateJoysticks;
internal IntPtr updateGamepadGUID;
internal IntPtr VkPhysicalDevice;
internal IntPtr GLFWwindow;
internal IntPtr waitEvents;
internal IntPtr waitEventsTimeout;
internal IntPtr windowFocused;
internal IntPtr windowHovered;
internal IntPtr windowIconified;
internal IntPtr windowMaximized;
internal IntPtr windowVisible;
}
+12 -50
View File
@@ -59,7 +59,6 @@ namespace StgSharp.Graphics
internal Vector4 backgroundColor;
internal TimeSpanProvider fpsCountProvider;
internal TimeSpanProvider frameTimeProvider;
internal IglFunc gl;
internal IntPtr graphicContextID;
internal int height;
internal IntPtr monitor;
@@ -78,19 +77,11 @@ namespace StgSharp.Graphics
Interlocked.Exchange(ref _frameSpeed, _frameCount);
Interlocked.Exchange(ref _frameCount, 0);
});
frameAsyncThreadList = new List<FrameAsyncThread>();
}
public int CurrentFrameCount => frameTimeProvider.CurrentSpan;
public int FrameSpeed => _frameSpeed;
/// <summary>
/// OpenGL package binded to current form context.
/// A OpenGL context is only binded to current form.
/// </summary>
public IglFunc GL => gl;
/// <summary>
/// Height of this form, represent in <see cref="int"/>
/// </summary>
@@ -102,10 +93,7 @@ namespace StgSharp.Graphics
public bool ShouldClose
{
get
{
return InternalIO.glfwWindowShouldClose(windowID) != 0;
}
get => InternalIO.glfwWindowShouldClose(windowID) != 0;
set => InternalIO.glfwSetWindowShouldClose(windowID, value ? 1 : 0);
}
@@ -145,17 +133,18 @@ namespace StgSharp.Graphics
}
}
public abstract void Deinit();
protected abstract void DeInit();
/// <summary>
/// Necessary operation to init this form.
/// Necessary operation to init graphic elements this form.
/// </summary>
public abstract void Init();
/// <param name="gl">OpenGL library binded to current form.</param>
protected abstract void Init();
/// <summary>
/// Behaviour of current form when in a frame cycle.
/// </summary>
public abstract void Main();
protected abstract void Main();
/// <summary>
/// Init an OpenGl context if current form has not been binded to any context. and set the context binded to
@@ -191,16 +180,11 @@ namespace StgSharp.Graphics
GLcontext* contextID = (GLcontext*)graphicContextID;
*contextID = new GLcontext();
contextID->glGetString = (delegate*<uint, IntPtr>)IntPtr.Zero;
gl = new GLpack(contextID);
}
GL.api = (GLcontext*)graphicContextID;
InternalIO.glfwMakeContextCurrent(windowID);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void PollEvents()
{
InternalIO.glfwPollEvents();
}
/// <summary>
/// Set all necessary metadata to current form instance
@@ -227,6 +211,8 @@ namespace StgSharp.Graphics
InternalIO.glfwSetWindowSize(this.windowID, (int)size.X, (int)size.Y);
}
protected abstract void ProcessInput();
/// <summary>
/// Resize the current form
/// </summary>
@@ -264,7 +250,7 @@ namespace StgSharp.Graphics
/// </summary>
/// <param name="minWidth">Minimum width of current form</param>
/// <param name="minHeight">Minimum height of current form</param>
/// <param name="maxWidth">Maximum width of curent form</param>
/// <param name="maxWidth">Maximum width of current form</param>
/// <param name="maxHeight">Maximum height of current form</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetSizeLimit(int minWidth, int minHeight, int maxWidth, int maxHeight)
@@ -274,38 +260,14 @@ namespace StgSharp.Graphics
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void InternalDeinit() { Deinit(); }
internal void InternalDeInit() { DeInit(); }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal unsafe void SwapBuffers()
{
InternalIO.glfwSwapBuffers(windowID);
}
/// <summary>
/// Get OpenGL library of this form's context.
/// </summary>
/// <returns>A <see cref="IglFunc"/> package contains all opengl APIs</returns>
protected IglFunc GetGL()
{
if (StgSharp.API == GraphicAPI.GL)
{
return this.GL;
}
else
{
InternalIO.InternalWriteLog(
"Attempt to get OpenGL API package in other graphic envitronment.",
LogType.Error);
throw new InvalidOperationException("Attempt to get OpenGL API package in other graphic envitronment.");
}
}
unsafe ~Form() { Marshal.FreeHGlobal(graphicContextID); }
#endregion form main
}
@@ -38,29 +38,44 @@ namespace StgSharp.Graphics
/// Mark that a method in a <see cref="Form"/>
/// should be called when rendering.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class RenderActivityAttribute : Attribute
{
internal bool _isRenderProgress;
internal int _priority;
public RenderActivityAttribute(RenderPriority priority, bool IsRenderProgress)
public RenderActivityAttribute()
{
_priority = (int)priority; _isRenderProgress = IsRenderProgress;
_priority = (int)RenderPriority.Default;
}
public RenderActivityAttribute(int priority, bool IsRenderProgress)
public RenderActivityAttribute(RenderPriority priority)
{
_priority = priority; _isRenderProgress = IsRenderProgress;
_priority = (int)priority;
}
public RenderActivityAttribute(int priority)
{
_priority = priority;
}
public int Priority { get => _priority; set => _priority = value; }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class MultiFrameActivityAttribute : Attribute
{
internal int _minFrameCount;
}
/// <summary>
/// Priority level of a render activity.
/// </summary>
public enum RenderPriority: int
public enum RenderPriority : int
{
/// <summary>
/// One level higher than <see cref="RenderPriority.Default"/>.
+181 -62
View File
@@ -1,4 +1,36 @@
using System;
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
@@ -10,92 +42,179 @@ namespace StgSharp.Graphics
{
public abstract partial class Form
{
#region form thread setting
private List<FrameAsyncThread> frameAsyncThreadList;
#endregion form thread setting
private List<FrameAsyncThread> multiFrameAsyncThreadList = new List<FrameAsyncThread>();
private List<FrameAsyncThread> singleFrameAsyncThreadList = new List<FrameAsyncThread>();
/// <summary>
/// Init this form and render it on screen, and respond with operation
/// </summary>
public unsafe void Show()
{
if (gl == null)
Init();
frameTimeProvider = new TimeSpanProvider(1 / 60.0, TimeSpanProvider.DefaultProvider);
MethodInfo[] methods = this.GetType().GetMethods(
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
GahterSignleFrameAsyncThread(methods);
GatherMultiFrameAsyncThread(methods);
//if no other operation
if (singleFrameAsyncThreadList.Count == 0)
{
InternalIO.InternalWriteLog($"Attempt to show form {name} before init", LogType.Error);
while (!ShouldClose)
{
ProcessInput();
Main( );
InternalIO.glfwSwapBuffers(windowID);
InternalIO.glfwPollEvents();
frameTimeProvider.WaitNextSpan();
Interlocked.Add(ref _frameCount, 1);
}
return;
}
else
List<IGrouping<int, FrameAsyncThread>> threadGroup = singleFrameAsyncThreadList.GroupBy<FrameAsyncThread, int>((t) => t.Priority).ToList();
if (threadGroup.Count == 1)
{
frameTimeProvider = new TimeSpanProvider(1 / 60.0, TimeSpanProvider.DefaultProvider);
MethodInfo[] methods = this.GetType().GetMethods(
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
if (methods.Length != 0)
int p = threadGroup.First().Key;
(Barrier, Barrier) bPair = FrameAsyncThread.CombineAsync(true, singleFrameAsyncThreadList);
FrameAsyncThread.AsyncStartAll(singleFrameAsyncThreadList);
switch (Scaler.SignOf(p))
{
foreach (MethodInfo m in methods) //find all methods decorated by RenderActivityAttribute
{
RenderActivityAttribute attr = m.GetCustomAttribute<RenderActivityAttribute>(false);
if (attr == null)
case 0:
while (!ShouldClose)
{
continue;
bPair.Item1.SignalAndWait();
ProcessInput();
Main( );
InternalIO.glfwSwapBuffers(windowID);
InternalIO.glfwPollEvents();
bPair.Item2.SignalAndWait();
Interlocked.Add(ref _frameCount, 1);
frameTimeProvider.WaitNextSpan();
}
if (!m.IsStatic && (m.GetParameters().Length != 0) && (m.ReturnType != typeof(void)))
break;
case 1:
while (!ShouldClose)
{
throw new NotSupportedException("A render activity cannot have parameters, returning value or be static.");
bPair.Item1.SignalAndWait();
bPair.Item2.SignalAndWait();
ProcessInput();
Main( );
InternalIO.glfwSwapBuffers(windowID);
InternalIO.glfwPollEvents();
Interlocked.Add(ref _frameCount, 1);
frameTimeProvider.WaitNextSpan();
}
if (m.Name != "Main")
break;
case -1:
while (!ShouldClose)
{
ThreadStart s = (ThreadStart)Delegate.CreateDelegate(typeof(ThreadStart), this, m);
FrameAsyncThread t = new(s,attr._priority);
frameAsyncThreadList.Add(t);
ProcessInput();
Main( );
InternalIO.glfwSwapBuffers(windowID);
InternalIO.glfwPollEvents();
bPair.Item1.SignalAndWait();
bPair.Item2.SignalAndWait();
Interlocked.Add(ref _frameCount, 1);
frameTimeProvider.WaitNextSpan();
}
}
break;
default:
return;
}
List<IGrouping<int,FrameAsyncThread>> threadGroup = frameAsyncThreadList.GroupBy<FrameAsyncThread, int>((t) => t.Priority).ToList();
int priority = 0;
foreach (var group in threadGroup)
FrameAsyncThread.TerminateAll(singleFrameAsyncThreadList);
bPair.Item1.SignalAndWait();
return;
}
threadGroup.Sort();
int priority = threadGroup.Count; //rearrange priority label
(Barrier, Barrier)[] barrierList = new (Barrier, Barrier)[priority];
for (int i = 0; i < priority; i++)
{
var group = threadGroup[i].ToList();
foreach (var t in group)
{
foreach (var t in group)
{
t.Priority = priority;
}
priority++;
t.Priority = priority;
}
(Barrier, Barrier) b = FrameAsyncThread.CombineAsync(true, frameAsyncThreadList);
FrameAsyncThread.AsyncStartAll(frameAsyncThreadList);
if (b.Item1 == null)
barrierList[i] = FrameAsyncThread.CombineAsync(true, group);
//setting thread sync
}
FrameAsyncThread.AsyncStartAll(singleFrameAsyncThreadList);
while (!ShouldClose)
{
barrierList[0].Item1.SignalAndWait();
int i = 0;
while (i < priority - 1)
{
while (!ShouldClose)
{
Main();
SwapBuffers();
PollEvents();
frameTimeProvider.WaitNextSpan();
Interlocked.Add(ref _frameCount, 1);
}
barrierList[i].Item2.SignalAndWait();
barrierList[i + 1].Item1.SignalAndWait();
}
else
barrierList[priority - 1].Item1.SignalAndWait();
InternalIO.glfwSwapBuffers(windowID);
InternalIO.glfwPollEvents();
frameTimeProvider.WaitNextSpan();
Interlocked.Add(ref _frameCount, 1);
}
FrameAsyncThread.TerminateAll(singleFrameAsyncThreadList);
foreach ((Barrier, Barrier) bPair in barrierList)
{
bPair.Item1.SignalAndWait();
bPair.Item2.SignalAndWait();
}
FrameAsyncThread.WaitAll(singleFrameAsyncThreadList);
//InternalDeinit();
}
private void GahterSignleFrameAsyncThread(MethodInfo[] methods)
{
if (methods.Length == 0)
{
return;
}
foreach (MethodInfo m in methods) //find all methods decorated by RenderActivityAttribute
{
RenderActivityAttribute attr = m.GetCustomAttribute<RenderActivityAttribute>(false);
if (attr == null)
{
while (!ShouldClose)
{
b.Item1.SignalAndWait();
Main();
b.Item2.SignalAndWait();
SwapBuffers();
PollEvents();
frameTimeProvider.WaitNextSpan();
Interlocked.Add(ref _frameCount, 1);
}
FrameAsyncThread.TerminateAll(frameAsyncThreadList);
b.Item1.SignalAndWait();
FrameAsyncThread.WaitAll(frameAsyncThreadList);
continue;
}
//InternalDeinit();
if (!m.IsStatic && (m.GetParameters().Length != 0) && (m.ReturnType != typeof(void)))
{
throw new NotSupportedException("A render activity cannot have parameters, returning value or be static.");
}
ThreadStart s = (ThreadStart)Delegate.CreateDelegate(typeof(ThreadStart), this, m);
FrameAsyncThread thread = new(s, attr._priority);
singleFrameAsyncThreadList.Add(thread);
}
}
private void GatherMultiFrameAsyncThread(MethodInfo[] methods)
{
if (methods.Length == 0)
{
return;
}
foreach (MethodInfo m in methods) //find all methods decorated by RenderActivityAttribute
{
MultiFrameActivityAttribute attr = m.GetCustomAttribute<MultiFrameActivityAttribute>(false);
if (attr == null)
{
continue;
}
if (!m.IsStatic && (m.GetParameters().Length != 0) && (m.ReturnType != typeof(void)))
{
throw new NotSupportedException("A render activity cannot have parameters, returning value or be static.");
}
ThreadStart s = (ThreadStart)Delegate.CreateDelegate(typeof(ThreadStart), this, m);
FrameAsyncThread thread = new(s, 0);
multiFrameAsyncThreadList.Add(thread);
}
}
}
}
@@ -48,9 +48,9 @@ namespace StgSharp.Graphics
private ConcurrentQueue<IntPtr> _funcQueue;
private readonly unsafe GLcontext* currentContext;
public unsafe FrameOperationBuffer(IglFunc gl)
public unsafe FrameOperationBuffer()
{
currentContext = gl.Context;
currentContext = GL.api;
_funcQueue = new ConcurrentQueue<IntPtr>();
}
@@ -497,9 +497,10 @@ namespace StgSharp.Graphics
public class FrameAsyncThread
{
private int _priority;
private Thread _task;
private volatile int _terminateToken;
private int _priority;
protected Barrier _frameSpeedSyncBarrier;
@@ -518,7 +519,7 @@ namespace StgSharp.Graphics
public int Priority
{
get => _priority;
internal set { _priority = value; }
internal set => _priority = value;
}
public ThreadStart TaskTODO
@@ -545,7 +546,6 @@ namespace StgSharp.Graphics
_taskTODO();
_spanCompleteBarrier.SignalAndWait();
}
Console.WriteLine("Thread terminated");
});
_task.Start();
}
@@ -558,14 +558,6 @@ namespace StgSharp.Graphics
}
}
public static void WaitAll(IEnumerable<FrameAsyncThread> threadList)
{
foreach (FrameAsyncThread t in threadList)
{
t._task.Join();
}
}
public static (Barrier, Barrier) CombineAsync(bool needOuterMonitor, IEnumerable<FrameAsyncThread> taskList)
{
if (taskList.Count() == 0)
@@ -597,10 +589,24 @@ namespace StgSharp.Graphics
}
return (b_start, b_complete);
}
public static Barrier CombineAsyncAfter(Barrier begin, bool needOuterMonitor, IEnumerable<FrameAsyncThread> taskList)
{
if (taskList.Count() == 0)
{
return null;
}
Barrier b_complete = new Barrier(taskList.Count() + (needOuterMonitor ? 1 : 0));
foreach (FrameAsyncThread item in taskList)
{
item._frameSpeedSyncBarrier = begin;
item._spanCompleteBarrier = b_complete;
}
return b_complete;
}
public void Terminate()
{
Interlocked.Exchange(ref _terminateToken,0);
Interlocked.Exchange(ref _terminateToken, 0);
}
public static void TerminateAll(params FrameAsyncThread[] threadList)
@@ -619,6 +625,14 @@ namespace StgSharp.Graphics
}
}
public static void WaitAll(IEnumerable<FrameAsyncThread> threadList)
{
foreach (FrameAsyncThread t in threadList)
{
t._task.Join();
}
}
}
@@ -41,9 +41,8 @@ namespace StgSharp.Graphics
/// </summary>
public abstract class BufferObjectBase : IDisposable
{
protected IntPtr binding;
protected glHandleSet _bufferHandle;
protected IglFunc binding;
/// <summary>
/// Get the only handle to one of the Object instance
+6 -6
View File
@@ -48,27 +48,27 @@ namespace StgSharp.Graphics
internal ElementBuffer(int n, Form binding)
{
this.binding = binding.GL;
_bufferHandle = this.binding.GenBuffers(n);
this.binding = binding.graphicContextID;
_bufferHandle = GL.GenBuffers(n);
}
public override sealed void Bind(int index)
{
binding.BindBuffer(BufferType.ELEMENT_ARRAY_BUFFER, _bufferHandle[index]);
GL.BindBuffer(BufferType.ELEMENT_ARRAY_BUFFER, _bufferHandle[index]);
}
public void SetValue<T>(int index, T[] bufferArray, BufferUsage usage)
where T : struct, IConvertible
{
binding.BindBuffer(BufferType.ELEMENT_ARRAY_BUFFER, _bufferHandle[index]);
binding.SetBufferData(BufferType.ELEMENT_ARRAY_BUFFER, bufferArray, usage);
GL.BindBuffer(BufferType.ELEMENT_ARRAY_BUFFER, _bufferHandle[index]);
GL.SetBufferData(BufferType.ELEMENT_ARRAY_BUFFER, bufferArray, usage);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
{
binding.DeleteBuffers(_bufferHandle);
GL.DeleteBuffers(_bufferHandle);
_bufferHandle.Release();
}
}
+6 -6
View File
@@ -40,26 +40,26 @@ namespace StgSharp.Graphics
internal VertexArray(int n, Form binding)
{
this.binding = binding.GL;
_bufferHandle = this.binding.GenVertexArrays(n);
this.binding = binding.graphicContextID;
_bufferHandle = GL.GenVertexArrays(n);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override sealed void Bind(int index)
{
binding.BindVertexArray(_bufferHandle[index]);
GL.BindVertexArray(_bufferHandle[index]);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void BindNull()
{
binding.BindVertexArray(glHandle.Zero);
GL.BindVertexArray(glHandle.Zero);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetVertexAttribute(uint index, int vertexLength, TypeCode dataType, bool isNomalized, uint stride, int pointer)
{
binding.SetVertexAttribute(
GL.SetVertexAttribute(
index, vertexLength, dataType,
isNomalized,
stride, pointer);
@@ -69,7 +69,7 @@ namespace StgSharp.Graphics
{
if (disposing)
{
binding.DeleteVertexArrays(_bufferHandle);
GL.DeleteVertexArrays(_bufferHandle);
_bufferHandle.Release();
}
}
+9 -9
View File
@@ -45,13 +45,13 @@ namespace StgSharp.Graphics
internal VertexBuffer(int n, Form binding)
{
this.binding = binding.GL;
_bufferHandle = this.binding.GenBuffers(n);
this.binding = binding.graphicContextID;
_bufferHandle = GL.GenBuffers(n);
}
public override sealed void Bind(int index)
{
binding.BindBuffer(BufferType.ARRAY_BUFFER, _bufferHandle[index]);
GL.BindBuffer(BufferType.ARRAY_BUFFER, _bufferHandle[index]);
}
/// <summary>
@@ -63,8 +63,8 @@ namespace StgSharp.Graphics
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void SetValue<T>(int index, T bufferData, BufferUsage usage) where T : struct, IMat
{
binding.BindBuffer(BufferType.ARRAY_BUFFER, _bufferHandle[index]);
binding.SetBufferData(BufferType.ARRAY_BUFFER, bufferData, usage);
GL.BindBuffer(BufferType.ARRAY_BUFFER, _bufferHandle[index]);
GL.SetBufferData(BufferType.ARRAY_BUFFER, bufferData, usage);
}
/// <summary>
@@ -76,8 +76,8 @@ namespace StgSharp.Graphics
/// <param name="usage">How OpenGL use these data, defined by <see cref="BufferUsage"/></param>
public void SetValueArray<T>(int index, T[] bufferArray, BufferUsage usage) where T : struct, IConvertible
{
binding.BindBuffer(BufferType.ARRAY_BUFFER, _bufferHandle[index]);
binding.SetBufferData(BufferType.ARRAY_BUFFER, bufferArray, usage);
GL.BindBuffer(BufferType.ARRAY_BUFFER, _bufferHandle[index]);
GL.SetBufferData(BufferType.ARRAY_BUFFER, bufferArray, usage);
}
/// <summary>
@@ -86,14 +86,14 @@ namespace StgSharp.Graphics
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Unbind()
{
binding.BindBuffer(BufferType.ARRAY_BUFFER, glHandle.Zero);
GL.BindBuffer(BufferType.ARRAY_BUFFER, glHandle.Zero);
}
protected override sealed void Dispose(bool disposing)
{
if (disposing)
{
binding.DeleteBuffers(_bufferHandle);
GL.DeleteBuffers(_bufferHandle);
_bufferHandle.Release();
}
}
@@ -44,25 +44,25 @@ namespace StgSharp.Graphics
{
internal static bool[] unitActivated = new bool[16];
private Form binding;
private IntPtr binding;
internal glHandleSet _textureHandle;
internal Image[] sourceList;
internal Texture(int n, Form binding)
{
sourceList = new Image[n];
this.binding = binding;
_textureHandle = binding.GL.GenTextures(n);
this.binding = binding.graphicContextID;
_textureHandle = GL.GenTextures(n);
}
public void Activate(TextureUnit unit)
{
binding.GL.ActiveTexture((uint)unit);
GL.ActiveTexture((uint)unit);
}
public void Bind2D(int index)
{
binding.GL.BindTexture(GLconst.TEXTURE_2D, _textureHandle[index]);
GL.BindTexture(GLconst.TEXTURE_2D, _textureHandle[index]);
}
/// <summary>
@@ -72,7 +72,7 @@ namespace StgSharp.Graphics
/// <param name="loader"> </param>
public unsafe void LoadTexture(int index, string name, ImageLoader loader)
{
Image.ImageInfo info = default;
ImageInfo info = default;
InternalIO.InternalLoadImage(name, &info, loader);
sourceList[index] = new Image(info);
if (sourceList[index].info.pixelPtr != IntPtr.Zero)
@@ -92,7 +92,7 @@ namespace StgSharp.Graphics
channel = 0;
break;
}
binding.GL.TextureImage2d<byte>(
GL.TextureImage2d<byte>(
GLconst.TEXTURE_2D, 0, channel,
(uint)sourceList[index].Width, (uint)sourceList[index].Height,
channel, GLconst.UNSIGNED_BYTE,
@@ -111,15 +111,15 @@ namespace StgSharp.Graphics
public void Set2dFilterProperty(
Filter onMinify, Filter onMagnify)
{
binding.GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MIN_FILTER, (int)onMinify);
binding.GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MAG_FILTER, (int)onMagnify);
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MIN_FILTER, (int)onMinify);
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_MAG_FILTER, (int)onMagnify);
}
public void Set2dWrapProperty(
Wrap onHorizontial, Wrap onVertical)
{
binding.GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_S, (int)onHorizontial);
binding.GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_T, (int)onVertical);
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_S, (int)onHorizontial);
GL.TextureParameter(GLconst.TEXTURE_2D, GLconst.TEXTURE_WRAP_T, (int)onVertical);
}
#endregion texture setting
+21 -89
View File
@@ -44,39 +44,27 @@ namespace StgSharp.Graphics
/// <summary>
/// A handle to an OpenGL object,
/// must be indexed from a <see cref="glHandleSet"/>.
/// Direct call will cause <see langword="InvalidOperationException"/>
/// Attempt at direct creating an instance will cause <see cref="InvalidOperationException"/>
/// </summary>
public unsafe struct glHandle
{
internal glHandleSet source;
internal uint* valuePtr;
private glHandle(IntPtr handle)
internal glHandle(int index, GCHandle arrayHandle)
{
this.valuePtr = (uint*)handle;
source = null;
}
internal glHandle(uint* val, glHandleSet set)
{
source = set;
valuePtr = val;
valuePtr = ((uint*)GCHandle.ToIntPtr(arrayHandle)) + index;
}
[Obsolete("Cannot init instance of this type", true)]
public glHandle()
{
throw new InvalidOperationException();
}
public IntPtr Handle
{
get
{
if (source.handle == (uint*)0)
{
throw new InvalidOperationException($"Handle set {nameof(source)} is not pinned.");
}
return (IntPtr)valuePtr;
}
}
@@ -85,68 +73,29 @@ namespace StgSharp.Graphics
{
get
{
if (source.handle == (uint*)0)
{
throw new InvalidOperationException($"Handle set {nameof(source)} is not pinned.");
}
return *valuePtr;
}
set
{
if (source.handle == (uint*)0)
{
throw new InvalidOperationException($"Handle set {nameof(source)} is not pinned.");
}
*valuePtr = value;
}
}
public static glHandle Zero => Alloc(0);
internal uint DirectValue => *valuePtr;
public static glHandle Alloc(uint value)
{
glHandle ret = default;
ret.source = new glHandleSet(1);
ret.valuePtr = ret.source.handle;
*ret.valuePtr = value;
return ret;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static glHandle Alloc(IntPtr handle)
{
return new glHandle(handle);
}
}
public unsafe struct glSHandle
{
internal glHandleSet source;
internal int* valuePtr;
internal glSHandle(int* val, glHandleSet set)
internal glSHandle(int index, glHandleSet set)
{
source = set;
valuePtr = val;
}
public static glSHandle Zero => Alloc(0);
internal int DirectValue => *valuePtr;
public static glSHandle Alloc(int value)
{
glSHandle ret = default;
ret.source = new glHandleSet(1);
ret.valuePtr = (int*)ret.source.handle;
*ret.valuePtr = value;
return ret;
}
}
public unsafe class glArrayHandle
@@ -202,15 +151,20 @@ namespace StgSharp.Graphics
public unsafe class glHandleSet
{
private readonly uint[] _value;
internal uint* handle;
private uint[] _value;
internal GCHandle handle;
internal int length;
public glHandleSet(int count)
{
_value = new uint[count];
length = count;
handle = (uint*)GCHandle.Alloc(_value, GCHandleType.Pinned).AddrOfPinnedObject();
handle = GCHandle.Alloc(_value);
}
public IntPtr Handle
{
get => GCHandle.ToIntPtr(handle);
}
public glHandle this[int index]
@@ -221,7 +175,7 @@ namespace StgSharp.Graphics
{
throw new IndexOutOfRangeException();
}
return new glHandle(handle + index, this);
return new glHandle(index, this.handle);
}
}
@@ -233,7 +187,7 @@ namespace StgSharp.Graphics
{
throw new IndexOutOfRangeException();
}
return new glSHandle(((int*)handle) + index, this);
return new glSHandle((int)index, this);
}
}
@@ -253,30 +207,6 @@ namespace StgSharp.Graphics
}
}
/// <summary>
/// temporarily release the handle of GLhandle sets.
/// Please call <see cref="Pin"/> method before indexing.
/// </summary>
public void Free()
{
if (_value == null)
{
return;
}
GCHandle h = GCHandle.FromIntPtr((IntPtr)handle);
h.Free();
handle = (uint*)0;
}
public void Pin()
{
if (_value == null)
{
return;
}
handle = (uint*)GCHandle.Alloc(_value, GCHandleType.Pinned).AddrOfPinnedObject();
}
/// <summary>
/// Release all resource in this handle.
/// This will release all resource in this <see cref="glHandle"/>.
@@ -284,17 +214,19 @@ namespace StgSharp.Graphics
/// </summary>
public void Release()
{
if (_value == null)
if (handle == default)
{
return;
}
else
{
GCHandle.FromIntPtr((IntPtr)handle).Free();
handle = (uint*)IntPtr.Zero;
handle.Free();
_value = null;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetValue(int index, uint value)
{
@@ -40,89 +40,72 @@ using System.Text;
namespace StgSharp.Graphics
{
internal unsafe partial class GLpack : IglFunc
internal unsafe static partial class GL
{
private FrameTimeoutException refreshSIgnal = new FrameTimeoutException();
internal GLcontext* api;
internal GLpack(GLcontext* context)
{
api = context;
}
internal static GLcontext* api;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.ActiveTexture(uint type)
public static void ActiveTexture(uint type)
{
api->glActiveTexture(type);
}
void IglFunc.AfterAlign(Form form, Action action)
{
throw new NotImplementedException();
}
void IglFunc.AlignFrame(Form form)
{
throw new NotImplementedException();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.AttachShader(glHandle program, glHandle shader)
public static void AttachShader(glHandle program, glHandle shader)
{
api->glAttachShader(*program.valuePtr, shader.DirectValue);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.BindBuffer(BufferType bufferType, glHandle handle)
public static void BindBuffer(BufferType bufferType, glHandle handle)
{
api->glBindBuffer((uint)bufferType, handle.DirectValue);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.BindTexture(uint type, glHandle texture)
public static void BindTexture(uint type, glHandle texture)
{
api->glBindTexture(type, texture.DirectValue);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.BindVertexArray(glHandle handle)
public static void BindVertexArray(glHandle handle)
{
api->glBindVertexArray(handle.Value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.Clear(MaskBufferBit mask)
public static void Clear(MaskBufferBit mask)
{
api->glClear((uint)mask);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.ClearColor(float R, float G, float B, float A)
unsafe public static void ClearColor(float R, float G, float B, float A)
{
api->glClearColor(R, G, B, A);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.ClearGraphicError()
unsafe public static void ClearGraphicError()
{
while (api->glGetError() != 0) { }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.CompileShader(glHandle shaderhandle)
public static void CompileShader(glHandle shaderhandle)
{
api->glCompileShader(shaderhandle.DirectValue);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
glHandle IglFunc.CreateProgram()
public static glHandle CreateProgram()
{
return glHandle.Alloc(api->glCreateProgram());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe glHandleSet IglFunc.CreateProgram(int count)
public static unsafe glHandleSet CreateProgram(int count)
{
glHandleSet h = new glHandleSet(count);
for (int i = 0; i < count; i++)
@@ -133,7 +116,7 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
glHandleSet IglFunc.CreateShaderSet(int count, ShaderType type)
public static glHandleSet CreateShaderSet(int count, ShaderType type)
{
glHandleSet ret = new glHandleSet(count);
uint t = (uint)type;
@@ -151,7 +134,7 @@ namespace StgSharp.Graphics
return ret;
}
unsafe IntPtr IglFunc.CreateWindowHandle(
public static unsafe IntPtr CreateWindowHandle(
int width, int height, string tittle, IntPtr monitor, Form share)
{
byte[] tittleBytes = Encoding.UTF8.GetBytes(tittle);
@@ -178,33 +161,33 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe glHandle IglFunc.CreatGraphicProgram()
public static unsafe glHandle CreateGraphicProgram()
{
return glHandle.Alloc(api->glCreateProgram());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.DeleteBuffer(glHandle handle)
unsafe public static void DeleteBuffer(glHandle handle)
{
api->glDeleteBuffers(1, (uint*)handle.Handle);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.DeleteBuffers(glHandleSet handle)
unsafe public static void DeleteBuffers(glHandleSet handle)
{
api->glDeleteBuffers((uint)handle.length, handle.handle);
handle.Free();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.DeleteVertexArrays(glHandleSet arrays)
unsafe public static void DeleteVertexArrays(glHandleSet arrays)
{
api->glDeleteVertexArrays((uint)arrays.length, arrays.handle);
arrays.Free();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.DrawElements(GepmetryType mode, uint count, TypeCode type, IntPtr ptr)
unsafe public static void DrawElements(GepmetryType mode, uint count, TypeCode type, IntPtr ptr)
{
uint a;
switch (type)
@@ -230,13 +213,8 @@ namespace StgSharp.Graphics
api->glDrawElements((uint)mode, count, a, (void*)ptr);
}
void IglFunc.frameworkHandleEnqueue(System.IntPtr handle, params M128[] param)
{
throw new InvalidOperationException();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe glHandleSet IglFunc.GenBuffers(int count)
public static unsafe glHandleSet GenBuffers(int count)
{
glHandleSet h = new glHandleSet(count);
api->glGenBuffers((uint)count, h.handle);
@@ -244,15 +222,15 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe glHandleSet IglFunc.GenTextures(int count)
public static unsafe glHandleSet GenTextures(int count)
{
glHandleSet h = new glHandleSet(count);
api->glGenTextures((uint)count, h.handle);
api->glGenTextures(count, (uint*)h.Handle);
return h;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe glHandleSet IglFunc.GenVertexArrays(int count)
public static unsafe glHandleSet GenVertexArrays(int count)
{
glHandleSet h = new glHandleSet(count);
api->glGenVertexArrays((uint)count, h.handle);
@@ -260,7 +238,7 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe glSHandle IglFunc.GetUniformLocation(glHandle program, string name)
public static unsafe glSHandle GetUniformLocation(glHandle program, string name)
{
byte[] code = Encoding.UTF8.GetBytes(name);
fixed (byte* ptr = code)
@@ -270,13 +248,7 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe bool IglFunc.GetWindowShouldClose(Form form)
{
return InternalIO.glfwWindowShouldClose(form.id) == 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.LoadShaderSource(glHandle shaderHandle, string codeStream)
unsafe public static void LoadShaderSource(glHandle shaderHandle, string codeStream)
{
byte[] stream = Encoding.UTF8.GetBytes(codeStream);
fixed (byte* streamPtr = stream)
@@ -286,7 +258,7 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.MakeContexCurrent(Form form)
public unsafe static void MakeContexCurrent(Form form)
{
if (form.WindowID == IntPtr.Zero)
{
@@ -297,7 +269,7 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.SetBufferData<T>(BufferType bufferType, T bufferData, BufferUsage usage)
public unsafe static void SetBufferData<T>(BufferType bufferType, T bufferData, BufferUsage usage)
{
int size = Marshal.SizeOf<T>();
T* p = &bufferData;
@@ -309,7 +281,7 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.SetBufferData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
public unsafe static void SetBufferData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage)
{
int size = bufferArray.Length * Marshal.SizeOf(typeof(T));
if (bufferArray == null)
@@ -327,16 +299,15 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.SetVertexAttribute(uint index, int size, TypeCode t, bool normalized, uint stride, int pointer)
public static void SetVertexAttribute(uint index, int size, TypeCode t, bool normalized, uint stride, int pointer)
{
uint type = InternalIO.GLtype[t];
api->glVertexAttribPointer(index, size, type, normalized ? 1 : 0, stride, (void*)pointer);
api->glEnableVertexAttribArray(index);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.TextureImage2d<T>(int target, int level, uint internalformat, uint width, uint height, uint format, uint type, glHandle pixels)
public static void TextureImage2d<T>(int target, int level, uint internalformat, uint width, uint height, uint format, uint type, glHandle pixels)
{
api->glTexImage2D(
(uint)target, level, internalformat, width, height, 0, format, type, pixels.valuePtr
@@ -344,25 +315,22 @@ namespace StgSharp.Graphics
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.TextureParameter(int target, uint pname, int param)
public static void TextureParameter(int target, uint pname, int param)
{
api->glTexParameteri((uint)target, pname, param);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.UseProgram(glHandle program)
public static void UseProgram(glHandle program)
{
api->glUseProgram(program.DirectValue);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void IglFunc.Viewport(int x, int y, uint width, uint height)
public static void Viewport(int x, int y, uint width, uint height)
{
api->glViewport(x, y, width, height);
}
GLcontext* IglFunc.Context
=> api;
}
}
}
@@ -44,7 +44,7 @@ namespace StgSharp.Graphics
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected Shader CreateShader(ShaderType type, int count)
{
return new Shader(this.gl, gl.CreateShaderSet(count, type), type);
return new Shader( GL.CreateShaderSet(count, type), type);
}
/// <summary>
/// Create an instance of <see cref="Shader"/> program
@@ -61,23 +61,22 @@ namespace StgSharp.Graphics
public class Shader
{
private readonly IglFunc GL;
internal readonly glHandleSet handle;
private readonly IntPtr context;
internal readonly GLhandle handle;
public readonly ShaderType type;
internal Shader(IglFunc gl, glHandleSet handle, ShaderType usage)
internal unsafe Shader(uint[] handle, ShaderType usage)
{
this.handle = handle;
GL = gl;
context = (IntPtr)GL.api;
type = usage;
}
//TODO:写链接着色器的文档注释
/// <summary>
///
/// Attach one shader code to a shader program.
/// </summary>
/// <param name="target"></param>
/// <param name="index"></param>
/// <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)
{
@@ -105,7 +104,7 @@ namespace StgSharp.Graphics
public class ShaderProgram
{
private readonly Form binding;
private readonly IntPtr binding;
internal readonly glHandle handle;
/// <summary>
@@ -113,8 +112,8 @@ namespace StgSharp.Graphics
/// </summary>
internal unsafe ShaderProgram(Form binding)
{
this.binding = binding;
handle = binding.GL.CreateProgram();
this.binding = binding.graphicContextID;
handle = GL.CreateProgram();
}
/// <summary>
@@ -153,7 +152,21 @@ namespace StgSharp.Graphics
where U : struct
where V : struct
{
return new Uniform<T, U, V>(this, name, binding);
return new Uniform<T, U, V>(this, name);
}
/// <summary>
/// Get a uniform form current shader,
/// the value type of the uniform should be provided.
/// </summary>
/// <param name="name">Name 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>(this, name);
}
/// <summary>
@@ -161,7 +174,7 @@ namespace StgSharp.Graphics
/// </summary>
public unsafe void Link()
{
if (InternalIO.InternalLinkShaderProgram(binding.GL.Context, handle.Value) == 0)
if (InternalIO.InternalLinkShaderProgram((GLcontext*)this.binding, handle.Value) == 0)
{
IntPtr logPtr = InternalIO.InternalReadSSCLog();
try
@@ -185,7 +198,7 @@ namespace StgSharp.Graphics
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Use()
{
binding.GL.UseProgram(handle);
GL.UseProgram(handle);
}
}
@@ -29,6 +29,7 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Math;
using System;
using System.Collections.Generic;
@@ -37,16 +38,19 @@ using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Graphics.GL.ShaderEdit
namespace StgSharp.Graphics.ShaderEdit
{
public class ShaderGenerator
{
private Dictionary<int,ShaderParameter> uniformDefine;
private List<string> codeList;
private List<ShaderFunction> usedShaderFunctions;
public Uniform<T> DefineUniform<T>() where T : struct
public Uniform<T> DefineUniform<T>(string name, int index) where T : struct
{
ShaderParameter p = new ShaderParameter(name,ShaderParameter.TypeMarshal<T>());
uniformDefine.Add(index,p);
//return new Uniform<T>();
throw new NotImplementedException();
}
@@ -54,7 +58,6 @@ namespace StgSharp.Graphics.GL.ShaderEdit
public class ShaderFunction
{
private List<string> codeList;
private List<ShaderParameter> inputList;
private string name;
@@ -100,7 +103,6 @@ namespace StgSharp.Graphics.GL.ShaderEdit
public class ShaderParameter
{
public static readonly ShaderParameter Void = new ShaderParameter(string.Empty, InternalShaderType.Void);
internal readonly bool isReadOnly;
internal readonly string name;
@@ -125,6 +127,48 @@ namespace StgSharp.Graphics.GL.ShaderEdit
}
}
public static InternalShaderType TypeMarshal<T>() where T : struct
{
switch (Type.GetTypeCode(typeof(T)))
{
case TypeCode.Single:
return InternalShaderType.Float;
case TypeCode.Double:
return InternalShaderType.Double;
case TypeCode.Int32:
return InternalShaderType.Int;
case TypeCode.UInt32:
return InternalShaderType.UInt;
default:
break;
}
switch (typeof(T).Name)
{
case "Vec4d":
return InternalShaderType.Vector4;
case "Matrix2x2":
return InternalShaderType.Matrix2x2;
case "Matrix2x3":
return InternalShaderType.Matrix2x3;
case "Matrix2x4":
return InternalShaderType.Matrix2x4;
case "Matrix3x2":
return InternalShaderType.Matrix3x2;
case "Matrix3x3":
return InternalShaderType.Matrix3x3;
case "Matrix3x4":
return InternalShaderType.Matrix3x4;
case "Matrix4x2":
return InternalShaderType.Matrix4x2;
case "Matrix4x3":
return InternalShaderType.Matrix4x3;
case "Matrix4x4":
return InternalShaderType.Matrix4x4;
default:
throw new ArgumentException("Not supported shader data type.");
}
}
}
public enum InternalShaderType
@@ -42,7 +42,7 @@ namespace StgSharp.Graphics
public class Uniform<T> where T : struct
{
private Form binding;
private IntPtr binding;
internal glSHandle id;
internal unsafe Uniform(glSHandle id)
@@ -52,9 +52,15 @@ namespace StgSharp.Graphics
internal unsafe Uniform(
ShaderProgram program, string name, Form binding)
{
this.binding = binding.graphicContextID;
id = GL.GetUniformLocation(program.handle, name);
}
internal unsafe Uniform(
ShaderProgram program, string name, IntPtr binding)
{
this.binding = binding;
id = binding.GL.GetUniformLocation(program.handle, name);
id = GL.GetUniformLocation(program.handle, name);
}
}
@@ -64,7 +70,7 @@ namespace StgSharp.Graphics
where U : struct
{
private Form binding;
private IntPtr binding;
internal glSHandle id;
internal unsafe Uniform(glSHandle id)
@@ -74,9 +80,16 @@ namespace StgSharp.Graphics
internal unsafe Uniform(
ShaderProgram program, string name, Form binding)
{
this.binding = binding.graphicContextID;
id = GL.GetUniformLocation(program.handle, name);
}
internal unsafe Uniform(
ShaderProgram program, string name, IntPtr binding)
{
this.binding = binding;
id = binding.GL.GetUniformLocation(program.handle, name);
id = GL.GetUniformLocation(program.handle, name);
}
}
@@ -87,7 +100,7 @@ namespace StgSharp.Graphics
where V : struct
{
private Form binding;
private IntPtr binding;
internal glSHandle id;
internal unsafe Uniform(glSHandle id)
@@ -95,10 +108,17 @@ namespace StgSharp.Graphics
this.id = id;
}
internal unsafe Uniform(
ShaderProgram program, string name)
{
this.binding = (IntPtr)GL.api;
id = GL.GetUniformLocation(program.handle, name);
}
public unsafe Uniform(ShaderProgram program, string name, Form binding)
{
this.binding = binding;
id = binding.GL.GetUniformLocation(program.handle, name);
this.binding = binding.graphicContextID;
id = GL.GetUniformLocation(program.handle, name);
}
}
@@ -110,7 +130,7 @@ namespace StgSharp.Graphics
where W : struct
{
private Form binding;
private IntPtr binding;
internal glSHandle id;
internal unsafe Uniform(glSHandle id)
@@ -120,55 +140,62 @@ namespace StgSharp.Graphics
internal unsafe Uniform(ShaderProgram program, string name, Form binding)
{
this.binding = binding;
id = binding.GL.GetUniformLocation(program.handle, name);
this.binding = binding.graphicContextID;
id = GL.GetUniformLocation(program.handle, name);
}
internal unsafe Uniform(
ShaderProgram program, string name)
{
this.binding = (IntPtr)GL.api;
id = GL.GetUniformLocation(program.handle, name);
}
}
internal partial class GLpack : IglFunc
internal static partial class GL
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void SetValue(Uniform<float, float, float, float> uniform, Vec4d vec)
public unsafe static void SetValue(Uniform<float, float, float, float> uniform, Vec4d vec)
{
api->glUniform1fv(uniform.id.DirectValue, 4, &vec);
api->glUniform1fv(uniform.id.DirectValue , 4, &vec);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void SetValue(Uniform<Vec4d> uniform, Vec4d vec)
public unsafe static void SetValue(Uniform<Vec4d> uniform, Vec4d vec)
{
api->glUniform1fv(uniform.id.DirectValue, 4, &vec);
api->glUniform1fv(uniform.id.DirectValue , 4, &vec);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.SetValue(Uniform<float> uniform, float v0)
public static unsafe void SetValue(Uniform<float> uniform, float v0)
{
api->glUniform1f(uniform.id.DirectValue, v0);
api->glUniform1f(uniform.id.DirectValue , v0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.SetValue(Uniform<int> uniform, int i0)
public static unsafe void SetValue(Uniform<int> uniform, int i0)
{
api->glUniform1i(uniform.id.DirectValue, i0);
api->glUniform1i(uniform.id.DirectValue , i0);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.SetValue(Uniform<float, float> uniform, float v0, float v1)
public static unsafe void SetValue(Uniform<float, float> uniform, float v0, float v1)
{
api->glUniform2f(uniform.id.DirectValue, v0, v1);
api->glUniform2f(uniform.id.DirectValue , v0, v1);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.SetValue(Uniform<float, float, float> uniform, float v0, float v1, float v2)
public static unsafe void SetValue(Uniform<float, float, float> uniform, float v0, float v1, float v2)
{
api->glUniform3f(uniform.id.DirectValue, v0, v1, v2);
api->glUniform3f(uniform.id.DirectValue , v0, v1, v2);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
unsafe void IglFunc.SetValue(Uniform<float, float, float, float> uniform, float v0, float v1, float v2, float v3)
public static unsafe void SetValue(Uniform<float, float, float, float> uniform, float v0, float v1, float v2, float v3)
{
api->glUniform4f(uniform.id.DirectValue, v0, v1, v2, v3);
api->glUniform4f(uniform.id.DirectValue , v0, v1, v2, v3);
}
}
@@ -60,13 +60,10 @@ namespace StgSharp.Graphics
/// </summary>
/// <param name="form">The <see cref="Form"/> used as current OpenGL context</param>
/// <param name="loader">A delegate to get address of OprnGL api</param>
public static unsafe void LoadGLapi(this Form form, GLfuncLoader loader)
public static unsafe void LoadGLapi(this Form form)
{
GLcontext* context = (GLcontext*)form.graphicContextID;
if (loader == null)
{
loader = InternalIO.glfwGetProcAddress;
}
GLfuncLoader loader = InternalIO.glfwGetProcAddress;
#pragma warning disable CS8909
if (((GLcontext*)form.graphicContextID)->glGetString != (delegate*<uint, IntPtr>)IntPtr.Zero)
#pragma warning restore CS8909
-336
View File
@@ -1,336 +0,0 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="IglFunc.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.Concurrent;
using System.ComponentModel.Design;
namespace StgSharp.Graphics
{
public interface IglFunc
{
internal unsafe GLcontext* Context
{
get;
}
/// <summary>
/// Same function as OpenGL api glActiveTexture
/// </summary>
/// <param name="type">type of texture to activate</param>
void ActiveTexture(uint type);
/// <summary>
/// Operation after alignment by calling <see cref="AlignFrame(Form)"/>.
/// No calling of this method is acceptable, but it will bring the risk
/// of that relevant code will not run if it is interrupted by frame overtime.
/// Please call this method immediately after calling <see cref="AlignFrame(Form)"/>,
/// too early or sonner may cause <see cref="InvalidOperationException"/>.
/// </summary>
/// <param name="form">The form used as frame update benchmark.</param>
/// <param name="action">Operation after frame update alignment.</param>
/// <exception cref="InvalidOperationException">The action binded to a wrong alignment.</exception>
void AfterAlign(Form form, Action action);
/// <summary>
/// Align a sets of code to frame update of a <see cref="Form"/>.
/// Usually, a call of <see cref="AfterAlign(Form,Action)"/> is required.
/// This method is used as sigle thread method. If more than one
/// alignment is requested, a <see cref="InvalidOperationException"/> will throw.
/// </summary>
/// <param name="form">The form used as frame update benchmark.</param>
/// <exception cref="InvalidOperationException">More than one alingment attached to one form timer</exception>
void AlignFrame(Form form);
/// <summary>
/// Same fucntion as OpenGL api glAttachShader.
/// Only the first <see href="shader"/> in handle
/// will be attached to the first <see href="program"/> in handle.
/// The rest shader and program will be ignored.
/// </summary>
/// <param name="program">Shader program to be attachec</param>
/// <param name="shader">A shader part to attach</param>
void AttachShader(glHandle program, glHandle shader);
//TODO:BindBuffer注释没写完
/// <summary>
/// Bind the indexed buffer object to certain type of buffer
/// </summary>
/// <param name="bufferType"></param>
/// <param name="handle"></param>
void BindBuffer(BufferType bufferType, glHandle handle);
/// <summary>
/// Same function as OpenGL api, glBindTexture.
/// </summary>
/// <param name="type">Type of texture to bind</param>
/// <param name="texture">Sign of texture</param>
void BindTexture(uint type, glHandle texture);
/// <summary>
/// Same function as OpenGL api, glBindVertexArray
/// </summary>
/// <param name="index"></param>
void BindVertexArray(glHandle index);
/// <summary>
/// Clear buffers to preset values
/// </summary>
/// <param name="mask"></param>
void Clear(MaskBufferBit mask);
/// <summary>
/// Call apiClearColor in OpenGL
/// specifies the red, green, blue, and alpha values used by apiClear to clear the color buffers.
/// Values specified by apiClearColor are clamped to the range [0,1]
/// </summary>
/// <param name="R">Specify the red values used when the color buffers are cleared.</param>
/// <param name="G">Specify the red values used when the color buffers are cleared.</param>
/// <param name="B">Specify the red values used when the color buffers are cleared.</param>
/// <param name="A">Specify the red values used when the color buffers are cleared.</param>
void ClearColor(float R, float G, float B, float A);
void ClearGraphicError();
void CompileShader(glHandle shaderhandle);
/// <summary>
/// Same function as OpenGL api, glCreateProgram
/// </summary>
/// <returns>A handle representing a single shader program</returns>
glHandle CreateProgram();
/// <summary>
/// Same function as OpenGL api, glCreateProgram.
/// Used for creating multiple shader program.
/// </summary>
/// <returns>A handle representing all shader programs</returns>
glHandleSet CreateProgram(int count);
glHandleSet CreateShaderSet(int count, ShaderType type);
/// <summary>
/// Creates a form and its associated
/// </summary>
/// <param name="width">Required width</param>
/// <param name="height">Required width</param>
/// <param name="tittle">Tittle of the window </param>
/// <param name="monitor"></param>
/// <param name="share"></param>
/// <exception cref="Exception"></exception>
IntPtr CreateWindowHandle(int width, int height, string tittle, IntPtr monitor, Form share);
glHandle CreatGraphicProgram();
/// <summary>
/// Same function as OpenGL api, glDeleteBuffer. This method can delete one buffer in one call
/// </summary>
/// <param name="handle">a handle representing the buffer to be deleted</param>
void DeleteBuffer(glHandle handle);
/// <summary>
/// Same function as OpenGL api, glDeleteBuffer. This method can delete a sets of buffers in one call.
/// </summary>
/// <param name="handleSet">Array of buffers to be deleted</param>
unsafe void DeleteBuffers(glHandleSet handleSet);
/// <summary>
/// Same function as OpenGL api, glDeleteVertexArrays
/// </summary>
/// <param name="handleSet">Handle of vertex objects.</param>
unsafe void DeleteVertexArrays(glHandleSet handleSet);
/// <summary>
///
/// </summary>
/// <param name="mode"></param>
/// <param name="count"></param>
/// <param name="type"></param>
/// <param name="ptr"></param>
void DrawElements(GepmetryType mode, uint count, TypeCode type, IntPtr ptr);
/// <summary>
/// Same fucntion as the OpenGL api glGenBuffers
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
unsafe glHandleSet GenBuffers(int count);
/// <summary>
/// Same fucnction as OpenGL api glGenTextures.
/// </summary>
/// <param name="count">amount of textures to generate</param>
unsafe glHandleSet GenTextures(int count);
/// <summary>
/// Same fucntion as OpenGL api, glGenVertexArray
/// </summary>
/// <param name="count">Amount of vao to be generated</param>
unsafe glHandleSet GenVertexArrays(int count);
/// <summary>
/// Same fucntion as OpenGL api, glGetUniformLocation
/// </summary>
/// <param name="program">Shader program to find the uniform</param>
/// <param name="name">Name of the uniform </param>
/// <returns></returns>
unsafe glSHandle GetUniformLocation(glHandle program, string name);
bool GetWindowShouldClose(Form form);
void LoadShaderSource(glHandle shaderHandle, string codeStream);
/// <summary>
/// Make the OpenGL context of a certain <see cref="Form"/> as the activated OpenGL context.
/// </summary>
/// <param name="form"></param>
void MakeContexCurrent(Form form);
void SetBufferData<T>(BufferType bufferType, T bufferData, BufferUsage usage) where T : struct, IMat;
void SetBufferData<T>(BufferType bufferType, T[] bufferArray, BufferUsage usage) where T : struct, IConvertible;
/// <summary>
/// Set data value to a float <see cref="Uniform{T,U,V,W}"/>,
/// all types of parameters are float.
/// </summary>
/// <param name="uniform">The <see cref="Uniform{T,U,V,W}"/> target</param>
/// <param name="vec">A <see cref="Vec4d"/> packing four parameters of the uniform </param>
void SetValue(Uniform<float, float, float, float> uniform, Vec4d vec);
/// <summary>
/// Set data value to a float <see cref="Uniform{T}"/>,
/// all types of parameters are float.
/// </summary>
/// <param name="uniform">The <see cref="Uniform{T}"/> target</param>
/// <param name="v0">The value to be set</param>
void SetValue(Uniform<float> uniform, float v0);
/// <summary>
/// Set data value to a int <see cref="Uniform{T}"/>,
/// all types of parameters are int.
/// </summary>
/// <param name="uniform">The <see cref="Uniform{T}"/> target</param>
/// <param name="i0">The value to be set</param>
void SetValue(Uniform<int> uniform, int i0);
/// <summary>
/// Set data value to a float <see cref="Uniform{T}"/>,
/// all types of parameters are <see cref="Vec4d"/>.
/// </summary>
/// <param name="uniform">The <see cref="Uniform{T}"/> target</param>
/// <param name="vec">A <see cref="Vec4d"/> value of the uniform </param>
void SetValue(Uniform<Vec4d> uniform, Vec4d vec);
/// <summary>
/// Set data value to a float <see cref="Uniform{T,U}"/>,
/// all types of parameters are float.
/// </summary>
/// <param name="uniform">The <see cref="Uniform{T,U}"/> target</param>
/// <param name="v0">The first value to be set</param>
/// <param name="v1">The second value to be set</param>
void SetValue(Uniform<float, float> uniform, float v0, float v1);
/// <summary>
/// Set data value to a float <see cref="Uniform{T,U,V}"/>,
/// all types of parameters are float.
/// </summary>
/// <param name="uniform">The <see cref="Uniform{T,U,V}"/> target</param>
/// <param name="v0">The first value to be set</param>
/// <param name="v1">The second value to be set</param>
/// <param name="v2">The third value to be set</param>
void SetValue(Uniform<float, float, float> uniform, float v0, float v1, float v2);
/// <summary>
/// Set data value to a float <see cref="Uniform{T,U,V,W}"/>,
/// all types of parameters are float.
/// </summary>
/// <param name="uniform">The <see cref="Uniform{T,U,V,W}"/> target</param>
/// <param name="v0">The first value to be set</param>
/// <param name="v1">The second value to be set</param>
/// <param name="v2">The third value to be set</param>
/// <param name="v3">The forth value to be set</param>
void SetValue(Uniform<float, float, float, float> uniform, float v0, float v1, float v2, float v3);
/// <summary>
/// Set how a shader parameter read data from a VBO.
/// </summary>
/// <param name="index">Serial number of the parameter</param>
/// <param name="size">Amount of data each elements contains</param>
/// <param name="t">Type of data read by shader</param>
/// <param name="normalized"></param>
/// <param name="stride">Pixels stride of each sets of data</param>
/// <param name="pointer"></param>
void SetVertexAttribute(uint index, int size, TypeCode t, bool normalized, uint stride, int pointer);
/// <summary>
/// Same function as OpenGL api glTexImage2d
/// </summary>
/// <param name="target">texture target to load image in</param>
/// <param name="level">level of mipmap, 0 if default</param>
/// <param name="internalformat">OpenGL's internal color channel format</param>
/// <param name="width">width of image</param>
/// <param name="height">height of image</param>
/// <param name="format">color channels of this image</param>
/// <param name="type">how this image express each pixel</param>
/// <param name="pixels">data array of pixels</param>
unsafe void TextureImage2d<T>(int target, int level, uint internalformat, uint width, uint height, uint format, uint type, glHandle pixels) where T : struct;
/// <summary>
/// Same fucntion as OpenGL api glTexParameteri
/// </summary>
/// <param name="target">texture target to set parameters</param>
/// <param name="pname">name of parameter</param>
/// <param name="param">value of parameter</param>
void TextureParameter(int target, uint pname, int param);
/// <summary>
/// Same fucntion as OpenGL api glUseShader.
/// </summary>
/// <param name="program">Sign of program to be used</param>
void UseProgram(glHandle program);
/// <summary>
/// Same function as the OpenGL api, glViewPort
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="width"></param>
/// <param name="height"></param>
void Viewport(int x, int y, uint width, uint height);
internal void frameworkHandleEnqueue(IntPtr handle, params M128[] param);
}
}
+15 -10
View File
@@ -69,16 +69,21 @@ namespace StgSharp.Graphics
Marshal.FreeHGlobal(info.pixelPtr);
}
[StructLayout(LayoutKind.Sequential)]
internal struct ImageInfo
{
internal int width;
internal int height;
internal int channel;
internal IntPtr pixelPtr;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct ImageInfo
{
internal int width;
internal int height;
internal int channel;
internal IntPtr pixelPtr;
public override string ToString()
{
return $"{channel}\t{width}\t{height}\t{pixelPtr}";
}
}
}