1 Commits

Author SHA1 Message Date
NepuShiro 060f117a01 ImGuiNet 2026-05-18 01:36:55 -05:00
9 changed files with 955 additions and 1321 deletions
+11 -166
View File
@@ -1,33 +1,27 @@
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Hexa.NET.ImGui; using ImGuiNET;
using Hexa.NET.ImPlot;
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 readonly Dictionary<string, List<uint>?> GlyphsByName = new Dictionary<string, List<uint>?>();
private static bool _initialized;
private static ImFontPtr _font;
private static float size = 1f;
public static void Main() public static void Main()
{ {
SDL3Window window = new SDL3Window("SDL3 Testing Suite", 100, 100, 1280, 720); const SDL.WindowFlags flags = SDL.WindowFlags.Resizable | SDL.WindowFlags.HighPixelDensity | SDL.WindowFlags.Transparent;
window.RenderCallback += () => SDL3Window window = new SDL3Window("SDL3 Testing Suite", 100, 100, 1280, 720, flags);
window.RenderCallback = () =>
{ {
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);
if (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"))
@@ -41,148 +35,16 @@ public class Program
} }
ImGui.Spacing(); ImGui.Spacing();
ImGui.MenuItem("Demo Window", "", ref _demoWindowVisible); ImGui.MenuItem("Demo Window", "", ref _demoWindowVisible);
ImGui.Spacing();
ImGui.MenuItem("ImPlot Demo Window", "", ref _imPlotDemoVisible);
ImGui.Spacing();
ImGui.MenuItem("Font Stuff", "", ref _fontStuff);
ImGui.EndMenuBar(); ImGui.EndMenuBar();
} }
ImGui.End(); ImGui.End();
}
if (_fontStuff)
{
ImGui.SetNextWindowSize(new Vector2(250, 500), ImGuiCond.FirstUseEver);
if (ImGui.Begin("FontStuff", ref _fontStuff))
{
ImGui.ShowFontSelector("Font");
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();
}
}
if (ImGui.Begin("Thing"))
{
float time = (float)ImGui.GetTime() * 5;
if (ImPlot.BeginPlot("Moving Rainbow Sine Wave"))
{
int count = 200;
float[] xs = new float[2];
float[] ys = new float[2];
for (int i = 0; i < count - 1; i++)
{
float x0 = i * 0.1f;
float x1 = (i + 1) * 0.1f;
float y0 = MathF.Sin(x0 * size + time);
float y1 = MathF.Sin(x1 * size + time);
xs[0] = x0;
xs[1] = x1;
ys[0] = y0;
ys[1] = y1;
float t = i / (float)count;
float r = 0.5f + 1f * MathF.Sin(6.2831f * (t));
float g = 0.5f + 1f * MathF.Sin(6.2831f * (t + 0.33f));
float b = 0.5f + 1f * MathF.Sin(6.2831f * (t + 0.66f));
ImPlot.PushStyleColor(ImPlotCol.Line, new Vector4(r, g, b, 1f));
ImPlot.PlotLine("##seg", ref xs[0], ref ys[0], 2);
ImPlot.PopStyleColor();
}
ImPlot.EndPlot();
}
ImGui.SliderFloat("Sine", ref size, 1f, 120f);
ImGui.End();
}
if (ImGui.Begin("ImageThing"))
{
ImGui.End();
}
if (_demoWindowVisible) if (_demoWindowVisible)
{ {
ImGui.ShowDemoWindow(ref _demoWindowVisible); ImGui.ShowDemoWindow(ref _demoWindowVisible);
} }
if (_imPlotDemoVisible)
{
ImPlot.ShowDemoWindow(ref _imPlotDemoVisible);
}
}; };
window.Run(); window.Run();
@@ -190,30 +52,13 @@ public class Program
public static class Logger public static class Logger
{ {
private const int MessageWidth = 80; public static void Log(string? str, [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0)
private const int CallerWidth = 35;
public static void Log(object? value, [CallerFilePath] string path = "", [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0)
{ {
Write(value?.ToString(), path, caller, line); Console.WriteLine($"{caller}({line}): {str}");
} }
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)
{ {
if (values == null) Log(str?.ToString(), caller, line);
{
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}");
} }
} }
} }
+6 -5
View File
@@ -11,11 +11,12 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<!--<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.ImPlot" Version="2.2.9" /> <!-- <PackageReference Include="Hexa.NET.ImPlot" Version="2.2.9" />-->
<PackageReference Include="Hexa.NET.Utilities" Version="2.2.12" /> <!-- <PackageReference Include="Hexa.NET.ImPlot3D" Version="2.2.9" />-->
<!-- <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" />
</ItemGroup> </ItemGroup>
+2 -1
View File
@@ -1,2 +1,3 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AImFontConfig_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003Fhome_003Fnepushiro_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fc97073b326e54291bbfaa37650bd4af34d6200_003F7f_003F46ea95ef_003FImFontConfig_002Ecs/@EntryIndexedValue">ForceIncluded</s:String></wpf:ResourceDictionary> <s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AImFontConfig_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003Fhome_003Fnepushiro_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fc97073b326e54291bbfaa37650bd4af34d6200_003F7f_003F46ea95ef_003FImFontConfig_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AImPtrVector_00601_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003Fhome_003Fnepushiro_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F8243060d9bfb43bd93c81caad5fecadf4d800_003Ffa_003Ff2bd8dce_003FImPtrVector_00601_002Ecs/@EntryIndexedValue">ForceIncluded</s:String></wpf:ResourceDictionary>
-8
View File
@@ -1,8 +0,0 @@
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);
}
-160
View File
@@ -1,160 +0,0 @@
using Hexa.NET.ImGui;
namespace SDL3_TestingSuite.SDL3;
public struct FontMetrics
{
public ushort UnitsPerEm;
public short TypoAscender;
public short TypoDescender;
public short TypoLineGap;
public short WinAscent;
public short WinDescent;
public int TypoLineHeight;
public int WinLineHeight;
}
public static class FontFind
{
extension(ImGuiIOPtr io)
{
public unsafe ImFontPtr AddFont(string fontPath)
{
try
{
if (fontPath == null || io.Handle == null) return null;
FileInfo info = new FileInfo(fontPath);
if (!info.Exists || info.Length <= 0) return null;
FontMetrics metrics = ReadFontMetrics(fontPath);
float size = GetRecommendedPixelSize(metrics);
ImFontConfigPtr config = ImGui.ImFontConfig();
config.FontLoaderFlags |= (uint)ImGuiFreeTypeLoaderFlags.LoadColor;
ImFontPtr font = io.Fonts.AddFontFromFileTTF(fontPath, size, config);
Program.Logger.Log("Added font: " + Path.GetFileName(fontPath));
return font;
}
catch (Exception e)
{
Console.WriteLine(e);
}
return null;
}
public unsafe bool RemoveFont(string? fontName)
{
if (fontName == null || io.Handle == null) return false;
bool flag = false;
ImVector<ImFontPtr> fonts = io.Fonts.Fonts;
List<ImFontPtr> toRemove = new List<ImFontPtr>();
for (int i = 0; i < fonts.Size; i++)
{
ImFontPtr font = fonts[i];
if (font.GetDebugNameS() == fontName)
{
toRemove.Add(font);
flag = true;
}
}
foreach (ImFontPtr font in toRemove)
{
io.Fonts.RemoveFont(font);
Program.Logger.Log("Removed font: " + fontName);
}
return flag;
}
}
public static FontMetrics ReadFontMetrics(string fontPath)
{
byte[] data = File.ReadAllBytes(fontPath);
ushort numTables = ReadU16Be(4);
const int tableDir = 12;
int headOffset = 0;
int os2Offset = 0;
for (int i = 0; i < numTables; i++)
{
int entry = tableDir + i * 16;
string tag = ReadTag(entry);
uint offset = ReadU32Be(entry + 8);
if (tag == "head")
headOffset = (int)offset;
if (tag == "OS/2")
os2Offset = (int)offset;
}
FontMetrics metrics = new FontMetrics();
metrics.UnitsPerEm = ReadU16Be(headOffset + 18);
if (os2Offset != 0)
{
metrics.TypoAscender = ReadS16Be(os2Offset + 68);
metrics.TypoDescender = ReadS16Be(os2Offset + 70);
metrics.TypoLineGap = ReadS16Be(os2Offset + 72);
metrics.WinAscent = ReadS16Be(os2Offset + 74);
metrics.WinDescent = ReadS16Be(os2Offset + 76);
}
metrics.TypoLineHeight = metrics.TypoAscender - metrics.TypoDescender + metrics.TypoLineGap;
metrics.WinLineHeight = metrics.WinAscent + metrics.WinDescent;
return metrics;
ushort ReadU16Be(int o)
{
return (ushort)((data[o] << 8) | data[o + 1]);
}
short ReadS16Be(int o)
{
return (short)ReadU16Be(o);
}
uint ReadU32Be(int o)
{
return (uint)((data[o] << 24) | (data[o + 1] << 16) | (data[o + 2] << 8) | data[o + 3]);
}
string ReadTag(int o)
{
char c1 = (char)data[o];
char c2 = (char)data[o + 1];
char c3 = (char)data[o + 2];
char c4 = (char)data[o + 3];
return new string(new char[] { c1, c2, c3, c4 });
}
}
public static int GetRecommendedPixelSize(FontMetrics metrics)
{
if (metrics.UnitsPerEm == 0 || metrics.TypoLineHeight == 0)
return 16;
const float targetLineHeightPx = 18.0f;
float scale = targetLineHeightPx * metrics.UnitsPerEm / metrics.TypoLineHeight;
int size = (int)MathF.Round(scale);
if (size < 10) size = 10;
if (size > 72) size = 72;
return size;
}
}
+537 -497
View File
File diff suppressed because it is too large Load Diff
+214 -221
View File
@@ -1,8 +1,6 @@
using System.Diagnostics;
using System.Numerics; using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using Hexa.NET.ImGui; using ImGuiNET;
using SDL3; using SDL3;
namespace SDL3_TestingSuite.SDL3; namespace SDL3_TestingSuite.SDL3;
@@ -25,137 +23,199 @@ public unsafe static class ImGuiSDL3Renderer
private struct BackupSDLRendererState private struct BackupSDLRendererState
{ {
public SDL.Rect Viewport; public SDL.Rect Viewport;
public bool ViewportEnabled;
public bool ClipEnabled; public bool ClipEnabled;
public SDL.Rect ClipRect; public SDL.Rect ClipRect;
} }
public static RendererData GetRendererData() => ImGui.GetCurrentContext().Handle != null ? ImGuiUserData<RendererData>.Get(ImGui.GetIO().BackendRendererUserData)! : null!; [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void RendererCreateWindowFn(ImGuiViewportPtr viewport);
public static SDL3Window? Parent; private static readonly RendererCreateWindowFn RendererCreateWindowDelegate = RendererCreateWindow;
public static bool Init(nint renderer, SDL3Window? parentWindow = null) [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void RendererDestroyWindowFn(ImGuiViewportPtr viewport);
private static readonly RendererDestroyWindowFn RendererDestroyWindowDelegate = RendererDestroyWindow;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void RendererSetWindowSizeFn(ImGuiViewportPtr viewport, Vector2 size);
private static readonly RendererSetWindowSizeFn RendererSetWindowSizeDelegate = RendererSetWindowSize;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void RendererRenderWindowFn(ImGuiViewportPtr viewport);
private static readonly RendererRenderWindowFn RendererRenderWindowDelegate = RendererRenderWindow;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void RendererSwapBuffersFn(ImGuiViewportPtr viewport);
private static readonly RendererSwapBuffersFn RendererSwapBuffersDelegate = RendererSwapBuffers;
public static RendererData Data => ImGui.GetCurrentContext() != nint.Zero ? ImGuiUserData<RendererData>.Get(ImGui.GetIO().BackendRendererUserData)! : null!;
private static nint _fontTexture = nint.Zero;
public static bool Init(nint renderer)
{ {
Parent = parentWindow;
ImGuiIOPtr io = ImGui.GetIO(); ImGuiIOPtr io = ImGui.GetIO();
RendererData bd = new RendererData(); RendererData bd = new RendererData();
io.BackendRendererUserData = ImGuiUserData<RendererData>.Store(bd); io.BackendRendererUserData = ImGuiUserData<RendererData>.Store(bd);
io.BackendRendererName = (byte*)Marshal.StringToHGlobalAnsi("NepImGuiSDL3Renderer");
io.BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset; // We can honor the ImDrawCmd.VtxOffset field, allowing for large meshes. io.BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset; // We can honor the ImDrawCmd.VtxOffset field, allowing for large meshes.
io.BackendFlags |= ImGuiBackendFlags.RendererHasTextures; // We can honor ImGuiPlatformIO.Textures[] requests during render.
io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports; io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports;
bd.Renderer = renderer; bd.Renderer = renderer;
ImGuiPlatformIOPtr platformIO = ImGui.GetPlatformIO(); ImGuiPlatformIOPtr platformIO = ImGui.GetPlatformIO();
platformIO.RendererCreateWindow = DelegateStorage.RendererCreateWindowDelegate.GetPtrForDelegate(); platformIO.Renderer_CreateWindow = Marshal.GetFunctionPointerForDelegate(RendererCreateWindowDelegate);
platformIO.RendererDestroyWindow = DelegateStorage.RendererDestroyWindowDelegate.GetPtrForDelegate(); platformIO.Renderer_DestroyWindow = Marshal.GetFunctionPointerForDelegate(RendererDestroyWindowDelegate);
platformIO.RendererRenderWindow = DelegateStorage.RendererRenderWindowDelegate.GetPtrForDelegate(); platformIO.Renderer_SetWindowSize = Marshal.GetFunctionPointerForDelegate(RendererSetWindowSizeDelegate);
platformIO.RendererSwapBuffers = DelegateStorage.RendererSwapBuffersDelegate.GetPtrForDelegate(); platformIO.Renderer_RenderWindow = Marshal.GetFunctionPointerForDelegate(RendererRenderWindowDelegate);
platformIO.Renderer_SwapBuffers = Marshal.GetFunctionPointerForDelegate(RendererSwapBuffersDelegate);
return true; return true;
} }
public static void Dispose() public static void Dispose()
{ {
ImGuiIOPtr io = ImGui.GetIO(); var io = ImGui.GetIO();
ImGuiPlatformIOPtr platformIO = ImGui.GetPlatformIO(); var platformIO = ImGui.GetPlatformIO();
if (io.BackendRendererName != null) DestroyDeviceObjects();
{
Marshal.FreeHGlobal((nint)io.BackendRendererName);
}
ImGuiUserData<RendererData>.Free(io.BackendRendererUserData); io.BackendRendererUserData = nint.Zero;
io.BackendRendererName = null; io.BackendFlags &= ~ImGuiBackendFlags.RendererHasVtxOffset;
io.BackendRendererUserData = null; platformIO.Renderer_RenderState = nint.Zero;
io.BackendFlags &= ~(ImGuiBackendFlags.RendererHasVtxOffset | ImGuiBackendFlags.RendererHasTextures | ImGuiBackendFlags.RendererHasViewports); platformIO.Renderer_CreateWindow = nint.Zero;
platformIO.RendererTextureMaxWidth = 0; platformIO.Renderer_DestroyWindow = nint.Zero;
platformIO.RendererTextureMaxHeight = 0; platformIO.Renderer_SetWindowSize = nint.Zero;
platformIO.RendererRenderState = null; platformIO.Renderer_RenderWindow = nint.Zero;
} platformIO.Renderer_SwapBuffers = nint.Zero;
public static void SetupRenderState(nint renderer)
{
// Clear out any viewports and cliprect set by the user
// FIXME: Technically speaking there are lots of other things we could backup/setup/restore during our render process.
SDL.SetRenderViewport(renderer, nint.Zero);
SDL.SetRenderClipRect(renderer, nint.Zero);
} }
public static void NewFrame() public static void NewFrame()
{ {
RendererData bd = GetRendererData(); if (_fontTexture == nint.Zero)
Debug.Assert(bd != null, "Context or backend not initialized! Did you call ImGuiSDL3Renderer.Init()?"); {
CreateDeviceObjects();
}
}
private static void RendererCreateWindow(ImGuiViewportPtr viewport)
{
Program.Logger.Log(null);
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
if (vd == null || vd.Window == nint.Zero)
return;
if (vd.Renderer == nint.Zero)
{
vd.Renderer = SDL.CreateRenderer(vd.Window, (string?)null);
vd.RendererOwned = true;
}
Program.Logger.Log(null);
}
private static void RendererDestroyWindow(ImGuiViewportPtr viewport)
{
Program.Logger.Log(null);
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
if (vd == null)
return;
if (vd.RendererOwned && vd.Renderer != nint.Zero)
{
SDL.DestroyRenderer(vd.Renderer);
}
vd.Renderer = nint.Zero;
vd.RendererOwned = false;
Program.Logger.Log(null);
}
private static void RendererSetWindowSize(ImGuiViewportPtr viewport, Vector2 size)
{
// SDL renderer windows track size through the platform window callback.
Program.Logger.Log(null);
}
private static void RendererRenderWindow(ImGuiViewportPtr viewport)
{
Program.Logger.Log(null);
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
if (vd == null || vd.Renderer == nint.Zero)
{
return;
}
RenderDrawData(viewport.DrawData, vd.Renderer);
Program.Logger.Log(null);
}
private static void RendererSwapBuffers(ImGuiViewportPtr viewport)
{
Program.Logger.Log(null);
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
if (vd == null || vd.Renderer == nint.Zero)
return;
SDL.RenderPresent(vd.Renderer);
Program.Logger.Log(null);
} }
public static void RenderDrawData(ImDrawDataPtr drawData, nint renderer) public static void RenderDrawData(ImDrawDataPtr drawData, nint renderer)
{ {
// Skip if no data to render // Skip if no data to render
if (drawData.Handle == null || drawData.CmdListsCount == 0) if (drawData.NativePtr == null || drawData.CmdListsCount == 0)
return; return;
SDL.GetRenderScale(renderer, out float renderScaleX, out float renderScaleY); SDL.GetRenderScale(renderer, out float renderScaleX, out float renderScaleY);
Vector2 renderScale = new Vector2(renderScaleX == 1.0f ? drawData.FramebufferScale.X : 1.0f, renderScaleY == 1.0f ? drawData.FramebufferScale.Y : 1.0f); Vector2 renderScale = new Vector2(
renderScaleX == 1.0f ? drawData.FramebufferScale.X : 1.0f,
renderScaleY == 1.0f ? drawData.FramebufferScale.Y : 1.0f);
int fbWidth = (int)(drawData.DisplaySize.X * renderScale.X); int fbWidth = (int)(drawData.DisplaySize.X * renderScale.X);
int fbHeight = (int)(drawData.DisplaySize.Y * renderScale.Y); int fbHeight = (int)(drawData.DisplaySize.Y * renderScale.Y);
if (fbWidth <= 0 || fbHeight <= 0) if (fbWidth <= 0 || fbHeight <= 0)
return; return;
for (int i = 0; i < drawData.Textures.Size; i++)
{
ImTextureDataPtr texture = drawData.Textures[i];
if (texture.Handle != null)
{
UpdateTexture(texture, renderer);
}
}
// Backup SDL renderer state // Backup SDL renderer state
BackupSDLRendererState old = new BackupSDLRendererState BackupSDLRendererState old = new BackupSDLRendererState
{ {
ViewportEnabled = SDL.RenderViewportSet(renderer),
ClipEnabled = SDL.RenderClipEnabled(renderer) ClipEnabled = SDL.RenderClipEnabled(renderer)
}; };
SDL.GetRenderViewport(renderer, out old.Viewport); SDL.GetRenderViewport(renderer, out var oldViewport);
SDL.GetRenderClipRect(renderer, out old.ClipRect); old.Viewport = oldViewport;
SDL.GetRenderClipRect(renderer, out var oldClipRect);
old.ClipRect = oldClipRect;
// Set up render state // Set up render state
SetupRenderState(renderer); SDL.SetRenderViewport(renderer, 0);
SDL.SetRenderClipRect(renderer, nint.Zero);
// Set render state in platform IO // Set render state in platform IO
ImGuiPlatformIOPtr platformIo = ImGui.GetPlatformIO(); ImGuiPlatformIOPtr platformIo = ImGui.GetPlatformIO();
platformIo.RendererRenderState = (void*)renderer; platformIo.Renderer_RenderState = renderer;
Vector2 clipOffset = drawData.DisplayPos; Vector2 clipOffset = drawData.DisplayPos;
// Render command lists // Render command lists
for (int n = 0; n < drawData.CmdListsCount; n++) for (int n = 0; n < drawData.CmdListsCount; n++)
{ {
ImDrawListPtr drawList = drawData.CmdLists[n]; ImDrawListPtr cmdList = drawData.CmdLists[n];
for (int cmdIndex = 0; cmdIndex < drawList.CmdBuffer.Size; cmdIndex++) for (int cmdIndex = 0; cmdIndex < cmdList.CmdBuffer.Size; cmdIndex++)
{ {
ImDrawCmd cmd = drawList.CmdBuffer[cmdIndex]; ImDrawCmdPtr cmd = cmdList.CmdBuffer[cmdIndex];
if (cmd.UserCallback != null) if (cmd.UserCallback != nint.Zero)
{ {
if (cmd.UserCallback == DelegateStorage.DrawCallbackResetRenderStateDelegate.GetPtrForDelegate()) continue; // User callback not implemented
{
SetupRenderState(renderer);
} }
else
{
// this is cursed af and idk if it even works :)
ImDrawCmdPtr cmdPtr = new ImDrawCmdPtr
{
Handle = (ImDrawCmd*)Unsafe.AsPointer(ref cmd)
};
((delegate* unmanaged[Cdecl]<ImDrawListPtr, ImDrawCmdPtr, void>)cmd.UserCallback)(drawList, cmdPtr);
}
}
else
{
// Apply clipping rectangle // Apply clipping rectangle
Vector4 clipRect = cmd.ClipRect; Vector4 clipRect = cmd.ClipRect;
Vector2 clipMin = new Vector2((clipRect.X - clipOffset.X) * renderScale.X, (clipRect.Y - clipOffset.Y) * renderScale.Y); Vector2 clipMin = new Vector2((clipRect.X - clipOffset.X) * renderScale.X, (clipRect.Y - clipOffset.Y) * renderScale.Y);
@@ -177,7 +237,27 @@ public unsafe static class ImGuiSDL3Renderer
}; };
SDL.SetRenderClipRect(renderer, r); SDL.SetRenderClipRect(renderer, r);
// Get texture
nint texId = cmd.GetTexID();
// Convert ImGui vertices to SDL vertices // Convert ImGui vertices to SDL vertices
if (!RenderDrawCommand(cmdList, cmd, renderer, texId, renderScale))
{
Console.WriteLine($"Failed to render ImGui draw command: {SDL.GetError()}");
}
}
}
// Reset render state
platformIo.Renderer_RenderState = nint.Zero;
// Restore renderer state
SDL.SetRenderViewport(renderer, old.ViewportEnabled ? old.Viewport : new SDL.Rect());
SDL.SetRenderClipRect(renderer, old.ClipEnabled ? old.ClipRect : new SDL.Rect());
}
private static bool RenderDrawCommand(ImDrawListPtr drawList, ImDrawCmdPtr cmd, nint renderer, nint texId, Vector2 scale)
{
uint indexOffset = cmd.IdxOffset; uint indexOffset = cmd.IdxOffset;
uint vertexOffset = cmd.VtxOffset; uint vertexOffset = cmd.VtxOffset;
uint elemCount = cmd.ElemCount; uint elemCount = cmd.ElemCount;
@@ -190,188 +270,101 @@ public unsafe static class ImGuiSDL3Renderer
ushort idx = drawList.IdxBuffer[(int)indexOffset + i]; ushort idx = drawList.IdxBuffer[(int)indexOffset + i];
int vertIdx = (int)(vertexOffset + idx); int vertIdx = (int)(vertexOffset + idx);
ImDrawVert srcVert = drawList.VtxBuffer[vertIdx]; ImDrawVertPtr srcVert = drawList.VtxBuffer[vertIdx];
uint col = srcVert.Col; uint col = srcVert.col;
byte colR = (byte)((col >> 0) & 0xFF); byte r = (byte)((col >> 0) & 0xFF);
byte colG = (byte)((col >> 8) & 0xFF); byte g = (byte)((col >> 8) & 0xFF);
byte colB = (byte)((col >> 16) & 0xFF); byte b = (byte)((col >> 16) & 0xFF);
byte colA = (byte)((col >> 24) & 0xFF); byte a = (byte)((col >> 24) & 0xFF);
vertices[i] = new SDL.Vertex vertices[i] = new SDL.Vertex()
{ {
Position = new SDL.FPoint Position = new SDL.FPoint()
{ {
X = (srcVert.Pos.X - clipOffset.X) * renderScale.X, X = srcVert.pos.X * scale.X,
Y = (srcVert.Pos.Y - clipOffset.Y) * renderScale.Y Y = srcVert.pos.Y * scale.Y
}, },
Color = new SDL.FColor Color = new SDL.FColor()
{ {
R = colR / 255f, R = r / 255f,
G = colG / 255f, G = g / 255f,
B = colB / 255f, B = b / 255f,
A = colA / 255f A = a / 255f
}, },
TexCoord = new SDL.FPoint TexCoord = new SDL.FPoint()
{ {
X = srcVert.Uv.X, X = srcVert.uv.X,
Y = srcVert.Uv.Y Y = srcVert.uv.Y
} }
}; };
indices[i] = i; indices[i] = i;
} }
// Get texture return SDL.RenderGeometry(renderer, texId, vertices, vertices.Length, indices, indices.Length);
ImTextureID texId = cmd.GetTexID(); }
if (!SDL.RenderGeometry(renderer, texId, vertices, vertices.Length, indices, indices.Length))
public static void CreateDeviceObjects()
{ {
Program.Logger.Log($"Failed to render ImGui draw command: {SDL.GetError()}"); ImGuiIOPtr io = ImGui.GetIO();
} var data = Data;
}
}
}
// Reset render state io.Fonts.AddFontDefault();
platformIo.RendererRenderState = null;
// Restore renderer state // TODO: Load custom fonts from "Fonts" directory
SDL.SetRenderViewport(renderer, old.Viewport); //string fontsPath = Path.Combine(Plugin.AssemblyDirectory, "Fonts");
SDL.SetRenderClipRect(renderer, old.ClipEnabled ? old.ClipRect : new SDL.Rect()); //if (Path.Exists(fontsPath))
} //{
// string[] fonts = Directory.GetFiles(fontsPath, "*.ttf");
// if (fonts.Length > 0)
// {
// foreach (string font in fonts)
// {
// io.Fonts.AddFontFromFileTTF(font, 20f);
// }
// }
//}
private static void UpdateTexture(ImTextureDataPtr tex, nint renderer) // Build texture atlas
io.Fonts.GetTexDataAsRGBA32(out byte* pixels, out int width, out int height);
// Create surface from pixel data
nint surface = SDL.CreateSurfaceFrom(width, height, SDL.PixelFormat.RGBA8888, (nint)pixels, width * 4);
if (surface == nint.Zero)
{ {
if (tex.Status == ImTextureStatus.WantDestroy) SDL.LogError(SDL.LogCategory.Application, $"Failed to create font surface: {SDL.GetError()}");
{
if (tex.TexID != ImTextureID.Null)
SDL.DestroyTexture(tex.TexID);
tex.SetTexID(ImTextureID.Null);
tex.SetStatus(ImTextureStatus.Destroyed);
return; return;
} }
bool needsCreate = tex.TexID == ImTextureID.Null || SDL.GetRendererFromTexture(tex.TexID) != renderer; // Create texture
if (tex.Status == ImTextureStatus.WantCreate || needsCreate) _fontTexture = SDL.CreateTextureFromSurface(data.Renderer, surface);
if (_fontTexture == nint.Zero)
{ {
if (tex.TexID != ImTextureID.Null) SDL.LogError(SDL.LogCategory.Application, $"Failed to create font texture: {SDL.GetError()}");
SDL.DestroyTexture(tex.TexID);
// Create texture on the renderer that is actually drawing this viewport.
// SDL textures are renderer-owned and cannot be shared across renderer instances.
nint sdlTexture = SDL.CreateTexture(renderer, SDL.PixelFormat.ABGR8888, SDL.TextureAccess.Static, tex.Width, tex.Height);
SDL.UpdateTexture(sdlTexture, nint.Zero, (nint)tex.GetPixels(), tex.GetPitch());
SDL.SetTextureBlendMode(sdlTexture, SDL.BlendMode.Blend);
SDL.SetTextureScaleMode(sdlTexture, SDL.ScaleMode.Linear);
tex.SetTexID(sdlTexture);
tex.SetStatus(ImTextureStatus.Ok);
return; return;
} }
if (tex.Status == ImTextureStatus.WantUpdates) // Update texture directly without converting pixel format
{ if (!SDL.UpdateTexture(_fontTexture, nint.Zero, (nint)pixels, width * 4))
// Update selected blocks. We only ever write to textures regions which have never been used before!
// This backend choose to use tex.Updates[] but you can use tex.UpdateRect to upload a single region.
nint sdlTexture = tex.TexID;
for (int i = 0; i < tex.Updates.Size; i++)
{
ImTextureRect r = tex.Updates[i];
SDL.Rect sdlR = new SDL.Rect { X = r.X, Y = r.Y, W = r.W, H = r.H };
SDL.UpdateTexture(sdlTexture, sdlR, (nint)tex.GetPixelsAt(r.X, r.Y), tex.GetPitch());
}
tex.SetStatus(ImTextureStatus.Ok);
}
}
public static void CreateDeviceObjects() { }
public static void DestroyDeviceObjects()
{
ImVector<ImTextureDataPtr> texures = ImGui.GetPlatformIO().Textures;
for (int i = 0; i < texures.Size; i++)
{
ImTextureDataPtr texture = texures[i];
texture.Status = ImTextureStatus.WantDestroy;
UpdateTexture(texture, GetRendererData().Renderer);
}
}
// @formatter:off — disable formatter after this line
public static class DelegateStorage
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void DrawCallbackResetRenderStateFn(ImDrawListPtr drawList, ImDrawCmdPtr cmd);
internal static readonly DrawCallbackResetRenderStateFn DrawCallbackResetRenderStateDelegate = DrawCallbackResetRenderState;
private static void DrawCallbackResetRenderState(ImDrawListPtr drawList, ImDrawCmdPtr cmd) { } // Intentionally empty. Used as an identifier for rendering loop to call its code. Simpler to implement this way.
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void RendererCreateWindowFn(ImGuiViewportPtr viewport);
internal static readonly RendererCreateWindowFn RendererCreateWindowDelegate = RendererCreateWindow;
private static void RendererCreateWindow(ImGuiViewportPtr viewport)
{
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
if (vd == null || vd.Window == nint.Zero)
return;
if (vd.Renderer == nint.Zero)
{
vd.Renderer = SDL.CreateRenderer(vd.Window, null);
vd.RendererOwned = true;
}
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void RendererDestroyWindowFn(ImGuiViewportPtr viewport);
internal static readonly RendererDestroyWindowFn RendererDestroyWindowDelegate = RendererDestroyWindow;
private static void RendererDestroyWindow(ImGuiViewportPtr viewport)
{
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
if (vd == null)
return;
if (vd.RendererOwned && vd.Renderer != nint.Zero)
{
SDL.DestroyRenderer(vd.Renderer);
}
vd.Renderer = nint.Zero;
vd.RendererOwned = false;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void RendererRenderWindowFn(ImGuiViewportPtr viewport);
internal static readonly RendererRenderWindowFn RendererRenderWindowDelegate = RendererRenderWindow;
private static void RendererRenderWindow(ImGuiViewportPtr viewport)
{
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
if (vd == null || vd.Renderer == nint.Zero)
{ {
SDL.LogError(SDL.LogCategory.Application, $"Failed to update font texture: {SDL.GetError()}");
return; return;
} }
if (Parent != null) // Ensure proper blending for font rendering
{ SDL.SetTextureBlendMode(_fontTexture, SDL.BlendMode.Blend);
SDL.SetRenderDrawColorFloat(vd.Renderer, Parent.ClearColor.X, Parent.ClearColor.Y, Parent.ClearColor.Z, 0f);
SDL.RenderClear(vd.Renderer); // Use nearest neighbor filtering for crisp font rendering at small sizes
SDL.SetTextureScaleMode(_fontTexture, SDL.ScaleMode.Linear);
// Store our identifier
io.Fonts.SetTexID(_fontTexture);
SDL.DestroySurface(surface);
io.Fonts.ClearTexData();
} }
RenderDrawData(viewport.DrawData, vd.Renderer); public static void DestroyDeviceObjects() { }
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void RendererSwapBuffersFn(ImGuiViewportPtr viewport);
internal static readonly RendererSwapBuffersFn RendererSwapBuffersDelegate = RendererSwapBuffers;
private static void RendererSwapBuffers(ImGuiViewportPtr viewport)
{
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
if (vd == null || vd.Renderer == nint.Zero)
return;
SDL.RenderPresent(vd.Renderer);
}
}
// @formatter:on — enable formatter after this line
} }
-35
View File
@@ -1,35 +0,0 @@
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();
}
}
+51 -94
View File
@@ -1,34 +1,31 @@
using System.Numerics; using System;
using Hexa.NET.ImGui; using System.Diagnostics;
using Hexa.NET.ImGuizmo; using System.Numerics;
using Hexa.NET.ImPlot; using System.Runtime.InteropServices;
using ImGuiNET;
using SDL3; using SDL3;
namespace SDL3_TestingSuite.SDL3; namespace SDL3_TestingSuite.SDL3;
public sealed unsafe class SDL3Window : IDisposable public sealed class SDL3Window : IDisposable
{ {
public readonly nint Window; public readonly nint Window;
public readonly nint Renderer; public readonly nint Renderer;
public readonly Vector4 DefaultClearColor = new Vector4(0.06f, 0.06f, 0.06f, 1f); internal Action? RenderCallback { get; set; }
private Vector4? _clearColor; public Vector4 ClearColor = new Vector4(0.06f, 0.05882353f, 0.05882353f, 1f);
public Vector4 ClearColor
{
get => _clearColor ?? DefaultClearColor;
set => _clearColor = value;
}
public event Action? RenderCallback; private readonly Stopwatch _timer = Stopwatch.StartNew();
private TimeSpan _time = TimeSpan.Zero;
private ImGuiContextPtr _imGuiContext; private SDL.Rect _screenClipRect;
private ImPlotContextPtr _imPlotContext; private nint _imGuiContext;
public bool Disposed => _disposed; public bool Disposed => _disposed;
private bool _disposed; private bool _disposed;
private readonly FileSystemWatcher? _watcher; private FileSystemWatcher? _watcher;
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)
{ {
@@ -45,63 +42,46 @@ public sealed unsafe class SDL3Window : IDisposable
// Create ImGui context // Create ImGui context
_imGuiContext = ImGui.CreateContext(); _imGuiContext = ImGui.CreateContext();
_imPlotContext = ImPlot.CreateContext();
ImPlot.SetImGuiContext(_imGuiContext);
ImGuizmo.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();
try
{
string fontsPath = Path.Combine(AppContext.BaseDirectory, "Fonts");
if (!Path.Exists(fontsPath)) Directory.CreateDirectory(fontsPath);
_watcher = new FileSystemWatcher(fontsPath);
_watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime;
_watcher.Created += (_, b) =>
{
if (!File.Exists(b.FullPath)) return;
if (Path.GetExtension(b.FullPath) != ".ttf") return;
ImGui.GetIO().AddFont(b.FullPath);
};
_watcher.Deleted += (_, b) =>
{
if (Path.GetExtension(b.FullPath) != ".ttf") return;
ImGui.GetIO().RemoveFont(b.Name);
};
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
string[] fonts = Directory.GetFiles(fontsPath, "*.ttf", SearchOption.AllDirectories);
foreach (string font in fonts)
{
io.AddFont(font);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
// Init platform and renderer // Init platform and renderer
ImGuiSDL3Platform.Init(Window, Renderer, this); ImGuiSDL3Platform.Init(Window, Renderer);
ImGuiSDL3Renderer.Init(Renderer, this); ImGuiSDL3Renderer.Init(Renderer);
} }
public bool ShouldClose;
public void Run() public void Run()
{ {
while (!_disposed) while (!_disposed)
{
ImGui.GetIO().DeltaTime = (float)(_timer.Elapsed - _time).TotalSeconds;
_time = _timer.Elapsed;
PollEvents();
Update();
RenderCallback?.Invoke();
Render();
if (ShouldClose)
{
Dispose();
break;
}
}
if (!_disposed)
Dispose();
}
public bool ShouldClose;
private void PollEvents()
{ {
if (ImGui.GetIO().WantTextInput && !SDL.TextInputActive(Window)) if (ImGui.GetIO().WantTextInput && !SDL.TextInputActive(Window))
SDL.StartTextInput(Window); SDL.StartTextInput(Window);
@@ -121,21 +101,23 @@ public sealed unsafe class SDL3Window : IDisposable
break; break;
} }
} }
}
private void Update()
{
ImGuiSDL3Platform.NewFrame(); ImGuiSDL3Platform.NewFrame();
ImGuiSDL3Renderer.NewFrame(); ImGuiSDL3Renderer.NewFrame();
ImGui.NewFrame(); ImGui.NewFrame();
}
RenderCallback?.Invoke(); private void Render()
{
ImGuiIOPtr io = ImGui.GetIO(); ImGuiIOPtr io = ImGui.GetIO();
ImGui.Render(); ImGui.Render();
SDL.SetRenderScale(Renderer, io.DisplayFramebufferScale.X, io.DisplayFramebufferScale.Y); SDL.SetRenderScale(Renderer, io.DisplayFramebufferScale.X, io.DisplayFramebufferScale.Y);
SDL.SetRenderDrawColorFloat(Renderer, ClearColor.X, ClearColor.Y, ClearColor.Z, ClearColor.W); SDL.SetRenderDrawColorFloat(Renderer, ClearColor.X, ClearColor.Y, ClearColor.Z, ClearColor.W);
SDL.RenderClear(Renderer); SDL.RenderClear(Renderer);
ImGuiSDL3Renderer.RenderDrawData(ImGui.GetDrawData(), Renderer); ImGuiSDL3Renderer.RenderDrawData(ImGui.GetDrawData(), Renderer);
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0) if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
@@ -145,16 +127,6 @@ public sealed unsafe class SDL3Window : IDisposable
} }
SDL.RenderPresent(Renderer); SDL.RenderPresent(Renderer);
if (ShouldClose)
{
Dispose();
break;
}
}
if (!_disposed)
Dispose();
} }
~SDL3Window() ~SDL3Window()
@@ -175,32 +147,17 @@ public sealed unsafe class SDL3Window : IDisposable
if (disposing) if (disposing)
{ {
if (_imGuiContext.Handle != null)
{
ImGui.SetCurrentContext(_imGuiContext);
}
if (_imPlotContext.Handle != null)
{
ImPlot.SetCurrentContext(_imPlotContext);
}
ImGuiSDL3Renderer.Dispose(); ImGuiSDL3Renderer.Dispose();
ImGuiSDL3Platform.Dispose(); ImGuiSDL3Platform.Dispose();
RenderCallback = null; RenderCallback = null;
} }
if (_imGuiContext.Handle != null) if (_imGuiContext != nint.Zero)
{ {
ImGui.SetCurrentContext(null); ImGui.SetCurrentContext(nint.Zero);
ImGui.DestroyContext(_imGuiContext); ImGui.DestroyContext(_imGuiContext);
_imGuiContext = null; _imGuiContext = nint.Zero;
}
if (_imPlotContext.Handle != null)
{
ImPlot.SetCurrentContext(null);
ImPlot.DestroyContext(_imPlotContext);
_imPlotContext = null;
} }
if (Renderer != nint.Zero) if (Renderer != nint.Zero)