10 Commits

Author SHA1 Message Date
NepuShiro f932a7704b b 2026-05-21 23:33:23 -05:00
NepuShiro 85781f4510 a 2026-05-21 08:18:52 -05:00
NepuShiro 935edf0db8 Add easy textures 2026-05-21 05:01:06 -05:00
NepuShiro 5c17e233bc a 2026-05-20 11:29:55 -05:00
NepuShiro 7d5f242a43 opengl4 2026-05-20 04:23:47 -05:00
NepuShiro 96e90a09d9 This works :) 2026-05-19 11:43:24 -05:00
NepuShiro 519b06367a push wtv 2026-05-19 10:05:38 -05:00
NepuShiro 2970fdc3c6 Remove ImPlot3D 2026-05-18 23:58:49 -05:00
NepuShiro 221cfa5e9c some cleanup 2026-05-18 23:19:40 -05:00
NepuShiro 7167d98cb6 Actual working viewports :) 2026-05-18 10:43:19 -05:00
9 changed files with 2132 additions and 1323 deletions
+217 -83
View File
@@ -1,42 +1,63 @@
using System.Numerics; using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Hexa.NET.ImGui; using Hexa.NET.ImGui;
using Hexa.NET.ImPlot; using Hexa.NET.ImPlot;
using Hexa.NET.ImPlot3D; using HexaGen.Runtime;
using SDL3_TestingSuite.SDL3; using SDL3_TestingSuite.SDL3;
using SDL3;
namespace SDL3_TestingSuite; namespace SDL3_TestingSuite;
public class Program public class Program
{ {
private static bool _demoWindowVisible = true; private static bool _demoWindowVisible = true;
private static bool _imPlotDemoVisible;
private static bool _fontStuff; private static bool _fontStuff;
private static readonly Dictionary<string, List<uint>?> GlyphsByName = new Dictionary<string, List<uint>?>(); private static readonly Dictionary<string, List<uint>?> GlyphsByName = new Dictionary<string, List<uint>?>();
private static bool _initialized; private static bool _fontStuffInitialized;
private static bool _init;
private static ImFontPtr _font; private static ImFontPtr _font;
private static float size = 1f; private static float size = 1f;
private static SDL3Window _window = null!;
private static OpenGLTexture? _imageTexture;
private static string? _imageLoadError;
public static void Main() public static void Main()
{ {
const SDL.WindowFlags flags = SDL.WindowFlags.Resizable | SDL.WindowFlags.HighPixelDensity | SDL.WindowFlags.Transparent; string baseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
SDL3Window window = new SDL3Window("SDL3 Testing Suite", 100, 100, 1280, 720, flags); string osPlatform = typeof(LibraryLoader).GetMethod("GetOSPlatform", BindingFlags.Static | BindingFlags.NonPublic)?.Invoke(null, null) as string ?? ""; // LibraryLoader.GetOSPlatform();
window.ClearColor.W = 0f; string architecture = typeof(LibraryLoader).GetMethod("GetArchitecture", BindingFlags.Static | BindingFlags.NonPublic)?.Invoke(null, null) as string ?? ""; // LibraryLoader.GetArchitecture());
window.RenderCallback = () => LibraryLoader.CustomLoadFolders.AddRange(new string[]
{ {
Path.Combine(baseDirectory),
Path.Combine(baseDirectory, "runtimes", osPlatform, "native"),
Path.Combine(baseDirectory, "runtimes", $"{osPlatform}-{architecture}", "debug"), // allows debug builds sideload.
Path.Combine(baseDirectory, "runtimes", $"{osPlatform}-{architecture}", "native"),
});
_window = new SDL3Window("SDL3 Testing Suite", 100, 100, 1280, 720);
_window.Disposing += DisposeImages;
_window.RenderCallback += () =>
{
if (!_init)
{
_init = true;
LoadImageTexture("");
}
ImGuiViewportPtr viewport = ImGui.GetMainViewport(); ImGuiViewportPtr viewport = ImGui.GetMainViewport();
ImGui.SetNextWindowPos(viewport.WorkPos); ImGui.SetNextWindowPos(viewport.WorkPos);
ImGui.SetNextWindowSize(viewport.WorkSize); ImGui.SetNextWindowSize(viewport.WorkSize);
ImGui.SetNextWindowViewport(viewport.ID);
ImGui.Begin("MainWindow", ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.MenuBar | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoBringToFrontOnFocus); ImGui.Begin("MainWindow", ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.MenuBar | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoBringToFrontOnFocus);
if (ImGui.BeginMenuBar()) if (ImGui.BeginMenuBar())
{ {
if (ImGui.BeginMenu("Stuff")) if (ImGui.BeginMenu("Stuff"))
{ {
if (ImGui.MenuItem("Quit")) if (ImGui.MenuItem("Quit"))
{ {
window.ShouldClose = true; _window.ShouldClose = true;
} }
ImGui.EndMenu(); ImGui.EndMenu();
@@ -44,86 +65,110 @@ public class Program
ImGui.Spacing(); ImGui.Spacing();
ImGui.MenuItem("Demo Window", "", ref _demoWindowVisible); ImGui.MenuItem("Demo Window", "", ref _demoWindowVisible);
ImGui.Spacing(); ImGui.Spacing();
ImGui.MenuItem("ImPlot Demo Window", "", ref _imPlotDemoVisible);
ImGui.Spacing();
ImGui.MenuItem("Font Stuff", "", ref _fontStuff); ImGui.MenuItem("Font Stuff", "", ref _fontStuff);
ImGui.EndMenuBar(); ImGui.EndMenuBar();
} }
string hash = "AAAA";
bool hasValue = true;
string text2 = "";
if (ImGui.InputTextWithHint($"##{hash}", hasValue ? "" : "Null", ref text2, 99999, ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.CtrlEnterForNewLine))
{
}
float buttonSize = ImGui.GetFrameHeight();
float avail = ImGui.GetContentRegionAvail().X;
float inputWidth = avail - buttonSize;
ImGui.PushItemWidth(inputWidth);
ImGui.SameLine(0f, 0f);
if (ImGui.Button($"X##{hash}_clear", new Vector2(buttonSize, buttonSize)))
{
}
ImGui.PopItemWidth();
ImGui.End(); ImGui.End();
if (_fontStuff) if (_fontStuff)
{ {
ImGui.SetNextWindowSize(new Vector2(250, 500), ImGuiCond.FirstUseEver); ImGui.SetNextWindowSize(new Vector2(250, 500), ImGuiCond.FirstUseEver);
if (ImGui.Begin("FontStuff", ref _fontStuff)) ImGui.Begin("FontStuff", ref _fontStuff);
ImGui.ShowFontSelector("Font");
bool change = false;
if (ImGui.GetFont() != _font)
{ {
ImGui.ShowFontSelector("Font"); _font = ImGui.GetFont();
change = true;
bool change = false;
if (ImGui.GetFont() != _font)
{
_font = ImGui.GetFont();
change = true;
}
string fontName = _font.GetDebugNameS();
fontName = string.IsNullOrEmpty(fontName) ? _font.FontId.ToString() : fontName;
if (!_initialized || change)
{
if (!GlyphsByName.TryGetValue(fontName, out List<uint> glyphs))
{
glyphs = new List<uint>();
ImFontPtr font = _font;
for (uint codepoint = 0; codepoint <= 0x10FFFF; codepoint++)
{
if (codepoint >= 0xD800 && codepoint <= 0xDFFF)
{
continue;
}
if (!font.IsGlyphInFont(codepoint)) continue;
glyphs.Add(codepoint);
}
GlyphsByName[fontName] = glyphs;
Logger.Log($"Initialized font {fontName} with {glyphs.Count} glyphs");
}
_initialized = true;
}
ImGui.PushFont(null, 24);
if (GlyphsByName.TryGetValue(fontName, out List<uint> glyphs2))
{
float cursorXStart = ImGui.GetCursorPosX();
float maxWidth = ImGui.GetContentRegionAvail().X;
foreach (uint codepoint in glyphs2)
{
string text = char.ConvertFromUtf32((int)codepoint);
float glyphWidth = ImGui.CalcTextSize(text).X;
float cursorX = ImGui.GetCursorPosX();
if (cursorX > cursorXStart && (cursorX + glyphWidth) > (cursorXStart + maxWidth))
{
ImGui.NewLine();
}
ImGui.TextUnformatted(text);
ImGui.SameLine();
}
}
ImGui.PopFont();
ImGui.End();
} }
string fontName = _font.GetDebugNameS();
fontName = string.IsNullOrEmpty(fontName) ? _font.FontId.ToString() : fontName;
if (!_fontStuffInitialized || change)
{
if (!GlyphsByName.TryGetValue(fontName, out List<uint>? glyphs))
{
glyphs = new List<uint>();
ImFontPtr font = _font;
for (uint codepoint = 0; codepoint <= 0x10FFFF; codepoint++)
{
if (codepoint >= 0xD800 && codepoint <= 0xDFFF)
{
continue;
}
if (!font.IsGlyphInFont(codepoint)) continue;
glyphs.Add(codepoint);
}
GlyphsByName[fontName] = glyphs;
Logger.Log($"Initialized font {fontName} with {glyphs.Count} glyphs");
}
_fontStuffInitialized = true;
}
ImGui.PushFont(null, 24);
if (GlyphsByName.TryGetValue(fontName, out List<uint>? glyphs2))
{
float cursorXStart = ImGui.GetCursorPosX();
float maxWidth = ImGui.GetContentRegionAvail().X;
foreach (uint codepoint in glyphs2!)
{
string text = char.ConvertFromUtf32((int)codepoint);
float glyphWidth = ImGui.CalcTextSize(text).X;
float cursorX = ImGui.GetCursorPosX();
if (cursorX > cursorXStart && (cursorX + glyphWidth) > (cursorXStart + maxWidth))
{
ImGui.NewLine();
}
ImGui.TextUnformatted(text);
ImGui.SameLine();
}
}
ImGui.PopFont();
ImGui.End();
} }
ImGui.Begin("Thing");
float time = (float)ImGui.GetTime() * 5; float time = (float)ImGui.GetTime() * 5;
if (ImPlot.BeginPlot("Moving Rainbow Sine Wave")) if (ImPlot.BeginPlot("Moving Rainbow Sine Wave"))
{ {
@@ -161,29 +206,118 @@ public class Program
ImPlot.EndPlot(); ImPlot.EndPlot();
} }
ImGui.SliderFloat("Sine", ref size, 1f, 120f); ImGui.SliderFloat("Sine", ref size, 1f, 120f);
ImGui.End();
bool regen1 = true;
if (_imageTexture != null)
{
Vector2 displaySize = ImGui.GetIO().DisplaySize;
Vector2 imageSize = new Vector2(_imageTexture.Width, _imageTexture.Height);
float maxWidth = displaySize.X * 0.5f;
float maxHeight = displaySize.Y * 0.5f;
float scale = MathF.Min(maxWidth / imageSize.X, maxHeight / imageSize.Y);
Vector2 scaledSize = imageSize * MathF.Min(scale, 1.0f);
Vector2 padding = ImGui.GetStyle().WindowPadding;
Vector2 windowSize = new Vector2(scaledSize.X + padding.X * 2, scaledSize.Y + padding.Y * 2 + (ImGui.GetFrameHeight() * 4));
ImGui.SetNextWindowSize(windowSize, ImGuiCond.Always);
ImGui.Begin(_imageTexture.FileName ?? "Image", ref regen1, ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoSavedSettings);
regen1 = !ImGui.Button("Regen");
ImGui.Image(_imageTexture.ImGuiTexture, scaledSize);
string text1 = $"{_imageTexture.Width}x{_imageTexture.Height}";
ImGui.TextUnformatted(text1);
ImGui.SameLine(ImGui.CalcTextSize(text1).X + padding.X * 2);
ImGui.TextUnformatted($"EXT: {(_imageTexture.Extension ?? "Unknown Format")}");
ImGui.TextUnformatted($"{(_imageTexture.FilePath ?? "Unknown Path")}");
}
else
{
ImGui.Begin("Image", ref regen1, ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoSavedSettings);
ImGui.TextUnformatted(_imageLoadError ?? "No image loaded.");
}
ImGui.End();
bool regen = !regen1;
if (regen)
{
DisposeImages();
LoadImageTexture("");
}
if (_demoWindowVisible) if (_demoWindowVisible)
{ {
ImGui.ShowDemoWindow(ref _demoWindowVisible); ImGui.ShowDemoWindow(ref _demoWindowVisible);
ImPlot.ShowDemoWindow(ref _demoWindowVisible); }
// ImPlot3D.ShowDemoWindow(ref _demoWindowVisible); if (_imPlotDemoVisible)
{
ImPlot.ShowDemoWindow(ref _imPlotDemoVisible);
} }
}; };
window.Run(); _window.Run();
}
private static void LoadImageTexture(string path)
{
if (string.IsNullOrEmpty(path)) return;
try
{
_imageTexture = OpenGLTexture.FromFile(_window.GL, path);
_imageLoadError = null;
}
catch (Exception e)
{
DisposeImages();
_imageLoadError = e.Message;
Logger.Log(e);
}
}
private static void DisposeImages()
{
_imageTexture?.Dispose();
_imageTexture = null;
} }
public static class Logger public static class Logger
{ {
public static void Log(string? str, [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0) private const int MessageWidth = 80;
private const int CallerWidth = 35;
public static void Log(object? value, [CallerFilePath] string path = "", [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0)
{ {
Console.WriteLine($"{caller}({line}): {str}"); if (value == null)
{
Write("null", path, caller, line);
return;
}
Write(value.ToString(), path, caller, line);
} }
public static void Log(object? str, [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0)
public static void Log(object?[] values, [CallerFilePath] string path = "", [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0)
{ {
Log(str?.ToString(), caller, line); if (values == null)
{
Write("null", path, caller, line);
return;
}
Write(string.Join(" ", values), path, caller, line);
}
private static void Write(string? str, string path, string caller, int line)
{
string message = (str ?? string.Empty).PadRight(MessageWidth);
string method = caller.PadRight(CallerWidth);
Console.WriteLine($"{message} | {method} | {path}:{line}");
} }
} }
} }
+4
View File
@@ -14,11 +14,15 @@
<!--<PackageReference Include="ImGui.NET" Version="*" />--> <!--<PackageReference Include="ImGui.NET" Version="*" />-->
<PackageReference Include="Hexa.NET.ImGui" Version="2.2.9" /> <PackageReference Include="Hexa.NET.ImGui" Version="2.2.9" />
<PackageReference Include="Hexa.NET.ImGui.Widgets" Version="1.2.18" /> <PackageReference Include="Hexa.NET.ImGui.Widgets" Version="1.2.18" />
<PackageReference Include="Hexa.NET.ImNodes" Version="2.2.9" />
<PackageReference Include="Hexa.NET.ImPlot" Version="2.2.9" /> <PackageReference Include="Hexa.NET.ImPlot" Version="2.2.9" />
<PackageReference Include="Hexa.NET.ImPlot3D" Version="2.2.9" /> <PackageReference Include="Hexa.NET.ImPlot3D" Version="2.2.9" />
<PackageReference Include="Hexa.NET.OpenGL4" Version="1.1.0" />
<PackageReference Include="Hexa.NET.SDL3.Image" Version="1.0.0" />
<PackageReference Include="Hexa.NET.Utilities" Version="2.2.12" /> <PackageReference Include="Hexa.NET.Utilities" Version="2.2.12" />
<PackageReference Include="SDL3-CS" Version="3.2.18" /> <PackageReference Include="SDL3-CS" Version="3.2.18" />
<PackageReference Include="SDL3-CS.Native" Version="3.2.18" /> <PackageReference Include="SDL3-CS.Native" Version="3.2.18" />
<PackageReference Include="SDL3-CS.Native.Image" Version="3.3.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+8
View File
@@ -0,0 +1,8 @@
using System.Runtime.InteropServices;
namespace SDL3_TestingSuite.SDL3;
public unsafe static class DelegateHelpers
{
public static void* GetPtrForDelegate<TDelegate>(this TDelegate _delegate) where TDelegate : notnull => (void*)Marshal.GetFunctionPointerForDelegate(_delegate);
}
+23 -9
View File
@@ -21,7 +21,7 @@ public static class FontFind
{ {
extension(ImGuiIOPtr io) extension(ImGuiIOPtr io)
{ {
public unsafe ImFontPtr AddFont(string fontPath) public unsafe ImFontPtr AddFont(string fontPath, bool merge = false)
{ {
try try
{ {
@@ -29,13 +29,14 @@ public static class FontFind
FileInfo info = new FileInfo(fontPath); FileInfo info = new FileInfo(fontPath);
if (!info.Exists || info.Length <= 0) return null; if (!info.Exists || info.Length <= 0) return null;
FontMetrics metrics = FontFind.ReadFontMetrics(fontPath); FontMetrics metrics = ReadFontMetricsSafe(fontPath);
float size = FontFind.GetRecommendedPixelSize(metrics); float size = GetRecommendedPixelSize(metrics);
ImFontConfigPtr config = ImGui.ImFontConfig(); ImFontConfigPtr config = ImGui.ImFontConfig();
config.FontLoaderFlags |= (uint)ImGuiFreeTypeLoaderFlags.LoadColor; config.FontLoaderFlags |= (uint)ImGuiFreeTypeLoaderFlags.LoadColor | (uint)ImGuiFreeTypeLoaderFlags.Bitmap;
config.MergeMode = merge;
ImFontPtr font = io.Fonts.AddFontFromFileTTF(fontPath, size, config); ImFontPtr font = io.Fonts.AddFontFromFileTTF(fontPath, size, config);
Program.Logger.Log("Added font: " + Path.GetFileName(fontPath)); Program.Logger.Log($"{(merge ? "Merged" : "Added")} font: " + Path.GetFileName(fontPath));
return font; return font;
} }
catch (Exception e) catch (Exception e)
@@ -72,6 +73,21 @@ public static class FontFind
} }
} }
public static FontMetrics ReadFontMetricsSafe(string fontPath)
{
try
{
return ReadFontMetrics(fontPath);
}
catch (Exception ex)
{
Console.WriteLine("Font parsing failed: " + fontPath);
Console.WriteLine(ex.ToString());
return new FontMetrics();
}
}
public static FontMetrics ReadFontMetrics(string fontPath) public static FontMetrics ReadFontMetrics(string fontPath)
{ {
byte[] data = File.ReadAllBytes(fontPath); byte[] data = File.ReadAllBytes(fontPath);
@@ -110,11 +126,9 @@ public static class FontFind
metrics.WinDescent = ReadS16Be(os2Offset + 76); metrics.WinDescent = ReadS16Be(os2Offset + 76);
} }
metrics.TypoLineHeight = metrics.TypoLineHeight = metrics.TypoAscender - metrics.TypoDescender + metrics.TypoLineGap;
metrics.TypoAscender - metrics.TypoDescender + metrics.TypoLineGap;
metrics.WinLineHeight = metrics.WinLineHeight = metrics.WinAscent + metrics.WinDescent;
metrics.WinAscent + metrics.WinDescent;
return metrics; return metrics;
+827 -783
View File
File diff suppressed because it is too large Load Diff
+586 -337
View File
File diff suppressed because it is too large Load Diff
+35
View File
@@ -0,0 +1,35 @@
using System.Runtime.InteropServices;
namespace SDL3_TestingSuite.SDL3;
public unsafe static class ImGuiUserData<T> where T : class
{
public static void* Store(T value)
{
if (value == null)
return null;
GCHandle handle = GCHandle.Alloc(value, GCHandleType.Normal);
return (void*)GCHandle.ToIntPtr(handle);
}
public static T? Get(void* ptr)
{
if (ptr == null)
return null;
GCHandle handle = GCHandle.FromIntPtr((nint)ptr);
return (T?)handle.Target;
}
public static void Free(void* ptr)
{
if (ptr == null)
return;
GCHandle handle = GCHandle.FromIntPtr((nint)ptr);
if (handle.IsAllocated)
handle.Free();
}
}
+182
View File
@@ -0,0 +1,182 @@
using System.Numerics;
using Hexa.NET.ImGui;
using Hexa.NET.OpenGL;
using SDL3;
namespace SDL3_TestingSuite.SDL3;
public sealed unsafe class OpenGLTexture : IDisposable
{
private readonly GL _gl;
public uint Handle { get; private set; }
public int Width { get; }
public int Height { get; }
public ImTextureRef ImGuiTexture => new ImTextureRef(null, (nint)Handle);
public Vector2 Size => new Vector2(Width, Height);
public string? FileName;
public string? FilePath;
public string? Extension;
private OpenGLTexture(GL gl, uint handle, int width, int height, string? path = null)
{
_gl = gl;
Handle = handle;
Width = width;
Height = height;
if (path == null) return;
FileName = Path.GetFileName(path);
FilePath = path;
Extension = Path.GetExtension(path);
}
public static OpenGLTexture FromFile(GL gl, string path)
{
nint surface = string.Equals(Path.GetExtension(path), ".bmp", StringComparison.OrdinalIgnoreCase)
? SDL.LoadBMP(path)
: Image.Load(path);
if (surface == nint.Zero)
{
throw new InvalidOperationException($"Failed to load image '{path}': {SDL.GetError()}");
}
try
{
return FromSurface(gl, surface, path);
}
finally
{
SDL.DestroySurface(surface);
}
}
public static OpenGLTexture FromSurface(GL gl, nint surface, string? path = null)
{
if (surface == nint.Zero)
{
throw new ArgumentException("Surface cannot be null.", nameof(surface));
}
SDL.PixelFormat uploadFormat = BitConverter.IsLittleEndian
? SDL.PixelFormat.ABGR8888
: SDL.PixelFormat.RGBA8888;
nint converted = SDL.ConvertSurface(surface, uploadFormat);
if (converted == nint.Zero)
{
throw new InvalidOperationException($"Failed to convert image surface to RGBA32: {SDL.GetError()}");
}
try
{
SDL.Surface* convertedSurface = (SDL.Surface*)converted;
bool locked = false;
if (SDL.MustLock(*convertedSurface))
{
if (!SDL.LockSurface(converted))
{
throw new InvalidOperationException($"Failed to lock image surface: {SDL.GetError()}");
}
locked = true;
}
try
{
uint texture = UploadRgba32(gl, convertedSurface);
return new OpenGLTexture(gl, texture, convertedSurface->Width, convertedSurface->Height, path);
}
finally
{
if (locked)
{
SDL.UnlockSurface(converted);
}
}
}
finally
{
SDL.DestroySurface(converted);
}
}
private static uint UploadRgba32(GL gl, SDL.Surface* surface)
{
uint texture = 0;
gl.GenTextures(1, ref texture);
gl.GetIntegerv(GLGetPName.TextureBinding2D, out int previousTexture);
gl.BindTexture(GLTextureTarget.Texture2D, texture);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.MinFilter, (int)GLTextureMinFilter.Linear);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.MagFilter, (int)GLTextureMagFilter.Linear);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.WrapS, (int)GLEnum.ClampToEdge);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.WrapT, (int)GLEnum.ClampToEdge);
gl.PixelStorei(GLPixelStoreParameter.UnpackAlignment, 1);
gl.PixelStorei(GLPixelStoreParameter.UnpackRowLength, surface->Pitch / 4);
gl.TexImage2D(
GLTextureTarget.Texture2D,
0,
GLInternalFormat.Rgba,
surface->Width,
surface->Height,
0,
GLPixelFormat.Rgba,
GLPixelType.UnsignedByte,
surface->Pixels);
gl.PixelStorei(GLPixelStoreParameter.UnpackRowLength, 0);
gl.BindTexture(GLTextureTarget.Texture2D, (uint)previousTexture);
return texture;
}
private static uint UploadRgba32FromPixels(GL gl, byte[] pixels, int width, int height)
{
uint texture = 0;
gl.GenTextures(1, ref texture);
gl.GetIntegerv(GLGetPName.TextureBinding2D, out int previousTexture);
gl.BindTexture(GLTextureTarget.Texture2D, texture);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.MinFilter, (int)GLTextureMinFilter.Linear);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.MagFilter, (int)GLTextureMagFilter.Linear);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.WrapS, (int)GLEnum.ClampToEdge);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.WrapT, (int)GLEnum.ClampToEdge);
gl.PixelStorei(GLPixelStoreParameter.UnpackAlignment, 1);
fixed (byte* ptr = &pixels[0])
{
gl.TexImage2D(
GLTextureTarget.Texture2D,
0,
GLInternalFormat.Rgba,
width,
height,
0,
GLPixelFormat.Rgba,
GLPixelType.UnsignedByte,
(nint)ptr);
}
gl.BindTexture(GLTextureTarget.Texture2D, (uint)previousTexture);
return texture;
}
public void Dispose()
{
if (Handle == 0)
{
return;
}
_gl.DeleteTexture(Handle);
Handle = 0;
}
}
+227 -88
View File
@@ -1,12 +1,10 @@
using System; using System.Numerics;
using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using Hexa.NET.ImGui; using Hexa.NET.ImGui;
using Hexa.NET.ImGui.Utilities;
using Hexa.NET.ImGuizmo; using Hexa.NET.ImGuizmo;
using Hexa.NET.ImPlot; using Hexa.NET.ImPlot;
using Hexa.NET.ImPlot3D; using Hexa.NET.ImNodes;
using Hexa.NET.OpenGL;
using HexaGen.Runtime;
using SDL3; using SDL3;
namespace SDL3_TestingSuite.SDL3; namespace SDL3_TestingSuite.SDL3;
@@ -14,49 +12,82 @@ namespace SDL3_TestingSuite.SDL3;
public sealed unsafe class SDL3Window : IDisposable public sealed unsafe class SDL3Window : IDisposable
{ {
public readonly nint Window; public readonly nint Window;
public readonly nint Renderer;
internal Action? RenderCallback { get; set; } public readonly Vector4 DefaultClearColor = new Vector4(0.06f, 0.06f, 0.06f, 1f);
public Vector4 ClearColor = new Vector4(0.06f, 0.05882353f, 0.05882353f, 1f); private Vector4? _clearColor;
public Vector4 ClearColor
{
get => _clearColor ?? DefaultClearColor;
set => _clearColor = value;
}
private readonly Stopwatch _timer = Stopwatch.StartNew(); public event Action? RenderCallback;
private TimeSpan _time = TimeSpan.Zero; public event Action? Disposing;
public event Action<Vector4>? Resized;
public event Action<SDL.Event>? EventCallback;
private SDL.Rect _screenClipRect;
private ImGuiContextPtr _imGuiContext; private ImGuiContextPtr _imGuiContext;
private ImPlotContextPtr _imPlotContext;
private ImNodesContextPtr _imNodesContext;
// private ImPLot3DContextPtr _imPlot3DContext;
public bool Disposed => _disposed; public bool Disposed => _disposed;
private bool _disposed; private bool _disposed;
private FileSystemWatcher? _watcher; private readonly FileSystemWatcher? _watcher;
public readonly GL GL;
public SDL3Window(string name, int posX, int posY, int width, int height, SDL.WindowFlags flags = SDL.WindowFlags.Resizable | SDL.WindowFlags.HighPixelDensity) public SDL3Window(string name, int posX, int posY, int width, int height, SDL.WindowFlags flags = SDL.WindowFlags.Resizable | SDL.WindowFlags.HighPixelDensity)
{ {
if (OperatingSystem.IsLinux())
SDL.SetHint(SDL.Hints.VideoDriver, "x11");
if (!SDL.Init(SDL.InitFlags.Events | SDL.InitFlags.Video | SDL.InitFlags.Gamepad)) if (!SDL.Init(SDL.InitFlags.Events | SDL.InitFlags.Video | SDL.InitFlags.Gamepad))
throw new Exception($"SDL_Init failed: {SDL.GetError()}"); throw new Exception($"SDL_Init failed: {SDL.GetError()}");
SDL.GLSetAttribute(SDL.GLAttr.ContextFlags, (int)SDL.GLContextFlag.ForwardCompatible);
SDL.GLSetAttribute(SDL.GLAttr.ContextProfileMask, (int)SDL.GLProfile.Core);
SDL.GLSetAttribute(SDL.GLAttr.ContextMajorVersion, 4);
SDL.GLSetAttribute(SDL.GLAttr.ContextMinorVersion, 6);
SDL.SetHint(SDL.Hints.IMEImplementedUI, "1");
// Create window & renderer // Create window & renderer
if (!SDL.CreateWindowAndRenderer(name, width, height, flags, out Window, out Renderer)) SDL.GLSetAttribute(SDL.GLAttr.DoubleBuffer, 1);
SDL.GLSetAttribute(SDL.GLAttr.DepthSize, 24);
SDL.GLSetAttribute(SDL.GLAttr.StencilSize, 8);
Window = SDL.CreateWindow(name, width, height, flags | SDL.WindowFlags.OpenGL);
if (Window == nint.Zero)
throw new Exception($"SDL_CreateWindowAndRenderer failed: {SDL.GetError()}"); throw new Exception($"SDL_CreateWindowAndRenderer failed: {SDL.GetError()}");
nint glContext = SDL.GLCreateContext(Window);
if (glContext == nint.Zero)
throw new Exception($"SDL_GL_CreateContext failed: {SDL.GetError()}");
SDL.GLMakeCurrent(Window, glContext);
SDL.GLSetSwapInterval(1);
SDL.SetWindowPosition(Window, posX, posY); SDL.SetWindowPosition(Window, posX, posY);
SDL.SetRenderVSync(Renderer, 1); // SDL.SetRenderVSync(Renderer, 1);
SDL.ShowWindow(Window); SDL.ShowWindow(Window);
// Create ImGui context // Create ImGui context
var context = ImGui.CreateContext(); _imGuiContext = ImGui.CreateContext();
ImPlot.CreateContext(); _imPlotContext = ImPlot.CreateContext();
ImPlot.SetImGuiContext(context); _imNodesContext = ImNodes.CreateContext();
ImGuizmo.SetImGuiContext(context); // _imPlot3DContext = ImPlot3D.CreateContext();
// ImPlot3D.SetImGuiContext(context); ImPlot.SetImGuiContext(_imGuiContext);
// ImPlot3D.CreateContext(); ImGuizmo.SetImGuiContext(_imGuiContext);
ImNodes.SetImGuiContext(_imGuiContext);
// ImPlot3D.SetImGuiContext(_imGuiContext);
ImGuiIOPtr io = ImGui.GetIO(); ImGuiIOPtr io = ImGui.GetIO();
io.ConfigFlags |= ImGuiConfigFlags.NavEnableKeyboard | ImGuiConfigFlags.NavEnableGamepad | ImGuiConfigFlags.DockingEnable; io.ConfigFlags |= ImGuiConfigFlags.NavEnableKeyboard | ImGuiConfigFlags.NavEnableGamepad | ImGuiConfigFlags.DockingEnable;
// io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable; io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;
io.Fonts.Flags |= ImFontAtlasFlags.NoBakedLines;
io.Fonts.Flags |= ImFontAtlasFlags.NoBakedLines;
io.Fonts.AddFontDefault(); io.Fonts.AddFontDefault();
try try
@@ -66,28 +97,57 @@ public sealed unsafe class SDL3Window : IDisposable
_watcher = new FileSystemWatcher(fontsPath); _watcher = new FileSystemWatcher(fontsPath);
_watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime; _watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime;
_watcher.Created += (a, b) => _watcher.Created += (_, b) =>
{ {
if (!File.Exists(b.FullPath)) return; if (!File.Exists(b.FullPath)) return;
if (Path.GetExtension(b.FullPath) != ".ttf") return; if (Path.GetExtension(b.FullPath) != ".ttf") return;
ImGui.GetIO().AddFont(b.FullPath); ImGui.GetIO().AddFont(b.FullPath);
}; };
_watcher.Deleted += (a, b) => _watcher.Deleted += (_, b) =>
{ {
if (Path.GetExtension(b.FullPath) != ".ttf") return; if (Path.GetExtension(b.FullPath) != ".ttf") return;
ImGui.GetIO().RemoveFont(b.Name); ImGui.GetIO().RemoveFont(b.Name);
}; };
_watcher.Renamed += (_, b) =>
{
if (Path.GetExtension(b.OldFullPath) != ".ttf") return;
ImGui.GetIO().RemoveFont(b.OldName);
if (!File.Exists(b.FullPath)) return;
if (Path.GetExtension(b.FullPath) != ".ttf") return;
ImGui.GetIO().AddFont(b.FullPath);
};
_watcher.IncludeSubdirectories = false; _watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true; _watcher.EnableRaisingEvents = true;
string[] fonts = Directory.GetFiles(fontsPath, "*.ttf", SearchOption.AllDirectories); List<string> fonts = Directory.GetFiles(fontsPath, "*.ttf", SearchOption.AllDirectories).ToList();
fonts.Sort();
List<string> mergeFonts = new List<string>();
for (int i = fonts.Count - 1; i >= 0; i--)
{
if (Path.GetFileName(fonts[i]).StartsWith("merge_", StringComparison.OrdinalIgnoreCase))
{
mergeFonts.Add(fonts[i]);
fonts.RemoveAt(i);
}
}
mergeFonts.Reverse();
foreach (string merge in mergeFonts)
{
io.AddFont(merge, true);
}
foreach (string font in fonts) foreach (string font in fonts)
{ {
io.AddFont(font); io.AddFont(font);
foreach (string merge in mergeFonts)
{
io.AddFont(merge, true);
}
} }
} }
catch (Exception e) catch (Exception e)
@@ -95,25 +155,75 @@ public sealed unsafe class SDL3Window : IDisposable
Console.WriteLine(e); Console.WriteLine(e);
} }
GL = new GL(new BindingsContext(Window, glContext));
// Init platform and renderer // Init platform and renderer
ImGuiSDL3Platform.Init(Window, Renderer); ImGuiSDL3Platform.Init(GL, Window, glContext);
ImGuiSDL3Renderer.Init(Renderer); ImGuiSDL3Renderer.Init(GL, "#version 330");
} }
public bool ShouldClose;
public void Run() public void Run()
{ {
while (!_disposed) while (!_disposed)
{ {
ImGui.GetIO().DeltaTime = (float)(_timer.Elapsed - _time).TotalSeconds; SDL.PumpEvents();
_time = _timer.Elapsed;
PollEvents(); while (SDL.PollEvent(out SDL.Event ev))
{
ImGuiSDL3Platform.ProcessEvent(ev);
Update(); switch ((SDL.EventType)ev.Type)
{
case SDL.EventType.Terminating:
case SDL.EventType.WindowCloseRequested:
case SDL.EventType.Quit:
ShouldClose = true;
break;
case SDL.EventType.WindowResized:
case SDL.EventType.WindowMoved:
SDL.GetWindowSize(Window, out int w, out int h);
SDL.GetWindowPosition(Window, out int x, out int y);
Resized?.Invoke(new Vector4(x, y, w, h));
break;
}
EventCallback?.Invoke(ev);
}
if (SDL.GetWindowFlags(Window).HasFlag(SDL.WindowFlags.Minimized))
{
SDL.Delay(10);
continue;
}
GL.MakeCurrent();
GL.ClearColor(ClearColor.X, ClearColor.Y, ClearColor.Z, ClearColor.W);
GL.Clear(GLClearBufferMask.ColorBufferBit);
ImGuiSDL3Platform.NewFrame();
ImGuiSDL3Renderer.NewFrame();
ImGui.NewFrame();
RenderCallback?.Invoke(); RenderCallback?.Invoke();
Render(); ImGuiIOPtr io = ImGui.GetIO();
ImGui.Render();
GL.MakeCurrent();
ImGuiSDL3Renderer.RenderDrawData(ImGui.GetDrawData());
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
ImGui.UpdatePlatformWindows();
ImGui.RenderPlatformWindowsDefault();
}
GL.MakeCurrent();
GL.SwapBuffers();
if (ShouldClose) if (ShouldClose)
{ {
@@ -126,56 +236,6 @@ public sealed unsafe class SDL3Window : IDisposable
Dispose(); Dispose();
} }
public bool ShouldClose;
private void PollEvents()
{
if (ImGui.GetIO().WantTextInput && !SDL.TextInputActive(Window))
SDL.StartTextInput(Window);
else if (!ImGui.GetIO().WantTextInput && SDL.TextInputActive(Window))
SDL.StopTextInput(Window);
while (SDL.PollEvent(out SDL.Event ev))
{
ImGuiSDL3Platform.ProcessEvent(ev);
switch ((SDL.EventType)ev.Type)
{
case SDL.EventType.Terminating:
case SDL.EventType.WindowCloseRequested:
case SDL.EventType.Quit:
ShouldClose = true;
break;
}
}
}
private void Update()
{
ImGuiSDL3Platform.NewFrame();
ImGuiSDL3Renderer.NewFrame();
ImGui.NewFrame();
}
private void Render()
{
ImGuiIOPtr io = ImGui.GetIO();
ImGui.Render();
SDL.SetRenderScale(Renderer, io.DisplayFramebufferScale.X, io.DisplayFramebufferScale.Y);
SDL.SetRenderDrawColorFloat(Renderer, ClearColor.X, ClearColor.Y, ClearColor.Z, ClearColor.W);
SDL.RenderClear(Renderer);
ImGuiSDL3Renderer.RenderDrawData(ImGui.GetDrawData(), Renderer);
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
ImGui.UpdatePlatformWindows();
ImGui.RenderPlatformWindowsDefault();
}
SDL.RenderPresent(Renderer);
}
~SDL3Window() ~SDL3Window()
{ {
Dispose(false); Dispose(false);
@@ -194,10 +254,22 @@ public sealed unsafe class SDL3Window : IDisposable
if (disposing) if (disposing)
{ {
if (_imGuiContext.Handle != null)
{
ImGui.SetCurrentContext(_imGuiContext);
}
if (_imPlotContext.Handle != null)
{
ImPlot.SetCurrentContext(_imPlotContext);
}
Disposing?.Invoke();
ImGuiSDL3Renderer.Dispose(); ImGuiSDL3Renderer.Dispose();
ImGuiSDL3Platform.Dispose(); ImGuiSDL3Platform.Dispose();
RenderCallback = null; RenderCallback = null;
Disposing = null;
} }
if (_imGuiContext.Handle != null) if (_imGuiContext.Handle != null)
@@ -206,11 +278,29 @@ public sealed unsafe class SDL3Window : IDisposable
ImGui.DestroyContext(_imGuiContext); ImGui.DestroyContext(_imGuiContext);
_imGuiContext = null; _imGuiContext = null;
} }
if (_imPlotContext.Handle != null)
if (Renderer != nint.Zero)
{ {
SDL.DestroyRenderer(Renderer); ImPlot.SetCurrentContext(null);
ImPlot.DestroyContext(_imPlotContext);
_imPlotContext = null;
} }
if (_imNodesContext.Handle != null)
{
ImNodes.SetCurrentContext(null);
ImNodes.DestroyContext(_imNodesContext);
_imNodesContext = null;
}
// if (_imPlot3DContext.Handle != null)
// {
// ImPlot3D.SetCurrentContext(null);
// ImPlot3D.DestroyContext(_imPlot3DContext);
// _imPlot3DContext = null;
// }
// if (Renderer != nint.Zero)
// {
// SDL.DestroyRenderer(Renderer);
// }
if (Window != nint.Zero) if (Window != nint.Zero)
{ {
@@ -219,3 +309,52 @@ public sealed unsafe class SDL3Window : IDisposable
} }
} }
public unsafe class BindingsContext : IGLContext
{
private readonly nint window;
private readonly nint context;
public BindingsContext(nint window, nint context)
{
this.window = window;
this.context = context;
}
public nint Handle => window;
public bool IsCurrent => SDL.GLGetCurrentContext() == context;
public void Dispose() { }
public nint GetProcAddress(string procName)
{
return (nint)SDL.GLGetProcAddress(procName).GetPtrForDelegate();
}
public bool IsExtensionSupported(string extensionName)
{
return SDL.GLExtensionSupported(extensionName);
}
public void MakeCurrent()
{
SDL.GLMakeCurrent(window, context);
}
public void SwapBuffers()
{
SDL.GLSwapWindow(window);
}
public void SwapInterval(int interval)
{
SDL.GLSetSwapInterval(interval);
}
public bool TryGetProcAddress(string procName, out nint procAddress)
{
procAddress = (nint)SDL.GLGetProcAddress(procName).GetPtrForDelegate();
return procAddress != 0;
}
}