Compare commits

...

2 Commits

40 changed files with 1273 additions and 177 deletions

View File

@ -0,0 +1,20 @@
namespace Dashboard.Events
{
public class AnimationTickEventArgs : UiEventArgs
{
/// <summary>
/// Animation delta time in seconds.
/// </summary>
public float Delta { get; }
public AnimationTickEventArgs(float delta) : base(UiEventType.AnimationTick)
{
Delta = delta;
}
}
public interface IAnimationTickEvent
{
event EventHandler<AnimationTickEventArgs> AnimationTimerEvent;
}
}

View File

@ -0,0 +1,69 @@
using System.Drawing;
using System.Numerics;
namespace Dashboard.Events
{
[Flags]
public enum MouseButtons
{
M1 = 1 << 0,
M2 = 1 << 1,
M3 = 1 << 2,
M4 = 1 << 3,
M5 = 1 << 4,
M6 = 1 << 5,
M7 = 1 << 6,
M8 = 1 << 7,
Left = M1,
Right = M2,
Middle = M3,
}
public sealed class MouseMoveEventArgs : UiEventArgs
{
public Vector2 ClientPosition { get; }
public Vector2 Delta { get; }
public MouseMoveEventArgs(Vector2 clientPosition, Vector2 delta)
: base(UiEventType.MouseMove)
{
ClientPosition = clientPosition;
Delta = delta;
}
}
public sealed class MouseButtonEventArgs : UiEventArgs
{
public Vector2 ClientPosition { get; }
public MouseButtons Buttons { get; }
public MouseButtonEventArgs(Vector2 clientPosition, MouseButtons buttons, bool up)
: base(up ? UiEventType.MouseButtonUp : UiEventType.MouseButtonDown)
{
ClientPosition = clientPosition;
Buttons = buttons;
}
}
public sealed class MouseScrollEventArgs : UiEventArgs
{
public Vector2 ClientPosition { get; }
public Vector2 ScrollDelta { get; }
public MouseScrollEventArgs(Vector2 clientPosition, Vector2 scrollDelta)
: base(UiEventType.MouseScroll)
{
ClientPosition = clientPosition;
ScrollDelta = scrollDelta;
}
}
public interface IMouseEvents
{
event EventHandler<MouseMoveEventArgs> MouseMoved;
event EventHandler<MouseButtonEventArgs> MouseButtonDown;
event EventHandler<MouseButtonEventArgs> MouseButtonUp;
event EventHandler<MouseScrollEventArgs> MouseScroll;
}
}

View File

@ -0,0 +1,76 @@
using System.Numerics;
namespace Dashboard.Events
{
public enum UiEventType
{
None,
AnimationTick, // Generic timer event.
// Text input related events.
KeyDown, // Keyboard key down.
KeyUp, // Keyboard key up.
TextInput, // Non-IME text event.
TextEdit, // IME text event.
TextCandidates, // IME text candidate list.
TextLanguage, // Keyboard language changed event.
// Mouse & touch related events
MouseButtonDown, // Mouse button down.
MouseButtonUp, // Mouse button up.
MouseMove, // Mouse moved.
MouseScroll, // Mouse scrolled.
// Reserved event names
StylusEnter, // The stylus has entered the hover region.
StylusLeave, // The stylus has left the hover region.
StylusMove, // The stylus has moved.
StylusDown, // The stylus is touching.
StylusUp, // The stylus is no longer touching.
StylusButtonUp, // Stylus button up.
StylusButtonDown, // Stylus button down.
StylusAxes, // Extra stylus axes data.
// Window & Control Events
ControlInvalidateVisual, // Force rendering the control again.
ControlStateChanged, // Control state changed.
ControlMoved, // Control moved.
ControlResized, // Control resized.
ControlEnter, // The pointing device entered the control.
ControlLeave, // The pointing device left the control.
ControlFocusGet, // The control acquired focus.
ControlFocusLost, // The control lost focus.
WindowClose, // The window closed.
UserRangeStart = 1 << 12,
}
public class UiEventArgs : EventArgs
{
public UiEventType Type { get; }
public UiEventArgs(UiEventType type)
{
Type = type;
}
public static readonly UiEventArgs None = new UiEventArgs(UiEventType.None);
}
public class ControlMovedEventArgs : UiEventArgs
{
public Vector2 OldPosition { get; }
public Vector2 NewPosition { get; }
public ControlMovedEventArgs(Vector2 oldPosition, Vector2 newPosition) : base(UiEventType.ControlMoved)
{
OldPosition = oldPosition;
NewPosition = newPosition;
}
}
public class ControlResizedEventArgs
{
}
}

View File

@ -0,0 +1,43 @@
namespace Dashboard.Windowing
{
/// <summary>
/// Interface for a class that composites multiple windows together.
/// </summary>
public interface ICompositor : IDisposable
{
void Composite(IPhysicalWindow window, IEnumerable<IVirtualWindow> windows);
}
/// <summary>
/// Interface for classes that implement a window manager.
/// </summary>
public interface IWindowManager : IEnumerable<IVirtualWindow>, IEventListener, IPaintable, IDisposable
{
/// <summary>
/// The physical window that this window manager is associated with.
/// </summary>
IPhysicalWindow PhysicalWindow { get; }
/// <summary>
/// The compositor that will composite all virtual windows.
/// </summary>
ICompositor Compositor { get; set; }
/// <summary>
/// The window that is currently focused.
/// </summary>
IVirtualWindow? FocusedWindow { get; }
/// <summary>
/// Create a virtual window.
/// </summary>
/// <returns>Virtual window handle.</returns>
IVirtualWindow CreateWindow();
/// <summary>
/// Focus a virtual window, if it is owned by this window manager.
/// </summary>
/// <param name="window">The window to focus.</param>
void Focus(IVirtualWindow window);
}
}

