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
+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();
}
}
}