This commit is contained in:
Nitload
2024-06-10 15:12:08 +08:00
parent f6963b8e00
commit be6c2e6b92
305 changed files with 28336 additions and 5938 deletions
-1
View File
@@ -1 +0,0 @@
D:/NitloadIndustry/研究项目/1-Flagship/TH2020/ProjectFile/源代码/StgSharp/Logic
@@ -0,0 +1,254 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Blueprint.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp;
using StgSharp.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace StgSharp.Logic
{
public partial class Blueprint : IConvertableToBlueprintNode
{
private BeginningNode beginNode;
private Dictionary<string, BlueprintNode> allNode;
private EndingNode endNode;
private Func<bool> terminate;
private int currentNodeIndex;
private List<Task> allThread;
private List<BlueprintNode> nativeNodeList;
private List<BlueprintNode> nodeList;
public Blueprint()
{
allNode = new Dictionary<string, BlueprintNode>();
allThread = new List<Task>();
nodeList = new List<BlueprintNode>();
nativeNodeList = new List<BlueprintNode>();
terminate = () => true;
beginNode = new BeginningNode();
endNode = new EndingNode();
}
public BlueprintNode BeginLayer => beginNode;
public BlueprintNode EndLayer => endNode;
public bool IsRunning => allThread.Any(t => t.Status == TaskStatus.Running);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public (string name, BlueprintPipelineArgs arg)[] GetOutput()
{
return endNode.OutputData;
}
public void Init(int threadCount)
{
if (threadCount > nodeList.Count)
{
InternalIO.InternalWriteLog(
"Thread setting error: amount of threads of this blueprint is larger than amount of nodes.", LogType.Warning);
threadCount = nodeList.Count;
}
if (threadCount!=0)
{
foreach (var item in allNode)
{
if (item.Value.IsNative)
{
nativeNodeList.Add(item.Value);
}
else
{
nodeList.Add(item.Value);
}
}
nativeNodeList.Sort();
PrepareTasks(threadCount);
}
else
{
foreach (var item in allNode)
{
nodeList.Add(item.Value);
}
}
nodeList.Sort();
}
public void PrepareTasks(int count)
{
for (int i = 0; i < count; i++)
{
allThread.Add(new Task(IndividualTask));
}
}
private void IndividualTask()
{
do
{
BlueprintNode node;
while (RequestNextNode(out node))
{
node.Run();
}
} while (!terminate());
}
/// <summary>
/// Run all nodes repeatedly until it is instructed to terminate.
/// </summary>
/// <param name="terminateInstructor">Instructor to terminate all tasks. Returns <see langword="true"/> if tasks should terminate</param>
public void RunRepeatedly(Func<bool> terminateInstructor)
{
if (allThread.Count != 0)
{
MultiThreadRun(terminateInstructor);
return;
}
SingleThreadRun(terminateInstructor);
}
private void MultiThreadRun(Func<bool> terminateInstructor)
{
if (terminate != terminateInstructor)
{
terminate = terminateInstructor;
if (allThread.Count != 0)
{
foreach (var t in allThread)
{
t.Start();
}
}
}
beginNode.Run();
foreach (var node in nativeNodeList)
{
node.Run();
}
EndLayer.Run();
}
private void SingleThreadRun(Func<bool> terminateInstructor)
{
beginNode.Run();
foreach (var item in nodeList)
{
item.Run();
}
EndLayer.Run();
}
public void AddNativeNode(BlueprintNode node)
{
node.IsNative = true;
allNode.Add(node.Name, node);
}
public void AddAsyncNode(BlueprintNode node)
{
node.IsNative = false;
allNode.Add(node.Name, node);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetInput(params (string name, BlueprintPipelineArgs arg)[] parameters)
{
beginNode.InputData = parameters;
}
private bool RequestNextNode(out BlueprintNode node)
{
if (currentNodeIndex < nodeList.Count)
{
BlueprintNode ret = nodeList[currentNodeIndex];
Interlocked.Increment(ref currentNodeIndex);
node = ret;
return true;
}
Interlocked.Exchange(ref currentNodeIndex, 0);
node = default!;
return false;
}
string[] IConvertableToBlueprintNode.InputInterfacesName
{
get
{
return beginNode.OutputInterfaces.Select(
p => p.Key).ToArray();
}
}
BlueprintNodeAction IConvertableToBlueprintNode.MainExecution
{
get
{
return (in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output)
=>
{
beginNode.Run();
foreach (var node in nativeNodeList)
{
node.Run();
}
endNode.Run();
};
}
}
string[] IConvertableToBlueprintNode.OutputInterfacesName
{
get
{
return beginNode.OutputInterfaces.Select(
p => p.Key).ToArray();
}
}
}
internal class NodeClearException : Exception
{
}
}
@@ -0,0 +1,316 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="BlueprintNode.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.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Logic
{
public delegate void BlueprintNodeAction(
in Dictionary<string, BlueprintPipeline> inpput,
in Dictionary<string, BlueprintPipeline> output);
/// <summary>
///
/// </summary>
/// <risk>
/// Reset pipeline has risk, this operation is a direct operation to port
/// in current node, the port on the other node cannot get the change.
/// </risk>
#pragma warning disable CA1036
public class BlueprintNode : IComparable<BlueprintNode>
#pragma warning restore CA1036
{
private BlueprintNodeAction mainOperation;
private protected bool levelAvailable, nativeRequested;
private protected int _level;
private string name;
private protected Dictionary<string, BlueprintPipeline> _inputInterfaces;
private protected Dictionary<string, BlueprintPipeline> _outputInterfaces;
internal BlueprintNode(string name,
BlueprintNodeAction operation, bool isNative,
string[] inputPorts,
string[] outputPorts)
{
this.levelAvailable = false;
this.name = name;
nativeRequested = isNative;
mainOperation = operation;
_inputInterfaces = new Dictionary<string, BlueprintPipeline>();
_outputInterfaces = new Dictionary<string, BlueprintPipeline>();
if (inputPorts.Length == 0 )
{
throw new ArgumentNullException(nameof(inputPorts));
}
if (outputPorts.Length == 0)
{
throw new ArgumentNullException(nameof(outputPorts));
}
foreach (var portName in inputPorts)
{
_inputInterfaces.Add(portName, null);
}
foreach (var portName in outputPorts)
{
_outputInterfaces.Add(portName, null);
}
}
public BlueprintNode(string name, IConvertableToBlueprintNode convertable)
{
this.levelAvailable = false;
this.name = name;
_inputInterfaces = new Dictionary<string, BlueprintPipeline>();
_outputInterfaces = new Dictionary<string, BlueprintPipeline>();
mainOperation = convertable.MainExecution;
foreach (var soket in convertable.InputInterfacesName)
{
_inputInterfaces.Add(soket, null);
}
foreach (var soket in convertable.OutputInterfacesName)
{
_outputInterfaces.Add(soket, null);
}
}
public BlueprintNode(string name,
string[] inputPorts,
string[] outputPorts
)
{
this.levelAvailable = false;
this.name = name;
_inputInterfaces = new Dictionary<string, BlueprintPipeline>();
_outputInterfaces = new Dictionary<string, BlueprintPipeline>();
if (inputPorts.Length * outputPorts.Length == 0)
{
throw new Exception();
}
foreach (var portName in inputPorts)
{
_inputInterfaces.Add(portName, null);
}
foreach (var portName in outputPorts)
{
_outputInterfaces.Add(portName, null);
}
}
public bool IsNative
{
get => nativeRequested;
internal set => nativeRequested = value;
}
public int Level
{
get
{
if (levelAvailable)
{
return _level;
}
_level = 0;
foreach (var item in _inputInterfaces)
{
if (item.Value == null)
{
continue;
}
if (_level <= item.Value.Level)
{
_level = item.Value.Level;
}
}
_level += 1;
return _level;
}
}
public string Name => name;
internal Dictionary<string, BlueprintPipeline> InputInterfaces => _inputInterfaces;
internal Dictionary<string, BlueprintPipeline> OutputInterfaces => _outputInterfaces;
public void AddAfter(
BlueprintNode former,
string formerOutputPortName,
string thisInputPortName)
{
this.levelAvailable = false;
BlueprintPipeline pipeline = new BlueprintPipeline(former, this);
if (former is BeginningNode bnode)
{
bnode.SetCertainOutputPort(formerOutputPortName, pipeline);
}
else
{
former.SetCertainOutputPort(formerOutputPortName, pipeline);
}
SetCertainInputPort(thisInputPortName, pipeline);
}
public void AddBefore(
BlueprintNode after,
string thisOutputPortName,
string afterInputPortName)
{
this.levelAvailable = false;
BlueprintPipeline pipeline = new BlueprintPipeline(this, after);
if (after is EndingNode enode)
{
enode.SetCertainInputPort(afterInputPortName, pipeline);
}
else
{
after.SetCertainInputPort(afterInputPortName, pipeline);
}
SetCertainOutputPort(thisOutputPortName, pipeline);
}
public void Run()
{
try
{
//Console.WriteLine(name);
BlueprintPipeline.WaitAll(_inputInterfaces);
mainOperation(in _inputInterfaces, in _outputInterfaces);
}
catch (Exception)
{
throw;
}
}
public int CompareTo(BlueprintNode other)
{
#pragma warning disable CA1062
return this.Level.CompareTo(other.Level);
#pragma warning restore CA1062
}
#region port operation
public BlueprintPipeline GetCertainInputPort(string name)
{
BlueprintPipeline ret;
if (!_inputInterfaces.TryGetValue(name,out ret))
{
throw new Exception($"Cannot find the interface named {name} in node {Name}.");
}
return ret;
}
public BlueprintPipeline GetCertainOutputPort(string name)
{
BlueprintPipeline ret;
if (!_outputInterfaces.TryGetValue(name, out ret))
{
throw new Exception($"Cannot find the interface named {name} in node {Name}.");
}
return ret;
}
public void SetCertainInputPort(string name, BlueprintPipeline pipeline)
{
if (!_inputInterfaces.ContainsKey(name))
{
throw new Exception($"Cannot find the interface named {name} in node {Name}.");
}
_inputInterfaces[name] = pipeline;
}
public void SetCertainOutputPort(string name, BlueprintPipeline pipeline)
{
if (!_outputInterfaces.ContainsKey(name))
{
throw new Exception($"Cannot find the interface named {name} in node {Name}.");
}
_outputInterfaces[name] = pipeline;
}
#endregion
}//--------------------------------- end of class -----------------------------------
public interface IConvertableToBlueprintNode
{
public string[] InputInterfacesName { get; }
public BlueprintNodeAction MainExecution { get; }
public string[] OutputInterfacesName { get; }
}
public class BlueprintNodeRunException : Exception
{
public BlueprintNodeRunException()
{
}
public BlueprintNodeRunException(Exception ex) : base(string.Empty, ex)
{
}
public BlueprintNodeRunException(string message) : base(message)
{
}
public BlueprintNodeRunException(string message, Exception innerException) : base(message, innerException)
{
}
protected BlueprintNodeRunException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Logic
{
/*
public class CrossCycleProcess:BlueprintNode
{
public CrossCycleProcess(string name, Action operation)
:base()
{
}
}
/**/
}
@@ -0,0 +1,126 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="PipeLine.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Security.Authentication.ExtendedProtection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StgSharp.Logic
{
public class BlueprintPipeline
{
private BlueprintNode after;
private BlueprintNode former;
private BlueprintPipelineArgs args;
private SemaphoreSlim formerCompleteSemaphore;
public BlueprintPipeline(BlueprintNode former, BlueprintNode after)
{
this.former = former;
this.after = after;
formerCompleteSemaphore = new SemaphoreSlim(initialCount: 0, maxCount: 1);
}
public BlueprintNode After => after;
public BlueprintNode Former => former;
public int Level => former.Level;
public BlueprintPipelineArgs Args
{
get => args;
set => args = value;
}
public void CompleteAndSkip()
{
//Console.WriteLine($"Complete\t{former.ContextName}\t->\t{after.ContextName}");
formerCompleteSemaphore.Release();
}
public void CompleteAndWriteData(BlueprintPipelineArgs args)
{
this.args = args;
//Console.WriteLine($"Complete\t{former.ContextName}\t->\t{after.ContextName}");
formerCompleteSemaphore.Release();
}
public static void SkipAll(Dictionary<string, BlueprintPipeline> ports)
{
if (ports == null)
{
throw new ArgumentNullException(nameof(ports));
}
foreach (var item in ports)
{
if (item.Value!=null)
{
item.Value.CompleteAndSkip();
}
}
}
public static void WaitAll(Dictionary<string, BlueprintPipeline> ports)
{
if (ports == null)
{
throw new ArgumentNullException(nameof(ports));
}
foreach (var item in ports)
{
if (item.Value!=null)
{
item.Value.WaitForStart();
}
}
}
public void WaitForStart()
{
//Console.WriteLine($"Waiting \t{former.ContextName}\t->\t{after.ContextName}");
formerCompleteSemaphore.Wait();
}
}
public abstract class BlueprintPipelineArgs
{
public object? Value { get; set; }
}
}
@@ -0,0 +1,182 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="RouteSwitch.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace StgSharp.Logic
{
public class RouteSwitch : BlueprintNode
{
private protected Dictionary<string, (BlueprintPipeline pipeline, Func<bool> openingRule)> outputDictionary;
public RouteSwitch(string name, string inputPorts) :
base(name, [inputPorts], [string.Empty])
{
outputDictionary = new Dictionary<string, (BlueprintPipeline pipeline, Func<bool> openingRule)>();
}
public new int Level
{
get
{
if (levelAvailable)
{
return _level;
}
_level = 0;
KeyValuePair<string, BlueprintPipeline> item = _inputInterfaces.First();
if (item.Value == null)
{
throw new InvalidOperationException();
}
if (_level <= item.Value.Level)
{
_level = item.Value.Level;
}
return _level;
}
}
public new void AddBefore(
BlueprintNode after,
string thisOutputPortName,
string afterInputPortName)
{
this.AppendNode(after, afterInputPortName, () => true);
}
public void AppendNode(BlueprintNode node, string portName, Func<bool> openningRule)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
string indexName = $"{node.Name}.{portName}";
BlueprintPipeline p = new BlueprintPipeline(this, node);
node.InputInterfaces[portName] = p;
outputDictionary.Add(indexName, (p, openningRule));
}
public new void Run()
{
try
{
BlueprintPipeline input = InputInterfaces.First().Value;
input.WaitForStart();
foreach (KeyValuePair<string, (BlueprintPipeline pipeline, Func<bool> openingRule)> item in outputDictionary)
{
if (item.Value.openingRule())
{
item.Value.pipeline.CompleteAndWriteData(input.Args);
}
}
}
catch (Exception)
{
throw;
}
}
}
public sealed class RouteHub : BlueprintNode
{
private Dictionary<string, (BlueprintPipeline pipeline, Func<bool> controllingFunc)> inputDictionary;
public RouteHub(string name, string[] inputPorts, string[] outputPorts) : base(name, inputPorts, outputPorts)
{
inputDictionary = new Dictionary<string, (BlueprintPipeline pipeline, Func<bool> controllingFunc)>();
}
public new int Level
{
get
{
if (levelAvailable)
{
return _level;
}
_level = 0;
foreach (KeyValuePair<string, BlueprintPipeline> item in _inputInterfaces)
{
if (item.Value == null)
{
continue;
}
if (_level <= item.Value.Level)
{
_level = item.Value.Level;
}
}
return _level;
}
}
public void PrependNode(BlueprintNode node, string portName, Func<bool> usingRule)
{
if (node == null)
{
throw new ArgumentNullException(nameof(node));
}
string indexName = $"{node.Name}.{portName}";
BlueprintPipeline p = new BlueprintPipeline(this, node);
node.InputInterfaces[portName] = p;
inputDictionary.Add(indexName, (p, usingRule));
}
public new void Run()
{
try
{
foreach (KeyValuePair<string, (BlueprintPipeline pipeline, Func<bool> controllingFunc)> item in inputDictionary)
{
item.Value.pipeline.WaitForStart();
if (item.Value.controllingFunc())
{
_outputInterfaces.First().Value.CompleteAndWriteData(item.Value.pipeline.Args);
}
}
}
catch (Exception)
{
throw;
}
}
}
}
@@ -0,0 +1,86 @@
using StgSharp.Logic;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Logic
{
internal sealed class BeginningNode : BlueprintNode
{
public BeginningNode() : base(name: "BeginningNode", null,
true, ["default"], ["default"]
)
{ }
internal (string name, BlueprintPipelineArgs arg)[] InputData
{
set
{
if (value == null)
{
return;
}
foreach (var parameter in value)
{
OutputInterfaces[parameter.name].Args = parameter.arg;
}
}
}
public new void SetCertainOutputPort(string name, BlueprintPipeline pipeline)
{
if (_outputInterfaces.ContainsKey(name))
{
_outputInterfaces[name] = pipeline;
}
_outputInterfaces.Add(name, pipeline);
}
public new void Run()
{
BlueprintPipeline.SkipAll(_outputInterfaces);
}
}
internal sealed class EndingNode : BlueprintNode
{
public EndingNode() : base(name: "EndingNode",
operation: (
in Dictionary<string, BlueprintPipeline> input,
in Dictionary<string, BlueprintPipeline> output
) =>
{
},
true, ["default"], ["default"]
)
{ }
internal (string name, BlueprintPipelineArgs arg)[] OutputData
{
get
{
return InputInterfaces.Select(
key => (key.Key, key.Value.Args)).
ToArray();
}
}
public new void SetCertainInputPort(string name, BlueprintPipeline pipeline)
{
if (_inputInterfaces.ContainsKey(name))
{
_inputInterfaces[name] = pipeline;
}
_inputInterfaces.Add(name, pipeline);
}
public new void Run()
{
BlueprintPipeline.WaitAll(_inputInterfaces);
}
}
}
+151
View File
@@ -0,0 +1,151 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Counter.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Xml.Serialization;
namespace StgSharp
{
public class Counter<T> where T : struct, IConvertible, IFormattable, IComparable
{
internal readonly T _defualtAddValue;
internal readonly T _defualtSubValue;
internal readonly T _defualtValue;
internal dynamic _value;
public Counter(T defualtValue, T defualtAddValue, T defualtSubValue)
{
var type = Type.GetTypeCode(defualtValue.GetType());
switch (type)
{
case TypeCode.Byte:
break;
case TypeCode.Int16:
break;
case TypeCode.Int32:
break;
case TypeCode.Int64:
break;
case TypeCode.Double:
break;
case TypeCode.Single:
break;
case TypeCode.SByte:
break;
case TypeCode.UInt16:
break;
case TypeCode.UInt32:
break;
case TypeCode.UInt64:
break;
default:
throw new ArgumentException("Input is not number value type");
break;
}
_value = defualtValue;
_defualtValue = defualtValue;
_defualtAddValue = defualtAddValue;
_defualtSubValue = defualtSubValue;
}
public T Decreament => _defualtSubValue;
public T Increament => _defualtAddValue;
public T Span => _value - _defualtValue;
public T Value
{
get => _value;
set => _value = value;
}
public void Add(T value)
{
_value += value;
}
public void QuickAdd()
{
_value += _defualtAddValue;
}
public void QuickSub()
{
_value -= _defualtSubValue;
}
public void Reset()
{
_value = _defualtValue;
}
public void Sub(T value)
{
_value -= value;
}
public override string ToString()
{
return Value.ToString();
}
public static Counter<T> operator --(Counter<T> counter)
{
counter.QuickSub();
return counter;
}
public static Counter<T> operator ++(Counter<T> counter)
{
counter.QuickAdd();
return counter;
}
public static implicit operator T(Counter<T> counter)
{
return counter.Value;
}
}
}
@@ -0,0 +1,41 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Exception.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.Logic
{
}
+73
View File
@@ -0,0 +1,73 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="Sensor.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Geometries;
namespace StgSharp
{
public delegate bool SensorRuleHandler(PlainGeometry target, PlainGeometry boarder);
public class Sensor<T>
{
internal PlainGeometry _boarder;
internal SensorRuleHandler _rule;
internal PlainGeometry _target;
public PlainGeometry boarder => _boarder;
public SensorRuleHandler Rule
{
get => _rule;
set => _rule = value;
}
public PlainGeometry target
{
get => _target;
set => _target = value;
}
public static Sensor<T> operator -(Sensor<T> sensor, SensorRuleHandler rule)
{
sensor._rule -= rule;
return sensor;
}
public static Sensor<T> operator +(Sensor<T> sensor, SensorRuleHandler rule)
{
sensor._rule += rule;
return sensor;
}
}
}
@@ -0,0 +1,154 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TimeFunction.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp
{
public class TimeFunction
{
private float _beginning, _ending;
private Func<float, float> _timeRelatedCalculation;
private TimeSpanProvider _timeProvider;
internal TimeFunction() { }
public TimeFunction(
TimeSpanProvider timeSpanProvider,
Func<float, float> timeRelatedCalculation,
float range)
{
_timeProvider = timeSpanProvider;
_timeRelatedCalculation = timeRelatedCalculation;
if (timeSpanProvider == null)
{
return;
}
_beginning = _timeProvider.CurrentSecond;
_ending = _timeProvider.CurrentSecond + range;
}
public virtual bool IsComplete
{
get => _timeProvider.CurrentSecond > _ending;
}
public static TimeFunction One
{
get => new TimeFunctionOne();
}
public Func<float, float> TimeRelatedCalculation
{
get { return _timeRelatedCalculation; }
set { _timeRelatedCalculation = value; }
}
public TimeSpanProvider TimeSpanProvider
{
get { return _timeProvider; }
set { _timeProvider = value; }
}
public virtual float Calculate()
{
if (_timeProvider.CurrentSecond < _ending)
{
return 0;
}
return _timeRelatedCalculation(_timeProvider.CurrentSecond - _beginning);
}
public static TimeFunction Proportional(TimeSpanProvider time, float begin, float range)
{
return new TimeFunction(
time, (float t) => t + begin, range
);
}
public virtual TimeFunction Renew((Func<float, float> func, float range) funcPair)
{
return new TimeFunction(_timeProvider, funcPair.func, funcPair.range);
}
public virtual TimeFunction Renew(Func<float, float> func, float range)
{
return new TimeFunction(_timeProvider, func, range);
}
public void Reset()
{
float range = _ending - _beginning;
_beginning = _timeProvider.CurrentSecond;
_ending = _beginning + range;
}
}
public sealed class TimeFunctionOne : TimeFunction
{
internal TimeFunctionOne() : base()
{
}
public override bool IsComplete
{
get => true;
}
public override float Calculate()
{
return 1;
}
public override TimeFunction Renew((Func<float, float> func, float range) funcPair)
{
throw new NotSupportedException();
}
public override TimeFunction Renew(Func<float, float> func, float range)
{
throw new NotSupportedException();
}
#pragma warning disable CA1822
public new void Reset()
#pragma warning restore CA1822
{
}
}
}
@@ -0,0 +1,90 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TimeSourceProvider.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp;
using System;
using System.Linq;
using System.Threading;
namespace StgSharp.Logic
{
public abstract class TimeSourceProviderBase
{
private SemaphoreSlim _addSubscriberSemaphore = new SemaphoreSlim(1, 1);
protected SemaphoreSlim CheckSubscriberSemaphore
=> _addSubscriberSemaphore;
public void AddSubscriber(TimeSpanProvider subscriber)
{
_addSubscriberSemaphore.Wait();
try
{
AddSubscriberUnsynced(subscriber);
}
catch (Exception)
{
throw;
}
finally
{
_addSubscriberSemaphore.Release();
}
}
public void RemoveSubscriber(TimeSpanProvider subscriber)
{
_addSubscriberSemaphore.Wait();
try
{
RemoveSubscriberUnsynced(subscriber);
}
catch (Exception)
{
throw;
}
finally
{
_addSubscriberSemaphore.Release();
}
}
public abstract void StartProvidingTime();
protected abstract void AddSubscriberUnsynced(TimeSpanProvider subscriber);
protected abstract void RemoveSubscriberUnsynced(TimeSpanProvider subscriber);
}
}
@@ -0,0 +1,215 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="TimeSpanProvider.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Logic;
using System;
using System.Linq;
using System.Threading;
namespace StgSharp
{
/// <summary>
/// A microsecond-accuracy timer. It will refresh every a certain time span.
/// </summary>
public class TimeSpanProvider
{
private Action _frameUpdateMissCallback = () => { };
private Action _refreshCallback;
private bool _subscribed;
private Counter<int> timeSpanCount = new Counter<int>(-1, 1, 1);
private readonly int _maxSpanCount;
private long _spanBegin;
private readonly long _spanLength;
private SemaphoreSlim _refreshSemaphore = new SemaphoreSlim(0, 1);
private readonly TimeSourceProviderBase _timeSource;
/// <summary>
/// Create a new <see cref="TimeSpanProvider"/> and define the length of time span. Length of a single time span is defined in microseconds.
/// </summary>
/// <param name="spanMicroSeconds"></param>
/// <param name="provider"></param>
public TimeSpanProvider(long spanMicroSeconds, TimeSourceProviderBase provider)
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
_timeSource = provider;
_spanLength = spanMicroSeconds;
_maxSpanCount = int.MaxValue;
provider.AddSubscriber(this);
_subscribed = true;
_refreshCallback = new Action(() => { });
}
/// <summary>
/// Create a new <see cref="TimeSpanProvider"/> and define the length of time span.
/// Length of a single time span is defined in seconds.
/// </summary>
/// <param name="spanSeconds"></param>
/// <param name="provider"></param>
public TimeSpanProvider(double spanSeconds, TimeSourceProviderBase provider)
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
_spanLength = (long)(spanSeconds * 1000L * 1000L);
_spanBegin = -_spanLength;
_maxSpanCount = int.MaxValue;
provider.AddSubscriber(this);
_subscribed = true;
_refreshCallback = new Action(() => { });
}
/// <summary>
/// Create a new <see cref="TimeSpanProvider"/> and define the length of time span. Length of a single time span is defined in microseconds.
/// </summary>
/// <param name="spanLength"></param>
/// <param name="maxSpan"></param>
/// <param name="provider"></param>
public TimeSpanProvider(long spanLength, int maxSpan, TimeSourceProviderBase provider)
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
if (maxSpan <= 0)
{
maxSpan = int.MaxValue;
}
_spanLength = spanLength; _spanBegin = -_spanLength;
provider.AddSubscriber(this);
_subscribed = true;
}
public int CurrentSpan
{
get => timeSpanCount.Value;
}
public float CurrentSecond
{
get => timeSpanCount.Value * SpanLengthLowPrecession;
}
/// <summary>
/// Time source provider provided in <see cref="StgSharp"/> internal framework.
/// </summary>
public static TimeSourceProviderBase DefaultProvider => StgSharpTime.OnlyInstance;
public Action FrameUpdateMissCallback
{
get => _frameUpdateMissCallback;
set => _frameUpdateMissCallback = value;
}
public double SpanLength
{
get => (_spanLength * 1.0) / (1000L * 1000L);
}
public float SpanLengthLowPrecession
{
get => (_spanLength * 1.0f) / (1000 * 1000);
}
/// <summary>
/// The method this <see cref="TimeSpanProvider"/> will call every time a new time span started.
/// </summary>
public Action SpanRefreshCallback
{
get => _refreshCallback;
set => _refreshCallback = value;
}
public void SubscribeToTimeSource(TimeSourceProviderBase serviceHandler)
{
if (serviceHandler == null)
{
throw new ArgumentNullException(nameof(serviceHandler));
}
if (_subscribed)
{
return;
}
_subscribed = true;
serviceHandler.AddSubscriber(this);
}
public void WaitNextSpan()
{
_refreshSemaphore.Wait();
}
internal bool CheckTime(long microseconds)
{
if (microseconds - _spanBegin < _spanLength)
{
return true;
}
_spanBegin = microseconds;
timeSpanCount++;
if (_refreshCallback != null)
{
_refreshCallback();
}
if (_refreshSemaphore.CurrentCount == 0)
{
_refreshSemaphore.Release();
}
else
{
if (_frameUpdateMissCallback != null)
{
_frameUpdateMissCallback();
}
}
if (timeSpanCount > _maxSpanCount)
{
return false;
}
return true;
}
public static implicit operator int(TimeSpanProvider provider)
{
return provider.timeSpanCount.Value;
}
}
}
@@ -0,0 +1,54 @@
using StgSharp.Graphics;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace StgSharp.Logic
{
public abstract partial class ViewModelBase
{
public void ShowViewPort()
{
}
private Blueprint renderLogic;
public Blueprint RenderLogic
{
get => renderLogic;
set => renderLogic = value;
}
/// <summary>
/// Init this form and render it on screen, and respond with operation
/// </summary>
public unsafe void Show()
{
while(0 == InternalIO.glfwWindowShouldClose(this.context.ViewPortID))
{
renderLogic.RunRepeatedly(() => ShouldClose);
frameTimeProvider.WaitNextSpan();
Interlocked.Add(ref _frameCount, 1);
}
}
public T BuildNewRenderStream<T>(View arg, (int x, int y, int z) unitCubeSize) where T : RenderStream
{
if (arg.ContextName == this.Name)
{
}
T? ret = Activator.CreateInstance(typeof(T), arg) as T;
if (ret == null)
{
throw new InvalidOperationException("Failed in building a new RenderStream when calling AsMainStreamOf");
}
ret!.InternalInit();
ret.timeProvider = this.frameTimeProvider;
return ret;
}
}
}
@@ -0,0 +1,32 @@
using StgSharp.Graphics;
using StgSharp.Graphics.GL;
using System;
using System.Collections.Generic;
using System.Text;
namespace StgSharp.Logic
{
public partial class ViewModelBase
{
private List<View> allView;
public View BuildNewView(
ViewPortDesigner designer, (int x, int y, int z) unitCubeSize
)
{
View ret = new View(this.context, designer,unitCubeSize);
allView.Add(ret);
return ret;
}
public T BuildRenderStream<T>(View v, (int, int, int) cube) where T : RenderStream
{
T ret = Activator.CreateInstance(typeof(T), v.Port, cube) as T ??
throw new InvalidOperationException("Cannot build new render stream.");
ret.timeProvider = this.frameTimeProvider;
ret.InternalInit();
return ret;
}
}
}
@@ -0,0 +1,249 @@
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
// file="ViewModel.cs"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
using StgSharp.Graphics;
using StgSharp.Math;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace StgSharp.Logic
{
public abstract partial class ViewModelBase
{
private int _frameCount;
private int _frameSpeed;
private ViewPort context;
internal IntPtr monitor;
internal TimeSpanProvider fpsCountProvider;
internal TimeSpanProvider frameTimeProvider;
internal Vector4 backgroundColor;
protected ViewModelBase(int frameSpeed)
{
context = new ViewPort();
allView = new List<View>();
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
fpsCountProvider.SpanRefreshCallback =
() =>
{
Interlocked.Exchange(ref _frameSpeed, _frameCount);
Interlocked.Exchange(ref _frameCount, 0);
};
long frameLength = (FrameSpeed > 0) ? ((1000L * 1000L) / FrameSpeed) : 0;
frameTimeProvider = new TimeSpanProvider(
frameLength, TimeSpanProvider.DefaultProvider
);
frameTimeProvider.SpanRefreshCallback =
() =>
{
};
}
public ViewModelBase(ViewPort vbinding, int framespeed)
{
context = vbinding;
allView = new List<View>();
fpsCountProvider = new TimeSpanProvider(1.0, TimeSpanProvider.DefaultProvider);
_frameSpeed = 0;
_frameCount = 0;
fpsCountProvider.SpanRefreshCallback =
() =>
{
Interlocked.Exchange(ref _frameSpeed, _frameCount);
Interlocked.Exchange(ref _frameCount, 0);
};
long frameLength = (FrameSpeed > 0) ? ((1000L * 1000L) / FrameSpeed) : 0;
frameTimeProvider = new TimeSpanProvider(
frameLength, TimeSpanProvider.DefaultProvider
);
frameTimeProvider.SpanRefreshCallback =
() =>
{
};
}
public int CurrentFrameCount => frameTimeProvider.CurrentSpan;
public int FrameSpeed => _frameSpeed;
/// <summary>
/// Height of this form, represent in <see cref="int"/>
/// </summary>
public int Height
{
get => context.Height;
set { context.Height = value; }
}
public string Name
{
get => context.Name;
}
public bool ShouldClose
{
get => InternalIO.glfwWindowShouldClose(context.ViewPortID) != 0;
set => InternalIO.glfwSetWindowShouldClose(context.ViewPortID, value ? 1 : 0);
}
/// <summary>
/// Width of this form, represent in <see cref="int"/>
/// </summary>
public vec2d Size
{
get => new vec2d(Width, Height);
set
{
Width = (int)value.X;
Height = (int)value.Y;
if (WindowID != IntPtr.Zero)
{
InternalIO.glfwSetWindowSize(context.ViewPortID, Width, Height);
}
}
}
/// <summary>
/// Width of this form, represent in <see cref="int"/>
/// </summary>
public int Width
{
get => context.Width;
set
{
context.Width = value;
if (WindowID != IntPtr.Zero)
{
InternalIO.glfwSetWindowSize(context.ViewPortID, Width, Height);
}
}
}
public unsafe IntPtr WindowID
{
get => context.ViewPortID;
}
#pragma warning disable CA1044
protected FrameBufferSizeHandler FrameSizeCallback
{
set
{
IntPtr handlerPtr = Marshal.GetFunctionPointerForDelegate(value);
InternalIO.glfwSetFramebufferSizeCallback(context.ViewPortID, handlerPtr);
}
}
#pragma warning restore CA1044
/// <summary>
/// Resize the current form
/// </summary>
/// <param name="size">
/// A <see cref="vec2d"/> (width,height) representing the new size of current form
/// </param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetSize(vec2d size)
{
this.Size = size;
InternalIO.glfwSetWindowSize(this.context.ViewPortID, (int)size.X, (int)size.Y);
}
/// <summary>
/// Set the size limit of current form
/// </summary>
/// <param name="minSize">
/// Minimum size of current form. In form of a <see cref="vec2d"/> of (width,height)
/// </param>
/// <param name="maxSize">
/// Maximum size of current form. In form of a <see cref="vec2d"/> of (width,height)
/// </param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetSizeLimit(vec2d minSize, vec2d maxSize)
{
InternalIO.glfwSetWindowSizeLimits(
this.context.ViewPortID,
(int)minSize.X,
(int)minSize.Y,
(int)maxSize.X,
(int)maxSize.Y);
}
/// <summary>
/// Set the size limit of current form
/// </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 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)
{
//TODO 重做form的尺寸极限控制
InternalIO.glfwSetWindowSizeLimits(this.context.ViewPortID, minWidth, minHeight, maxWidth, maxHeight);
}
#region Key Control
protected KeyStatus CheckKey(KeyboardKey key)
{
return InternalIO.glfwGetKey(this.WindowID, (int)key);
}
protected KeyStatus CheckKey(Mouse key)
{
return InternalIO.glfwGetKey(this.WindowID, (int)key);
}
protected KeyStatus CheckKey(Joystick key)
{
return InternalIO.glfwGetKey(this.WindowID, (int)key);
}
#endregion
}
}