View File

@ -0,0 +1,20 @@
using System.Drawing;
namespace Dashboard.Windowing
{
/// <summary>
/// Generic interface for the rendering system present in a <see cref="IPhysicalWindow"/>
/// </summary>
public interface IDeviceContext
{
/// <summary>
/// The swap group for this device context.
/// </summary>
ISwapGroup SwapGroup { get; }
/// <summary>
/// The size of the window framebuffer in pixels.
/// </summary>
Size FramebufferSize { get; }
}
}

View File

@ -0,0 +1,11 @@
namespace Dashboard.Windowing
{
public interface IEventListener
{
/// <summary>
/// Send an event to this windowing object.
/// </summary>
/// <param name="args">The event arguments sent.</param>
void SendEvent(EventArgs args);
}
}

View File

@ -0,0 +1,12 @@
namespace Dashboard.Windowing
{
public interface IPaintable
{
event EventHandler Painting;
/// <summary>
/// Paint this paintable object.
/// </summary>
void Paint();
}
}

View File

@ -0,0 +1,18 @@
namespace Dashboard.Windowing
{
/// <summary>
/// Interface that is used to swap the buffers of windows
/// </summary>
public interface ISwapGroup
{
/// <summary>
/// The swap interval for this swap group.
/// </summary>
public int SwapInterval { get; set; }
/// <summary>
/// Swap buffers.
/// </summary>
void Swap();
}
}

View File

@ -0,0 +1,74 @@
using System.Drawing;
using Dashboard.Events;
namespace Dashboard.Windowing
{
/// <summary>
/// Base class of all Dashboard windows.
/// </summary>
public interface IWindow :
IPaintable,
IDisposable,
IAnimationTickEvent,
IMouseEvents
{
/// <summary>
/// Name of the window.
/// </summary>
string Title { get; set; }
/// <summary>
/// The size of the window that includes the window extents.
/// </summary>
SizeF OuterSize { get; set; }
/// <summary>
/// The size of the window that excludes the window extents.
/// </summary>
SizeF ClientSize { get; set; }
}
/// <summary>
/// Base class for all Dashboard windows that are DPI-aware.
/// </summary>
public interface IDpiAwareWindow : IWindow
{
/// <summary>
/// DPI of the window.
/// </summary>
float Dpi { get; }
/// <summary>
/// Scale of the window.
/// </summary>
float Scale { get; }
}
/// <summary>
/// An object that represents a window in a virtual space, usually another window or a rendering system.
/// </summary>
public interface IVirtualWindow : IWindow, IEventListener
{
}
/// <summary>
/// An object that represents a native operating system window.
/// </summary>
public interface IPhysicalWindow : IWindow
{
/// <summary>
/// The device context for this window.
/// </summary>
IDeviceContext DeviceContext { get; }
/// <summary>
/// True if the window is double buffered.
/// </summary>
public bool DoubleBuffered { get; }
/// <summary>
/// The window manager for this physical window.
/// </summary>
public IWindowManager? WindowManager { get; set; }
}
}

View File

@ -1,5 +1,6 @@
using System.Drawing;
using Dashboard.Drawing.OpenGL.Executors;
using Dashboard.OpenGL;
namespace Dashboard.Drawing.OpenGL
{

View File

@ -1,3 +1,5 @@
using Dashboard.OpenGL;
namespace Dashboard.Drawing.OpenGL
{
public class ContextResourcePoolManager

View File

@ -9,11 +9,12 @@
<ItemGroup>
<PackageReference Include="BlurgText" Version="0.1.0-nightly-19" />
<PackageReference Include="OpenTK.Graphics" Version="5.0.0-pre.13" />
<PackageReference Include="OpenTK.Graphics" Version="[5.0.0-pre*,5.1)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Dashboard.Drawing\Dashboard.Drawing.csproj" />
<ProjectReference Include="..\Dashboard.OpenGL\Dashboard.OpenGL.csproj" />
</ItemGroup>
<ItemGroup>

View File

@ -1,6 +1,7 @@
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Dashboard.OpenGL;
using OpenTK.Graphics.OpenGL;
using OpenTK.Mathematics;
using Vector2 = System.Numerics.Vector2;

View File

@ -1,4 +1,5 @@
using Dashboard.Drawing.OpenGL.Text;
using Dashboard.OpenGL;
using OpenTK;
using OpenTK.Graphics;

View File

@ -1,4 +1,5 @@
using System.Runtime.InteropServices;
using Dashboard.OpenGL;
using OpenTK.Mathematics;
namespace Dashboard.Drawing.OpenGL

View File

@ -1,5 +1,6 @@
using System.Numerics;
using System.Runtime.CompilerServices;
using Dashboard.OpenGL;
using OpenTK.Graphics.OpenGL;
namespace Dashboard.Drawing.OpenGL

View File

@ -2,6 +2,7 @@ using System.Diagnostics;
using System.Drawing;
using System.Numerics;
using BlurgText;
using Dashboard.OpenGL;
using OpenTK.Graphics.OpenGL;
using OPENGL = OpenTK.Graphics.OpenGL;
@ -54,7 +55,7 @@ namespace Dashboard.Drawing.OpenGL.Text
path = Path.GetTempFileName();
try
{
dest = File.Open(path, FileMode.CreateNew, FileAccess.Write, FileShare.None);
dest = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
}
catch (IOException ex)
{
@ -71,14 +72,13 @@ namespace Dashboard.Drawing.OpenGL.Text
dest.Dispose();
DbBlurgFont font = (DbBlurgFont)LoadFont(path);
File.Delete(path);
return font;
}
public IFont LoadFont(string path)
{
BlurgFont? font = Blurg.AddFontFile(path) ?? throw new Exception("Failed to load the font file.");
return new DbBlurgFont(Blurg, font, 12f);
return new DbBlurgFont(Blurg, font, 12f) { Path = path };
}
public IFont LoadFont(NamedFont font)
@ -103,7 +103,12 @@ namespace Dashboard.Drawing.OpenGL.Text
{
if (dblurg.Owner != Blurg)
{
throw new Exception();
if (dblurg.Path == null)
return (DbBlurgFont)LoadFont(new NamedFont(dblurg.Family, dblurg.Size, dblurg.Weight,
dblurg.Slant,
dblurg.Stretch));
else
return (DbBlurgFont)LoadFont(dblurg.Path);
}
else
{

View File

@ -13,6 +13,8 @@ namespace Dashboard.Drawing.OpenGL.Text
public FontSlant Slant => Font.Italic ? FontSlant.Italic : FontSlant.Normal;
public FontStretch Stretch => FontStretch.Normal;
internal string? Path { get; init; }
public DbBlurgFont(Blurg owner, BlurgFont font, float size)
{
Owner = owner;

View File

@ -2,9 +2,7 @@
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.IO;
using System.Runtime.CompilerServices;
namespace Dashboard.Drawing
{
@ -160,7 +158,7 @@ namespace Dashboard.Drawing
{
byte b = bytes[i];
value = (value << 7) | b;
value |= (b & 0x7F) << (7*i);
if ((b & (1 << 7)) == 0)
{

View File

@ -0,0 +1,9 @@
using Dashboard.Windowing;
namespace Dashboard.Drawing
{
public interface IDrawQueuePaintable : IPaintable
{
DrawQueue DrawQueue { get; }
}
}

View File

@ -1,7 +1,6 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Net.Http;
using System.Numerics;
using System.Text;
using Dashboard.Drawing;

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Dashboard.Common\Dashboard.Common.csproj" />
</ItemGroup>
</Project>

View File

@ -1,11 +1,12 @@
using System.Drawing;
using Dashboard.Windowing;
namespace Dashboard.Drawing.OpenGL
namespace Dashboard.OpenGL
{
/// <summary>
/// Interface for GL context operations
/// </summary>
public interface IGLContext
public interface IGLContext : IDeviceContext
{
/// <summary>
/// The associated group for context sharing.
@ -22,21 +23,10 @@ namespace Dashboard.Drawing.OpenGL
/// Called when the context is disposed.
/// </summary>
event Action Disposed;
}
/// <summary>
/// Extension interface for GL contexts in a DPI-aware environment.
/// </summary>
public interface IDpiAwareGLContext : IGLContext
{
/// <summary>
/// Dpi for current context.
/// </summary>
public float Dpi { get; }
/// <summary>
/// Scale for the current context. This will be used to scale drawn geometry.
/// Activate this OpenGL Context.
/// </summary>
public float Scale { get; }
void MakeCurrent();
}
}

View File

@ -1,4 +1,4 @@
namespace Dashboard.Drawing.OpenGL
namespace Dashboard.OpenGL
{
/// <summary>
/// Interface much like <see cref="IDisposable"/> except GL resources are dropped.

View File

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="OpenTK" Version="[5.0.0-pre*,5.1)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Dashboard.OpenGL\Dashboard.OpenGL.csproj" />
<ProjectReference Include="..\Dashboard\Dashboard.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,18 @@
using Dashboard.Events;
using OpenTK.Platform;
namespace Dashboard.OpenTK.PAL2
{
public static class EventConverter
{
public static UiEventArgs? Convert(PlatformEventType type, EventArgs ea)
{
switch (type)
{
case PlatformEventType.KeyDown:
default:
return null;
}
}
}
}

View File

@ -0,0 +1,118 @@
using System.Collections.Concurrent;
using System.Drawing;
using Dashboard.OpenGL;
using Dashboard.Windowing;
using OpenTK.Mathematics;
using OpenTK.Platform;
using TK = OpenTK.Platform.Toolkit;
namespace Dashboard.OpenTK.PAL2
{
public class OpenGLDeviceContext : IGLContext, IGLDisposable
{
public OpenGLContextHandle ContextHandle { get; }
public WindowHandle WindowHandle { get; }
public ISwapGroup SwapGroup { get; }
public int ContextGroup { get; }
public Size FramebufferSize
{
get
{
TK.Window.GetFramebufferSize(WindowHandle, out Vector2i size);
return new Size(size.X, size.Y);
}
}
public event Action? Disposed;
public OpenGLDeviceContext(WindowHandle window, OpenGLContextHandle context, ISwapGroup? group = null)
{
WindowHandle = window;
ContextHandle = context;
SwapGroup = group ?? new DummySwapGroup(context);
ContextGroup = GetContextGroup(context);
}
public void MakeCurrent()
{
TK.OpenGL.SetCurrentContext(ContextHandle);
}
private bool _isDisposed = false;
public void Dispose() => Dispose(true);
public void Dispose(bool safeExit)
{
if (_isDisposed) return;
_isDisposed = true;
if (SwapGroup is IGLDisposable glDisposable)
{
glDisposable.Dispose(safeExit);
}
else if (SwapGroup is IDisposable disposable)
{
disposable.Dispose();
}
Disposed?.Invoke();
}
private static int _contextGroupId = 0;
private static ConcurrentDictionary<OpenGLContextHandle, int> _contextGroupRootContexts = new ConcurrentDictionary<OpenGLContextHandle, int>();
private static int GetContextGroup(OpenGLContextHandle handle)
{
OpenGLContextHandle? shared = TK.OpenGL.GetSharedContext(handle);
if (shared == null)
{
if (_contextGroupRootContexts.TryGetValue(handle, out int group))
return group;
group = Interlocked.Increment(ref _contextGroupId);
_contextGroupRootContexts.TryAdd(handle, group);
return GetContextGroup(handle);
}
else
{
if (_contextGroupRootContexts.TryGetValue(shared, out int group))
return group;
return GetContextGroup(shared);
}
}
public class DummySwapGroup : ISwapGroup
{
public OpenGLContextHandle ContextHandle { get; }
public int SwapInterval
{
get
{
TK.OpenGL.SetCurrentContext(ContextHandle);
return TK.OpenGL.GetSwapInterval();
}
set
{
TK.OpenGL.SetCurrentContext(ContextHandle);
TK.OpenGL.SetSwapInterval(value);
}
}
public DummySwapGroup(OpenGLContextHandle handle)
{
ContextHandle = handle;
}
public void Swap()
{
TK.OpenGL.SwapBuffers(ContextHandle);
}
}
}
}

View File

@ -0,0 +1,7 @@
namespace Dashboard.OpenTK.PAL2
{
public static class OpenTKEventExtensions
{
// public static EventArgs ToDashboardEvent(this EventArgs)
}
}

View File

@ -0,0 +1,50 @@
using Dashboard.Windowing;
using OpenTK.Graphics;
using OpenTK.Platform;
using TK = OpenTK.Platform.Toolkit;
namespace Dashboard.OpenTK.PAL2
{
public class Pal2DashboardBackend : IDashboardBackend
{
public GraphicsApiHints GraphicsApiHints { get; set; } = new OpenGLGraphicsApiHints();
public bool OpenGLBindingsInitialized { get; set; } = false;
public IPhysicalWindow CreatePhysicalWindow()
{
PhysicalWindow window = new PhysicalWindow(GraphicsApiHints);
if (!OpenGLBindingsInitialized)
{
OpenGLBindingsInitialized = true;
GLLoader.LoadBindings(
new Pal2BindingsContext(TK.OpenGL,
((OpenGLDeviceContext)window.DeviceContext).ContextHandle));
}
return window;
}
public virtual IWindow CreateWindow()
{
return CreatePhysicalWindow();
}
public void Dispose()
{
}
public void Initialize()
{
}
public void Leave()
{
}
public void RunEvents(bool wait)
{
TK.Window.ProcessEvents(wait);
}
}
}

View File

@ -0,0 +1,164 @@
using System.Collections.Concurrent;
using System.Drawing;
using Dashboard.Drawing;
using Dashboard.Events;
using Dashboard.Windowing;
using OpenTK.Mathematics;
using OpenTK.Platform;
using MouseMoveEventArgs = Dashboard.Events.MouseMoveEventArgs;
using TK = OpenTK.Platform.Toolkit;
namespace Dashboard.OpenTK.PAL2
{
public class PhysicalWindow : IPhysicalWindow, IDrawQueuePaintable, IEventListener
{
public DrawQueue DrawQueue { get; } = new DrawQueue();
public WindowHandle WindowHandle { get; }
public IDeviceContext DeviceContext { get; }
public bool DoubleBuffered => true; // Always true for OpenTK windows.
public IWindowManager? WindowManager { get; set; }
public string Title
{
get => TK.Window.GetTitle(WindowHandle);
set => TK.Window.SetTitle(WindowHandle, value);
}
public SizeF OuterSize
{
get
{
TK.Window.GetSize(WindowHandle, out Vector2i size);
return new SizeF(size.X, size.Y);
}
set => TK.Window.SetSize(WindowHandle, new Vector2i((int)value.Width, (int)value.Height));
}
public SizeF ClientSize
{
get
{
TK.Window.GetClientSize(WindowHandle, out Vector2i size);
return new SizeF(size.X, size.Y);
}
set => TK.Window.SetClientSize(WindowHandle, new Vector2i((int)value.Width, (int)value.Height));
}
public event EventHandler? Painting;
public event EventHandler<AnimationTickEventArgs>? AnimationTimerEvent;
public event EventHandler<MouseMoveEventArgs>? MouseMoved;
public event EventHandler<MouseButtonEventArgs>? MouseButtonDown;
public event EventHandler<MouseButtonEventArgs>? MouseButtonUp;
public event EventHandler<MouseScrollEventArgs>? MouseScroll;
public PhysicalWindow(WindowHandle window, IDeviceContext dc)
{
WindowHandle = window;
DeviceContext = dc;
AddWindow(this);
}
public PhysicalWindow(WindowHandle window, OpenGLContextHandle context, ISwapGroup? swapGroup = null)
{
WindowHandle = window;
DeviceContext = new OpenGLDeviceContext(window, context, swapGroup);
AddWindow(this);
}
public PhysicalWindow(GraphicsApiHints hints)
{
WindowHandle = TK.Window.Create(hints);
DeviceContext = CreateDeviceContext(WindowHandle, hints);
AddWindow(this);
}
private static IDeviceContext CreateDeviceContext(WindowHandle window, GraphicsApiHints hints)
{
switch (hints.Api)
{
case GraphicsApi.OpenGL:
case GraphicsApi.OpenGLES:
OpenGLContextHandle context = TK.OpenGL.CreateFromWindow(window);
return new OpenGLDeviceContext(window, context);
default:
throw new Exception($"Unknown graphics API {hints.Api}.");
}
}
private bool _isDisposed = false;
public void Dispose()
{
if (_isDisposed) return;
_isDisposed = true;
RemoveWindow(this);
(DeviceContext as IDisposable)?.Dispose();
TK.Window.Destroy(WindowHandle);
}
protected virtual void OnPaint()
{
WindowManager?.Paint();
Painting?.Invoke(this, EventArgs.Empty);
}
public void Paint()
{
DrawQueue.Clear();
OnPaint();
}
protected virtual void OnAnimationTimerEvent(AnimationTickEventArgs ea) =>
AnimationTimerEvent?.Invoke(this, ea);
protected virtual void OnMouseMoved(MouseMoveEventArgs ea) => MouseMoved?.Invoke(this, ea);
protected virtual void OnMouseButtonDown(MouseButtonEventArgs ea) => MouseButtonDown?.Invoke(this, ea);
protected virtual void OnMouseButtonUp(MouseButtonEventArgs ea) => MouseButtonUp?.Invoke(this, ea);
protected virtual void OnMouseScroll(MouseScrollEventArgs ea) => MouseScroll?.Invoke(this, ea);
public void SendEvent(EventArgs args)
{
}
private static readonly ConcurrentDictionary<WindowHandle, PhysicalWindow> _windows =
new ConcurrentDictionary<WindowHandle, PhysicalWindow>();
static PhysicalWindow()
{
EventQueue.EventRaised += EventQueueOnEventRaised;
}
private static void AddWindow(PhysicalWindow window)
{
_windows.TryAdd(window.WindowHandle, window);
}
private static void RemoveWindow(PhysicalWindow window)
{
_windows.TryRemove(window.WindowHandle, out _);
}
private static void EventQueueOnEventRaised(PalHandle? handle, PlatformEventType type, EventArgs args)
{
if (handle is not WindowHandle windowHandle)
return;
if (!_windows.TryGetValue(windowHandle, out PhysicalWindow? window))
return;
switch (type)
{
case PlatformEventType.MouseMove:
case PlatformEventType.Scroll:
case PlatformEventType.MouseUp:
case PlatformEventType.MouseDown:
break;
}
}
}
}

View File

@ -21,6 +21,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dashboard.Drawing.OpenGL",
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dashboard.ImmediateUI", "Dashboard.ImmediateUI\Dashboard.ImmediateUI.csproj", "{3F33197F-0B7B-4CD8-98BD-05D6D5EC76B2}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Frameworks", "Frameworks", "{9B62A92D-ABF5-4704-B831-FD075515A82F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dashboard.OpenTK", "Dashboard.OpenTK\Dashboard.OpenTK.csproj", "{7B064228-2629-486E-95C6-BDDD4B4602C4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dashboard.OpenGL", "Dashboard.OpenGL\Dashboard.OpenGL.csproj", "{33EB657C-B53A-41B4-BC3C-F38C09ABA577}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -51,11 +57,20 @@ Global
{3F33197F-0B7B-4CD8-98BD-05D6D5EC76B2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3F33197F-0B7B-4CD8-98BD-05D6D5EC76B2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3F33197F-0B7B-4CD8-98BD-05D6D5EC76B2}.Release|Any CPU.Build.0 = Release|Any CPU
{7B064228-2629-486E-95C6-BDDD4B4602C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7B064228-2629-486E-95C6-BDDD4B4602C4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7B064228-2629-486E-95C6-BDDD4B4602C4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7B064228-2629-486E-95C6-BDDD4B4602C4}.Release|Any CPU.Build.0 = Release|Any CPU
{33EB657C-B53A-41B4-BC3C-F38C09ABA577}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{33EB657C-B53A-41B4-BC3C-F38C09ABA577}.Debug|Any CPU.Build.0 = Debug|Any CPU
{33EB657C-B53A-41B4-BC3C-F38C09ABA577}.Release|Any CPU.ActiveCfg = Release|Any CPU
{33EB657C-B53A-41B4-BC3C-F38C09ABA577}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{7C90B90B-DF31-439B-9080-CD805383B014} = {9D6CCC74-4DF3-47CB-B9B2-6BB75DF2BC40}
{7B064228-2629-486E-95C6-BDDD4B4602C4} = {9B62A92D-ABF5-4704-B831-FD075515A82F}
EndGlobalSection
EndGlobal

130
Dashboard/Application.cs Normal file
View File

@ -0,0 +1,130 @@
using System;
using System.Collections.Generic;
using System.Threading;
using Dashboard.Windowing;
namespace Dashboard
{
public class Application : IDisposable
{
public IDashboardBackend Backend { get; }
public IWindowFactory WindowFactory { get; set; }
public string Name { get; } = "Dashboard Application";
protected bool IsInitialized { get; private set; } = false;
protected bool IsDisposed { get; private set; } = false;
private readonly List<IPhysicalWindow> _physicalWindows = new List<IPhysicalWindow>();
public event EventHandler? PreInitializing;
public event EventHandler? Initializing;
public event EventHandler? PostInitializing;
public event EventHandler? Leaving;
public Application(IDashboardBackend backend)
{
Backend = backend;
WindowFactory = backend;
}
protected virtual void PreInitialize()
{
PreInitializing?.Invoke(this, EventArgs.Empty);
}
public virtual void Initialize()
{
Backend.Initialize();
Initializing?.Invoke(this, EventArgs.Empty);
}
protected virtual void PostInitialize()
{
PostInitializing?.Invoke(this, EventArgs.Empty);
}
private void InitializeInternal()
{
if (IsInitialized)
return;
IsInitialized = true;
PreInitialize();
Initialize();
PostInitialize();
}
public virtual void RunEvents(bool wait)
{
if (!IsInitialized)
throw new InvalidOperationException("The application is not initialized. Cannot run events at this time.");
Backend.RunEvents(wait);
}
public virtual void Leave()
{
Backend.Leave();
}
public void Run() => Run(true, CancellationToken.None);
public void Run(bool wait) => Run(wait, CancellationToken.None);
public void Run(bool waitForEvents, CancellationToken token)
{
InitializeInternal();
while (!token.IsCancellationRequested)
{
RunEvents(waitForEvents);
foreach (IPhysicalWindow window in _physicalWindows)
{
window.Paint();
}
}
Leave();
}
/// <inheritdoc cref="IWindowFactory.CreateWindow"/>
public IWindow CreateWindow()
{
IWindow window = WindowFactory.CreateWindow();
if (window is IPhysicalWindow physical)
_physicalWindows.Add(physical);
return window;
}
/// <inheritdoc cref="IWindowFactory.CreatePhysicalWindow"/>
public IPhysicalWindow CreatePhysicalWindow()
{
IPhysicalWindow window = WindowFactory.CreatePhysicalWindow();
_physicalWindows.Add(window);
return window;
}
protected virtual void Dispose(bool disposing)
{
}
protected void InvokeDispose(bool disposing)
{
if (IsDisposed)
return;
IsDisposed = true;
Dispose(disposing);
if (disposing)
GC.SuppressFinalize(this);
}
public void Dispose() => InvokeDispose(true);
}
}

View File

@ -0,0 +1,77 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace Dashboard.Controls
{
public enum ClassChangeType
{
Added,
Removed,
}
public record struct ClassChanged(object? Owner, string ClassName, ClassChangeType Type);
public class ClassSet : ICollection<string>
{
public int Count => _classes.Count;
public bool IsReadOnly => false;
public object? Owner { get; }
public event EventHandler<ClassChanged>? ClassChanged;
private readonly HashSet<string> _classes = new HashSet<string>();
public ClassSet(object? owner)
{
Owner = owner;
}
public IEnumerator<string> GetEnumerator() => _classes.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(string item)
{
if (_classes.Add(item))
{
OnClassAdded(item);
}
}
public void Clear()
{
foreach (string @class in _classes)
OnClassRemoved(@class);
_classes.Clear();
}
public bool Contains(string item) => _classes.Contains(item);
public void CopyTo(string[] array, int arrayIndex) => _classes.CopyTo(array, arrayIndex);
public bool Remove(string item)
{
if (_classes.Remove(item))
{
OnClassRemoved(item);
return true;
}
return false;
}
private void OnClassAdded(string @class)
{
ClassChanged?.Invoke(this, new ClassChanged(Owner, @class, ClassChangeType.Added));
}
private void OnClassRemoved(string @class)
{
ClassChanged?.Invoke(this, new ClassChanged(Owner, @class, ClassChangeType.Removed));
}
}
}

View File

@ -0,0 +1,68 @@
using System;
using Dashboard.Drawing;
using Dashboard.Windowing;
namespace Dashboard.Controls
{
public class Control : IEventListener, IDrawQueuePaintable, IDisposable
{
public string? Id { get; set; }
public ClassSet Classes { get; }
public Form? Owner { get; protected set; } = null;
public Control? Parent { get; private set; } = null;
public bool Disposed { get; private set; }
public virtual DrawQueue DrawQueue => Owner?.DrawQueue ?? throw NoOwnerException;
public virtual Box2d ClientArea { get; set; }
public event EventHandler? Painting;
public event EventHandler? OwnerChanged;
public event EventHandler? ParentChanged;
public event EventHandler? Disposing;
public event EventHandler? Resized;
public Control()
{
Classes = new ClassSet(this);
}
public virtual void OnPaint()
{
Painting?.Invoke(this, EventArgs.Empty);
}
public void Paint()
{
OnPaint();
}
protected void InvokeDispose(bool disposing)
{
if (Disposed)
return;
Disposed = true;
Dispose(disposing);
if (disposing)
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
public void Dispose() => InvokeDispose(true);
public void SendEvent(EventArgs args)
{
throw new NotImplementedException();
}
internal static void SetParent(Control parent, Control child)
{
child.Parent = parent;
}
protected static Exception NoOwnerException => new Exception("No form owns this control");
}
}

View File

@ -0,0 +1,23 @@
using Dashboard.Drawing;
using Dashboard.Windowing;
namespace Dashboard.Controls
{
public class Form : Control
{
public IWindow Window { get; }
public override DrawQueue DrawQueue { get; }
public override Box2d ClientArea
{
get => new Box2d(0, 0, Window.ClientSize.Width, Window.ClientSize.Height);
set { }
}
public Form(IWindow window)
{
Window = window;
DrawQueue = (window as IDrawQueuePaintable)?.DrawQueue ?? new DrawQueue();
}
}
}

View File

@ -0,0 +1,37 @@
using System;
using System.Drawing;
using System.Numerics;
using Dashboard.Drawing;
namespace Dashboard.Controls
{
public class Label : Control
{
public bool AutoSize { get; set; } = true;
public string Text { get; set; } = "";
public event EventHandler? TextChanged;
protected IBrush TextBrush => throw new NotImplementedException();
protected IFont Font => throw new NotImplementedException();
protected virtual void OnTextChanged(string oldValue, string newValue)
{
if (AutoSize)
CalculateSize();
}
protected void CalculateSize()
{
SizeF sz = Typesetter.MeasureString(Font, Text);
ClientArea = new Box2d(ClientArea.Min, ClientArea.Min + (Vector2)sz);
}
public override void OnPaint()
{
base.OnPaint();
DrawQueue.Text(new Vector3(ClientArea.Min, 0), TextBrush, Text, Font);
}
}
}

View File

@ -6,4 +6,9 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Dashboard.Common\Dashboard.Common.csproj" />
<ProjectReference Include="..\Dashboard.Drawing\Dashboard.Drawing.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,29 @@
using System;
using Dashboard.Windowing;
namespace Dashboard
{
public interface IWindowFactory
{
/// <summary>
/// Creates a window. It could be a virtual window, or a physical window.
/// </summary>
/// <returns>A window.</returns>
IWindow CreateWindow();
/// <summary>
/// Always creates a physical window.
/// </summary>
/// <returns>A physical window.</returns>
IPhysicalWindow CreatePhysicalWindow();
}
public interface IDashboardBackend : IDisposable, IWindowFactory
{
void Initialize();
void RunEvents(bool wait);
void Leave();
}
}

View File

@ -11,6 +11,7 @@
<ProjectReference Include="..\..\Dashboard.Drawing.OpenGL\Dashboard.Drawing.OpenGL.csproj" />
<ProjectReference Include="..\..\Dashboard.Drawing\Dashboard.Drawing.csproj" />
<ProjectReference Include="..\..\Dashboard.ImmediateUI\Dashboard.ImmediateUI.csproj" />
<ProjectReference Include="..\..\Dashboard.OpenTK\Dashboard.OpenTK.csproj" />
</ItemGroup>
<ItemGroup>

View File

@ -1,18 +1,16 @@
using Dashboard.Drawing;
using System.Drawing;
using System.Text;
using Dashboard;
using Dashboard.Drawing.OpenGL;
using Dashboard.Drawing.OpenGL.Text;
using Dashboard.ImmediateUI;
using Dashboard.OpenTK.PAL2;
using OpenTK.Graphics;
using OpenTK.Platform;
using OpenTK.Graphics.OpenGL;
using OpenTK.Mathematics;
using Box2d = Dashboard.Box2d;
using TK = OpenTK.Platform.Toolkit;
using sys = System.Numerics;
using otk = OpenTK.Mathematics;
using Dashboard;
TK.Init(new ToolkitOptions()
{
@ -24,185 +22,156 @@ TK.Init(new ToolkitOptions()
}
});
WindowHandle wnd = TK.Window.Create(new OpenGLGraphicsApiHints()
{
Version = new Version(3, 2),
ForwardCompatibleFlag = true,
DebugFlag = true,
Profile = OpenGLProfile.Core,
sRGBFramebuffer = true,
Application app = new Application(new Pal2DashboardBackend()
{
GraphicsApiHints = new OpenGLGraphicsApiHints()
{
Version = new Version(3, 2),
ForwardCompatibleFlag = true,
DebugFlag = true,
Profile = OpenGLProfile.Core,
sRGBFramebuffer = true,
SwapMethod = ContextSwapMethod.Undefined,
SwapMethod = ContextSwapMethod.Undefined,
RedColorBits = 8,
GreenColorBits = 8,
BlueColorBits = 8,
AlphaColorBits = 8,
Multisamples = 0,
RedColorBits = 8,
GreenColorBits = 8,
BlueColorBits = 8,
AlphaColorBits = 8,
Multisamples = 0,
SupportTransparentFramebufferX11 = true,
SupportTransparentFramebufferX11 = true,
}
});
TK.Window.SetTitle(wnd, "DashTerm");
TK.Window.SetMinClientSize(wnd, 300, 200);
TK.Window.SetClientSize(wnd, new Vector2i(320, 240));
TK.Window.SetBorderStyle(wnd, WindowBorderStyle.ResizableBorder);
// TK.Window.SetTransparencyMode(wnd, WindowTransparencyMode.TransparentFramebuffer, 0.1f);
OpenGLContextHandle context = TK.OpenGL.CreateFromWindow(wnd);
TK.OpenGL.SetCurrentContext(context);
TK.OpenGL.SetSwapInterval(1);
GLLoader.LoadBindings(new Pal2BindingsContext(TK.OpenGL, context));
DrawQueue queue = new DrawQueue();
PhysicalWindow window;
SolidBrush fg = new SolidBrush(Color.FromArgb(0, 0, 0, 0));
SolidBrush bg = new SolidBrush(Color.Black);
bool shouldExit = false;
GLEngine engine = new GLEngine();
engine.Initialize();
GlContext dbGlContext = new GlContext(wnd, context);
ContextExecutor executor = engine.GetExecutor(dbGlContext);
DimUI dimUI = new DimUI(new DimUIConfig()
{
Font = new NamedFont("Noto Sans", 9f),
});
CancellationTokenSource source = new CancellationTokenSource();
GLEngine engine;
ContextExecutor executor;
DimUI dimUI;
Vector2 mousePos = Vector2.Zero;
Random r = new Random();
EventQueue.EventRaised += (handle, type, eventArgs) =>
{
if (handle != wnd)
return;
switch (type)
{
case PlatformEventType.Close:
shouldExit = true;
break;
case PlatformEventType.MouseMove:
mousePos = ((MouseMoveEventArgs)eventArgs).ClientPosition;
break;
}
};
TK.Window.SetMode(wnd, WindowMode.Normal);
List<Vector3> points = new List<Vector3>();
IFont font = Typesetter.LoadFont("Nimbus Mono", 12f);
IFont font;
StringBuilder builder = new StringBuilder();
while (!shouldExit)
{
TK.Window.ProcessEvents(true);
TK.Window.GetFramebufferSize(wnd, out Vector2i framebufferSize);
executor.BeginFrame();
app.PostInitializing += (sender, ea) => {
window = (PhysicalWindow)app.CreatePhysicalWindow();
dimUI.Begin(new Box2d(0, 0, framebufferSize.X, framebufferSize.Y), queue);
dimUI.Text("Hello World!");
dimUI.Button("Cancel"); dimUI.SameLine();
dimUI.Button("OK");
window.Title = "DashTerm";
TK.Window.SetMinClientSize(window.WindowHandle, 300, 200);
TK.Window.SetClientSize(window.WindowHandle, new Vector2i(320, 240));
TK.Window.SetBorderStyle(window.WindowHandle, WindowBorderStyle.ResizableBorder);
// TK.Window.SetTransparencyMode(wnd, WindowTransparencyMode.TransparentFramebuffer, 0.1f);
dimUI.Input("type me!", builder);
OpenGLDeviceContext context = (OpenGLDeviceContext)window.DeviceContext;
dimUI.BeginMenu();
context.MakeCurrent();
context.SwapGroup.SwapInterval = 1;
if (dimUI.MenuItem("File"))
engine = new GLEngine();
engine.Initialize();
executor = engine.GetExecutor(context);
dimUI = new DimUI(new DimUIConfig()
{
dimUI.BeginMenu();
dimUI.MenuItem("New Window");
dimUI.MenuItem("Preferences");
dimUI.MenuItem("Exit");
dimUI.EndMenu();
}
Font = new NamedFont("Noto Sans", 9f),
});
if (dimUI.MenuItem("Edit"))
EventQueue.EventRaised += (handle, type, eventArgs) =>
{
dimUI.BeginMenu();
dimUI.MenuItem("Cut");
dimUI.MenuItem("Copy");
dimUI.MenuItem("Paste");
if (handle != window.WindowHandle)
return;
if (dimUI.MenuItem("Send Char"))
switch (type)
{
case PlatformEventType.Close:
source.Cancel();
break;
case PlatformEventType.MouseMove:
mousePos = ((MouseMoveEventArgs)eventArgs).ClientPosition;
break;
}
};
TK.Window.SetMode(window.WindowHandle, WindowMode.Normal);
font = Typesetter.LoadFont("Nimbus Mono", 12f);
window.Painting += (sender, ea) => {
TK.Window.GetFramebufferSize(context.WindowHandle, out Vector2i framebufferSize);
executor.BeginFrame();
dimUI.Begin(new Box2d(0, 0, framebufferSize.X, framebufferSize.Y), window.DrawQueue);
dimUI.Text("Hello World!");
dimUI.Button("Cancel"); dimUI.SameLine();
dimUI.Button("OK");
dimUI.Input("type me!", builder);
dimUI.BeginMenu();
dimUI.EndMenu();
}
dimUI.EndMenu();
}
if (dimUI.MenuItem("File"))
{
dimUI.BeginMenu();
dimUI.MenuItem("New Window");
dimUI.MenuItem("Preferences");
dimUI.MenuItem("Exit");
dimUI.EndMenu();
}
if (dimUI.MenuItem("View"))
{
dimUI.BeginMenu();
dimUI.MenuItem("Clear");
if (dimUI.MenuItem("Edit"))
{
dimUI.BeginMenu();
dimUI.MenuItem("Cut");
dimUI.MenuItem("Copy");
dimUI.MenuItem("Paste");
if (dimUI.MenuItem("Set Size"))
{
dimUI.BeginMenu();
dimUI.MenuItem("24 x 40");
dimUI.MenuItem("25 x 40");
dimUI.MenuItem("24 x 80");
dimUI.MenuItem("25 x 80");
dimUI.MenuItem("25 x 120");
dimUI.EndMenu();
}
if (dimUI.MenuItem("Send Char"))
{
dimUI.BeginMenu();
dimUI.EndMenu();
}
dimUI.EndMenu();
}
dimUI.EndMenu();
}
dimUI.Finish();
if (dimUI.MenuItem("View"))
{
dimUI.BeginMenu();
dimUI.MenuItem("Clear");
GL.Viewport(0, 0, framebufferSize.X, framebufferSize.Y);
GL.ClearColor(0.3f, 0.3f, 0.3f, 1.0f);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
GL.Disable(EnableCap.DepthTest);
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
GL.ColorMask(true, true, true, true);
if (dimUI.MenuItem("Set Size"))
{
dimUI.BeginMenu();
dimUI.MenuItem("24 x 40");
dimUI.MenuItem("25 x 40");
dimUI.MenuItem("24 x 80");
dimUI.MenuItem("25 x 80");
dimUI.MenuItem("25 x 120");
dimUI.EndMenu();
}
executor.Draw(queue);
executor.EndFrame();
queue.Clear();
dimUI.EndMenu();
}
TK.OpenGL.SwapBuffers(context);
}
dimUI.Finish();
class GlContext : IGLContext
{
public WindowHandle Window { get; }
public OpenGLContextHandle Context { get; }
public int ContextGroup { get; } = -1;
GL.Viewport(0, 0, framebufferSize.X, framebufferSize.Y);
GL.ClearColor(0.3f, 0.3f, 0.3f, 1.0f);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
GL.Disable(EnableCap.DepthTest);
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
GL.ColorMask(true, true, true, true);
public Size FramebufferSize
{
get
{
TK.Window.GetFramebufferSize(Window, out Vector2i framebufferSize);
return new Size(framebufferSize.X, framebufferSize.Y);
}
}
executor.Draw(window.DrawQueue);
executor.EndFrame();
public event Action? Disposed;
context.SwapGroup.Swap();
};
};
public GlContext(WindowHandle window, OpenGLContextHandle context)
{
Window = window;
Context = context;
OpenGLContextHandle? shared = TK.OpenGL.GetSharedContext(context);
if (shared != null)
{
ContextGroup = _contexts.IndexOf(shared);
}
else
{
_contexts.Add(context);
}
}
private static readonly List<OpenGLContextHandle> _contexts = new List<OpenGLContextHandle>();
}
app.Run(true, source.Token);