This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit b578433e37
22 changed files with 784842 additions and 0 deletions

View file

@ -0,0 +1,120 @@
namespace Brutal.ImGuiApi;
public static partial class ImDrawListExtensions
{
/// <remarks><code>
/// Image primitives
/// - Read FAQ to understand what ImTextureID/ImTextureRef are.
/// - &quot;p_min&quot; and &quot;p_max&quot; represent the upper-left and lower-right corners of the rectangle.
/// - &quot;uv_min&quot; and &quot;uv_max&quot; represent the normalized texture coordinates to use for those corners. Using (0,0)-&gt;(1,1) texture coordinates will generally display the entire texture.
/// </code></remarks>
/// <source href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui.h#L3407"><a href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui.h#L3407">imgui.h:3407</a></source>
/// <br/>
/// <declaration><c>void AddImage(ImTextureRef tex_ref, const ImVec2&amp; p_min, const ImVec2&amp; p_max, const ImVec2&amp; uv_min = ImVec2(0, 0), const ImVec2&amp; uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE)</c></declaration>
public static void AddImage(
this ImDrawListPtr target,
ImTextureRef texRef,
in float2 pMin,
in float2 pMax,
in float2? uvMin = default,
in float2? uvMax = default,
ImColor8? col = default
)
{
unsafe
{
var uvMin_default = uvMin ?? new float2(0f, 0f);
var uvMax_default = uvMax ?? new float2(1f, 1f);
var col_default = col ?? new byte4(255);
fixed (float2* pMax_fixed = &pMax)
fixed (float2* pMin_fixed = &pMin)
{
ImGui.PInvoke.ImDrawList_AddImage(
target,
texRef,
pMin_fixed,
pMax_fixed,
&uvMin_default,
&uvMax_default,
col_default
);
}
}
}
/// <remarks><code>
/// Image primitives
/// - Read FAQ to understand what ImTextureID/ImTextureRef are.
/// - &quot;p_min&quot; and &quot;p_max&quot; represent the upper-left and lower-right corners of the rectangle.
/// - &quot;uv_min&quot; and &quot;uv_max&quot; represent the normalized texture coordinates to use for those corners. Using (0,0)-&gt;(1,1) texture coordinates will generally display the entire texture.
/// </code></remarks>
/// <source href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui.h#L3408"><a href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui.h#L3408">imgui.h:3408</a></source>
/// <br/>
/// <declaration><c>void AddImageQuad(ImTextureRef tex_ref, const ImVec2&amp; p1, const ImVec2&amp; p2, const ImVec2&amp; p3, const ImVec2&amp; p4, const ImVec2&amp; uv1 = ImVec2(0, 0), const ImVec2&amp; uv2 = ImVec2(1, 0), const ImVec2&amp; uv3 = ImVec2(1, 1), const ImVec2&amp; uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE)</c></declaration>
public static void AddImageQuad(
this ImDrawListPtr target,
ImTextureRef texRef,
in float2 p1,
in float2 p2,
in float2 p3,
in float2 p4,
in float2? uv1 = default,
in float2? uv2 = default,
in float2? uv3 = default,
in float2? uv4 = default,
ImColor8? col = default
)
{
unsafe
{
var uv1_default = uv1 ?? new float2(0f, 0f);
var uv2_default = uv2 ?? new float2(1f, 0f);
var uv3_default = uv3 ?? new float2(1f, 1f);
var uv4_default = uv4 ?? new float2(0f, 1f);
var col_default = col ?? new byte4(255);
fixed (float2* p4_fixed = &p4)
fixed (float2* p3_fixed = &p3)
fixed (float2* p2_fixed = &p2)
fixed (float2* p1_fixed = &p1)
{
ImGui.PInvoke.ImDrawList_AddImageQuad(
target,
texRef,
p1_fixed,
p2_fixed,
p3_fixed,
p4_fixed,
&uv1_default,
&uv2_default,
&uv3_default,
&uv4_default,
col_default
);
}
}
}
/// <remarks><code>
/// Advanced: Draw Callbacks
/// - May be used to alter render state (change sampler, blending, current shader).
/// - May be used to emit custom rendering commands (difficult to do correctly, but possible).
/// - Use special ImDrawCallback_ResetRenderState callback to instruct backend to reset its render state to the default.
/// - Your rendering loop must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. (All standard backends are honoring this.)
/// </code></remarks>
/// <summary>
/// User data is copied to a backing buffer by ImGui internals, and the callback points to the copy for user data
/// </summary>
public static unsafe void AddCallback<T>(this ImDrawListPtr target, ImDrawCallback callback, in T userData)
where T : unmanaged
{
fixed (void* ptr = &userData)
{
PInvoke.ImDrawList_AddCallback(
target,
Marshal.GetFunctionPointerForDelegate(callback),
ptr,
(UIntPtr)ByteSize.Of<T>()
);
}
}
}

View file

@ -0,0 +1,45 @@
namespace Brutal.ImGuiApi;
public partial class ImGui
{
// Manually wrap PInvoke.TextUnformatted() as Managed.Text(), as rules don't have renaming support.
/// <summary>
/// <para>raw text without formatting. Roughly equivalent to Text(&quot;%s&quot;, text) but: A) doesn&apos;t require null terminated string if &apos;text_end&apos; is specified, B) it&apos;s faster, no memory copy is done, no buffer size limits, recommended for long chunks of text.</para>
/// <para>
/// C++: <a href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui.h#L614">imgui.h:614</a>, <a href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui_widgets.cpp#L268">imgui_widgets.cpp:268</a>
/// <br/>
/// <c>void TextUnformatted(const char* text, const char* text_end = NULL)</c>
/// </para>
/// </summary>
/// <remarks>Widgets: Text</remarks>
public static void Text(ImString text)
{
unsafe
{
fixed (byte* text_fixed = text)
{
PInvoke.TextUnformatted(text_fixed, null);
}
}
}
public partial class Internal
{
/// <summary>
/// <para>
/// C++: <a href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui.h#L616">imgui.h:616</a>, <a href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui_widgets.cpp#L281">imgui_widgets.cpp:281</a>
/// <br/>
/// <c>void TextV(const char* fmt, va_list args) IM_FMTLIST(1)</c>
/// </para>
/// </summary>
/// <remarks>Uses C++/printf-style formatting: %d, %f etc.
/// <br/>C# has better options, but this could be useful for compatibility, porting C++ code etc.</remarks>
public static unsafe void TextFormatted(ImString fmt, params ReadOnlySpan<VariadicArgument> args)
{
fixed (byte* fmt_fixed = fmt)
fixed (byte* vaList_fixed = VaList.Pack(stackalloc byte[VaList.GetSize(args)], args))
PInvoke.TextV(fmt_fixed, vaList_fixed);
}
}
}

View file

@ -0,0 +1,385 @@
using System.Buffers;
using System.Runtime.InteropServices;
namespace Brutal.ImGuiApi;
/*
* NOTE: we want ImGui non-static to allow extensions -> make it abstract instead
* (static == abstract sealed, so we just don't seal it).
*
* If we want to roll back on that decision, this is the only place we should add `static`,
* (ie not in the dozens of auto-generated files).
*/
public abstract partial class ImGui
{
/// <inheritdoc cref="PInvoke.LoadIniSettingsFromMemory"/>
public static void LoadIniSettingsFromMemory(ImString iniData)
{
unsafe
{
fixed (byte* iniData_fixed = iniData)
{
PInvoke.LoadIniSettingsFromMemory(iniData_fixed, (nuint)iniData.Length);
}
}
}
/// <inheritdoc cref="PInvoke.SaveIniSettingsToMemory"/>
public static ImString SaveIniSettingsToMemory()
{
unsafe
{
nuint outIniSize;
var resultPtr = PInvoke.SaveIniSettingsToMemory(&outIniSize);
return new ReadOnlySpan<byte>(resultPtr, (int)outIniSize);
}
}
/// <inheritdoc cref="PInvoke.Combo_0"/>
public static unsafe bool Combo(
ImString label,
ref int currentItem,
ReadOnlySpan<Ptr<byte>> items,
int popupMaxHeightInItems = -1
)
{
fixed (Ptr<byte>* pointers = items)
fixed (int* currentItem_fixed = &currentItem)
fixed (byte* label_fixed = label)
{
return PInvoke.Combo_0(
label_fixed,
currentItem_fixed,
(byte**)pointers,
items.Length,
popupMaxHeightInItems
);
}
}
/// <inheritdoc cref="PInvoke.Combo_0"/>
public static unsafe bool Combo(
ImString label,
ref int currentItem,
scoped RefString8Array items,
int popupMaxHeightInItems = -1
)
{
try
{
fixed (byte* bytePtr = items)
{
fixed (int* currentItem_fixed = &currentItem)
fixed (byte* label_fixed = label)
{
return PInvoke.Combo_0(
label_fixed,
currentItem_fixed,
items.CommitFixedRegion(bytePtr),
items.Length,
popupMaxHeightInItems
);
}
}
}
finally
{
items.Dispose();
}
}
/// <inheritdoc cref="PInvoke.ListBox_0"/>
public static unsafe bool ListBox(
ImString label,
ref int currentItem,
ReadOnlySpan<Ptr<byte>> items,
int heightInItems = -1
)
{
fixed (Ptr<byte>* test = items)
fixed (int* currentItem_fixed = &currentItem)
fixed (byte* label_fixed = label)
{
return PInvoke.ListBox_0(label_fixed, currentItem_fixed, (byte**)test, items.Length, heightInItems);
}
}
/// <inheritdoc cref="PInvoke.ListBox_0"/>
public static unsafe bool ListBox(
ImString label,
ref int currentItem,
scoped RefString8Array items,
int heightInItems = -1
)
{
try
{
fixed (byte* bytePtr = items)
{
fixed (int* currentItem_fixed = &currentItem)
fixed (byte* label_fixed = label)
{
return PInvoke.ListBox_0(
label_fixed,
currentItem_fixed,
items.CommitFixedRegion(bytePtr),
items.Length,
heightInItems
);
}
}
}
finally
{
items.Dispose();
}
}
/// <inheritdoc cref="PInvoke.InputText"/>
public static unsafe bool InputText(
ImString label,
ImInputString buffer,
ImGuiInputTextFlags flags = default,
ImGuiInputTextCallback? callback = null,
nint userData = 0
)
{
fixed (byte* buffer_fixed = buffer.Buffer)
fixed (byte* label_fixed = label)
{
var result = PInvoke.InputText(
label_fixed,
buffer_fixed,
(nuint)buffer.Capacity,
flags,
callback is null ? 0 : Marshal.GetFunctionPointerForDelegate(callback),
(void*)userData
);
if (result)
buffer.EvaluateLength();
return result;
}
}
/// <inheritdoc cref="PInvoke.InputTextMultiline"/>
public static unsafe bool InputTextMultiline(
ImString label,
ImInputString buffer,
in float2 size = default,
ImGuiInputTextFlags flags = default,
ImGuiInputTextCallback? callback = null,
nint userData = 0
)
{
fixed (byte* buffer_fixed = buffer.Buffer)
fixed (float2* size_fixed = &size)
fixed (byte* label_fixed = label)
{
var result = PInvoke.InputTextMultiline(
label_fixed,
buffer_fixed,
(nuint)buffer.Capacity,
size_fixed,
flags,
callback is null ? 0 : Marshal.GetFunctionPointerForDelegate(callback),
(void*)userData
);
if (result)
buffer.EvaluateLength();
return result;
}
}
/// <inheritdoc cref="PInvoke.InputTextWithHint"/>
public static unsafe bool InputTextWithHint(
ImString label,
ImString hint,
ImInputString buffer,
ImGuiInputTextFlags flags = default,
ImGuiInputTextCallback? callback = null,
nint userData = 0
)
{
fixed (byte* buffer_fixed = buffer.Buffer)
fixed (byte* hint_fixed = hint)
fixed (byte* label_fixed = label)
{
var result = PInvoke.InputTextWithHint(
label_fixed,
hint_fixed,
buffer_fixed,
(nuint)buffer.Capacity,
flags,
callback is null ? 0 : Marshal.GetFunctionPointerForDelegate(callback),
(void*)userData
);
if (result)
buffer.EvaluateLength();
return result;
}
}
/// <inheritdoc cref="PInvoke.GetAllocatorFunctions"/>
public static unsafe void GetAllocatorFunctions(
out ImGuiMemAllocFunc? pAllocFunc,
out ImGuiMemFreeFunc? pFreeFunc,
out nint pUserData
)
{
nint pAllocFunc_value = 0;
nint pFreeFunc_value = 0;
fixed (nint* pUserData_ptr = &pUserData)
{
PInvoke.GetAllocatorFunctions(&pAllocFunc_value, &pFreeFunc_value, (void**)pUserData_ptr);
}
pAllocFunc = pAllocFunc_value is 0
? null
: Marshal.GetDelegateForFunctionPointer<ImGuiMemAllocFunc>(pAllocFunc_value);
pFreeFunc = pFreeFunc_value is 0
? null
: Marshal.GetDelegateForFunctionPointer<ImGuiMemFreeFunc>(pFreeFunc_value);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate byte* ComboGetter(nint userData, int idx);
/// <inheritdoc cref="PInvoke.Combo_2" />
public static bool Combo(
ImString label,
ref int currentItem,
ComboGetter getter,
nint userData,
int itemsCount,
int popupMaxHeightInItems = -1
)
{
unsafe
{
fixed (int* currentItem_fixed = &currentItem)
fixed (byte* label_fixed = label)
{
return PInvoke.Combo_2(
label_fixed,
currentItem_fixed,
Marshal.GetFunctionPointerForDelegate(getter),
(void*)userData,
itemsCount,
popupMaxHeightInItems
);
}
}
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate byte* ListBoxGetter(nint userData, int idx);
/// <inheritdoc cref="PInvoke.ListBox_1" />
public static bool ListBox(
ImString label,
ref int currentItem,
ListBoxGetter getter,
nint userData,
int itemsCount,
int heightInItems = -1
)
{
unsafe
{
fixed (int* currentItem_fixed = &currentItem)
fixed (byte* label_fixed = label)
{
return PInvoke.ListBox_1(
label_fixed,
currentItem_fixed,
Marshal.GetFunctionPointerForDelegate(getter),
(void*)userData,
itemsCount,
heightInItems
);
}
}
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate float PlotLinesValuesGetter(nint data, int idx);
/// <inheritdoc cref="PInvoke.PlotLines_1" />
public static void PlotLines(
ImString label,
PlotLinesValuesGetter valuesGetter,
nint data,
int valuesCount,
int valuesOffset = 0,
ImString overlayText = default,
float scaleMin = float.MaxValue,
float scaleMax = float.MaxValue,
float2? graphSize = default
)
{
unsafe
{
var graphSize_default = graphSize ?? new float2(0f, 0f);
fixed (byte* overlayText_fixed = overlayText)
fixed (byte* label_fixed = label)
{
PInvoke.PlotLines_1(
label_fixed,
Marshal.GetFunctionPointerForDelegate(valuesGetter),
(void*)data,
valuesCount,
valuesOffset,
overlayText_fixed,
scaleMin,
scaleMax,
graphSize_default
);
}
}
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate float PlotHistogramValuesGetter(nint data, int idx);
/// <inheritdoc cref="PInvoke.PlotHistogram_1" />
public static void PlotHistogram(
ImString label,
PlotHistogramValuesGetter valuesGetter,
nint data,
int valuesCount,
int valuesOffset = 0,
ImString overlayText = default,
float scaleMin = float.MaxValue,
float scaleMax = float.MaxValue,
float2? graphSize = default
)
{
unsafe
{
var graphSize_default = graphSize ?? new float2(0f, 0f);
fixed (byte* overlayText_fixed = overlayText)
fixed (byte* label_fixed = label)
{
PInvoke.PlotHistogram_1(
label_fixed,
Marshal.GetFunctionPointerForDelegate(valuesGetter),
(void*)data,
valuesCount,
valuesOffset,
overlayText_fixed,
scaleMin,
scaleMax,
graphSize_default
);
}
}
}
}

View file

@ -0,0 +1,17 @@
namespace Brutal.ImGuiApi;
public record struct ImDrawListSharedData;
public readonly unsafe struct ImDrawListSharedDataPtr(ImDrawListSharedData* value) : INullable
{
private readonly ImDrawListSharedData* _value = value;
public bool IsNull()
{
return _value == null;
}
public static implicit operator ImDrawListSharedDataPtr(ImDrawListSharedData* value) => new(value);
public static implicit operator ImDrawListSharedData*(ImDrawListSharedDataPtr wrapper) => wrapper._value;
}

View file

@ -0,0 +1,15 @@
namespace Brutal.ImGuiApi;
public class ImException(string message) : Exception(message);
public partial class ImGui
{
/// <summary>
/// This is an equivalent of the IM_ASSERT C++ macro, intended for similar validation in ported code.
/// </summary>
public static void Assert(bool condition, string? message = null)
{
if (!condition)
throw new ImException(message ?? "Assertion failed");
}
}

View file

@ -0,0 +1,77 @@
namespace Brutal.ImGuiApi;
// TODO: byte4 converts implicitly to uint... so why not from uint as well?
/// <summary>
/// 8-bit per channel color, for interop.
/// Converts to/from uint, byte4, and float4.
/// </summary>
public struct ImColor8
{
private byte4 _value;
private ImColor8(uint value)
{
_value = Unsafe.As<uint, byte4>(ref value);
}
private ImColor8(byte4 value)
{
_value = value;
}
private ImColor8(float4 value)
{
_value = byte4.Pack(value, Pack.Float.Normalize);
}
public ImColor8(byte r, byte g, byte b, byte a = 255)
: this(new byte4(r, g, b, a)) { }
public static implicit operator ImColor8(in uint value) => new(value);
public static implicit operator ImColor8(in byte4 value) => new(value);
public static explicit operator ImColor8(in float4 value) => new(value);
public static implicit operator ImColor8(in Color.Preset value) => new(value.AsByte4);
public static implicit operator ImColor8(in ImGuiCol value) => ImGui.GetColorU32(value);
// TODO: this is just here to make PInvoke easier but I don't like it...
public static implicit operator uint(in ImColor8 value) => value._value;
//public static implicit operator byte4(in ImColor8 value) => value._value;
public readonly uint AsUint() => _value;
public readonly byte4 AsByte4() => _value;
public readonly float4 AsFloat4()
{
float4 result;
result.X = _value.X / 255f;
result.Y = _value.Y / 255f;
result.Z = _value.Z / 255f;
result.W = _value.W / 255f;
return result;
}
public ImColor8 RGBA
{
get => _value.RGBA;
set => _value.RGBA = value._value.RGBA;
}
public ImColor8 ARGB
{
get => _value.ARGB;
set => _value.ARGB = value._value.ARGB;
}
public static readonly ImColor8 Black = new(0, 0, 0);
public static readonly ImColor8 White = new(255, 255, 255);
public static readonly ImColor8 Red = new(255, 0, 0);
public static readonly ImColor8 Green = new(0, 255, 0);
public static readonly ImColor8 Blue = new(0, 0, 255);
}

View file

@ -0,0 +1,15 @@
namespace Brutal.ImGuiApi
{
public abstract partial class ImGui
{
public abstract partial class Internal : Brutal.ImGuiApi.ImGui
{
public new abstract class PInvoke : Brutal.ImGuiApi.Internal.PInvoke;
}
}
}
namespace Brutal.ImGuiApi.Internal
{
public abstract partial class PInvoke : Brutal.ImGuiApi.ImGui.PInvoke;
}

View file

@ -0,0 +1,118 @@
namespace Brutal.ImGuiApi;
/*
* These types are only forward declared in headers, defined in imgui.cpp but used in imgui_internal.h structs
*/
public enum ImGuiDockRequestType
{
None = 0,
Dock,
Undock,
Split, // Split is the same as Dock but without a DockPayload
}
[StructLayout(LayoutKind.Explicit, Size = 64)]
public struct ImGuiDockRequest()
{
[FieldOffset(0)]
public ImGuiDockRequestType Type;
[FieldOffset(8)]
public Ptr<ImGuiWindow> DockTargetWindow; // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
[FieldOffset(16)]
public Ptr<ImGuiDockNode> DockTargetNode; // Destination/Target Node to dock into
[FieldOffset(24)]
public Ptr<ImGuiWindow> DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
[FieldOffset(32)]
public ImGuiDir DockSplitDir;
[FieldOffset(36)]
public float DockSplitRatio = 0.5f;
[FieldOffset(40)]
public Bool8 DockSplitOuter;
[FieldOffset(48)]
public Ptr<ImGuiWindow> UndockTargetWindow;
[FieldOffset(56)]
public Ptr<ImGuiDockNode> UndockTargetNode;
}
[InlineArray((int)ImGuiDir.COUNT + 1)]
public struct ImGuiDockPreviewData_DockRectsDraw
{
public floatRect Value;
}
[StructLayout(LayoutKind.Explicit, Size = 312)]
public struct ImGuiDockPreviewData
{
[FieldOffset(0)]
public ImGuiDockNode FutureNode;
[FieldOffset(208)]
public Bool8 IsDropAllowed;
[FieldOffset(209)]
public Bool8 IsCenterAvailable;
[FieldOffset(210)]
public Bool8 IsSidesAvailable; // Hold your breath, grammar freaks..
[FieldOffset(211)]
public Bool8 IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
[FieldOffset(216)]
public Ptr<ImGuiDockNode> SplitNode;
[FieldOffset(224)]
public ImGuiDir SplitDir;
[FieldOffset(228)]
public float SplitRatio;
[FieldOffset(232)]
public ImGuiDockPreviewData_DockRectsDraw DropRectsDraw; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
// TODO: Init DropRectsDraw as per constructor defaults
}
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
[StructLayout(LayoutKind.Explicit, Size = 36)]
public struct ImGuiDockNodeSettings
{
[FieldOffset(0)]
public ImGuiID ID;
[FieldOffset(4)]
public ImGuiID ParentNodeId;
[FieldOffset(8)]
public ImGuiID ParentWindowId;
[FieldOffset(12)]
public ImGuiID SelectedTabId;
[FieldOffset(16)]
public sbyte SplitAxis;
[FieldOffset(17)]
public byte Depth;
[FieldOffset(20)]
public ImGuiDockNodeFlags Flags; // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
[FieldOffset(24)]
public short2 Pos;
[FieldOffset(28)]
public short2 Size;
[FieldOffset(32)]
public short2 SizeRef;
}

View file

@ -0,0 +1,226 @@
using System.Collections;
using Brutal.Memory;
namespace Brutal.ImGuiApi;
[StructLayout(LayoutKind.Sequential)]
public struct ImVector<T> : IList<T>
where T : unmanaged
{
private const int DEFAULT_CAPACITY = 8;
private int _size;
private int _capacity;
private Ptr<T> _data;
public int Count
{
get => _size;
set
{
ArgumentOutOfRangeException.ThrowIfNegative(value);
if (value == _size)
return;
EnsureCapacity(value);
if (value > _size)
{
Mem.Clear(Data.Offset(_size), ElementCount.Of(value - _size));
}
_size = value;
}
}
public int Capacity => _capacity;
public unsafe void EnsureCapacity(int capacity)
{
if (capacity <= _capacity)
return;
var newCapacity = GetGrownCapacity(capacity);
var newData = (T*)ImGui.MemAlloc((nuint)newCapacity * (nuint)Stride);
if (_data.IsNotNull())
{
Mem.Copy(_data, newData, _size);
ImGui.MemFree(_data.Pointer);
}
_data = new Ptr<T>(newData);
_capacity = newCapacity;
}
public Ptr<T> Data => _data;
public unsafe T* DataRaw => _data;
public Span<T> Span => _data.AsSpan(_size);
public T this[int i]
{
get
{
ArgumentOutOfRangeException.ThrowIfNegative(i);
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(i, _size);
return Data[i];
}
set
{
ArgumentOutOfRangeException.ThrowIfNegative(i);
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(i, _size);
Data[i] = value;
}
}
public int IndexOf(T item)
{
return Span.IndexOf(item);
}
public void Insert(int index, T item)
{
ArgumentOutOfRangeException.ThrowIfNegative(index);
ArgumentOutOfRangeException.ThrowIfGreaterThan(index, _size);
EnsureCapacity(_size + 1);
// Shift elements right to open a slot; Mem.Copy has memmove semantics, so the overlapping
// copy is safe.
if (index < _size)
Mem.Copy(Data.Offset(index), Data.Offset(index + 1), _size - index);
Data[index] = item;
_size++;
}
public void RemoveAt(int index)
{
ArgumentOutOfRangeException.ThrowIfNegative(index);
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, _size);
_size--;
if (index < _size)
{
// Shift elements left over the removed slot; Mem.Copy has memmove semantics, so the
// overlapping copy is safe.
Mem.Copy(Data.Offset(index + 1), Data.Offset(index), _size - index);
}
}
// Pattern-based GetEnumerator to enable foreach without boxing
public unsafe ImVectorEnumerator<T> GetEnumerator() => new(Data, _size);
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
unsafe
{
return new ImVectorEnumerator<T>(Data, _size);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(T item)
{
EnsureCapacity(_size + 1);
Data[_size] = item;
_size++;
}
public unsafe void Clear()
{
if (_data.IsNull())
return;
_size = _capacity = 0;
ImGui.MemFree(_data.Pointer);
_data = null;
}
/// Resets the count to zero but keeps the allocated buffer so we can re-use it without freeing/allocating
public void Reset() => _size = 0;
public bool Contains(T item)
{
return IndexOf(item) >= 0;
}
public void CopyTo(T[] array, int arrayIndex)
{
unsafe
{
fixed (T* ptr = array)
{
Mem.Copy(Data, ptr + arrayIndex, _size);
}
}
}
public bool Remove(T item)
{
var index = IndexOf(item);
if (index < 0)
return false;
RemoveAt(index);
return true;
}
public bool IsReadOnly => false;
private static unsafe int Stride => sizeof(T);
private readonly int GetGrownCapacity(int requiredCapacity)
{
var newCapacity = _capacity is 0 ? DEFAULT_CAPACITY : _capacity + _capacity / 2;
return newCapacity > requiredCapacity ? newCapacity : requiredCapacity;
}
}
public struct ImVectorEnumerator<T> : IEnumerator<T>
where T : unmanaged
{
private readonly unsafe T* _start;
private readonly int _length;
private int _index;
public unsafe ImVectorEnumerator(T* start, int length)
{
_start = start;
_length = length;
_index = -1;
}
public bool MoveNext()
{
var i = _index + 1;
if ((uint)i < (uint)_length)
{
_index = i;
return true;
}
return false;
}
public void Reset()
{
_index = -1;
}
public unsafe T Current => _start[_index];
object IEnumerator.Current => Current;
public void Dispose() { }
}

View file

@ -0,0 +1,40 @@
using System.Diagnostics;
using System.Reflection;
namespace Brutal.ImGuiApi
{
public static class Interop
{
/// <summary>
/// A function that sets up a trampoline for our functions that take an ImGuiViewportPtr and return an ImVec2 so
/// that interop works. Without this things don't work because C++ and C# think different things about ImVec2
/// and how it can be returned over interop. C++ expects the return type on the stack but C# puts it in a register.
/// </summary>
/// <remarks>The function looks for a native function pointer variable and sets it to the value of managedFunction.
/// It then requests the function pointer for the shim function and returns it, so that can be passed to ImGui as
/// a callback. This shim function calls the managed function that returns a POD type, and converts it to the
/// non-pod type that C++ expects to be returned.</remarks>
/// <param name="managedFunction">Address of the function that is your normal C# callback</param>
/// <param name="functionName">The name of the function that you are hooking. e.g. "GetWindowPos"</param>
/// <returns>Pointer to the c++ shim function.</returns>
public static unsafe nint CreateTrampoline(
delegate* unmanaged[Cdecl]<ImGuiViewportPtr, float2> managedFunction,
string functionName
)
{
Debug.Assert(sizeof(delegate* unmanaged[Cdecl]<ImGuiViewportPtr, float2>) == sizeof(IntPtr));
var imguiLibrary = NativeLibrary.Load(LibraryName, Assembly.GetExecutingAssembly(), null);
var pointerToManagedFunctionPointer = (delegate* unmanaged[Cdecl]<ImGuiViewportPtr, float2>*)
NativeLibrary.GetExport(imguiLibrary, $"Platform_{functionName}_ManagedFunctionPointer");
*pointerToManagedFunctionPointer = managedFunction;
var getShimFunctionPointer = (delegate* unmanaged[Cdecl]<nint>)
NativeLibrary.GetExport(imguiLibrary, $"Get_{functionName}_InteropPointer");
return getShimFunctionPointer();
}
private const string LibraryName = "imgui";
}
}

View file

@ -0,0 +1,23 @@
namespace Brutal.ImGuiApi;
public partial struct ImDrawCmd
{
/// <inheritdoc cref="ImDrawCmdExtensions.GetTexID(ImDrawCmdPtr)"/>
/// <remarks>
/// Port of definition in imgui.h for backend use on underlying struct
/// </remarks>
public unsafe ImTextureID GetTexID()
{
if (TexRef._TexData.IsNotNull())
{
var texId = TexRef._TexData.TexID;
ImGui.Assert(
texId != ImTextureID.Invalid,
"ImDrawCmd is referring to ImTextureData that wasn't uploaded to graphics system. Backend must call ImTextureData::SetTexID() after handling ImTextureStatus_WantCreate request!"
);
return texId;
}
return TexRef._TexID;
}
}

View file

@ -0,0 +1,12 @@
using System.Runtime.InteropServices;
namespace Brutal.ImGuiApi;
public partial struct ImGuiPlatformIO
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate byte* GetClipboardTextFnDelegate(ImGuiContextPtr ctx);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate void SetClipboardTextFnDelegate(ImGuiContextPtr ctx, byte* text);
}

View file

@ -0,0 +1,23 @@
namespace Brutal.ImGuiApi;
public partial struct ImGuiTextFilter
{
private static int InputBufSize => 256;
public unsafe ImGuiTextFilter(ImString defaultFilter = default)
: this()
{
if (!defaultFilter.IsNull())
{
fixed (byte* inputBufPtr = InputBuf)
{
var target = new Span<byte>(inputBufPtr, InputBufSize);
var source = defaultFilter.AsSpan();
if (source.Length > InputBufSize)
source = source[..InputBufSize];
source.CopyTo(target);
this.Build();
}
}
}
}

View file

@ -0,0 +1,49 @@
namespace Brutal.ImGuiApi;
[InlineArray(2)]
public struct ImDrawDataBuilderLayers
{
public Ptr<ImVector<ImDrawListPtr>> Value;
}
/// <summary>Helper to build a ImDrawData instance</summary>
/// <remarks>ImDrawList/ImFontAtlas</remarks>
/// <source href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui_internal.h#L142"><a href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui_internal.h#L142">imgui_internal.h:142</a></source>
/// <br/>
/// <declaration><c>struct ImDrawDataBuilder</c></declaration>
[StructLayout(LayoutKind.Explicit, Size = 32)]
public partial struct ImDrawDataBuilder()
{
/// <summary>Pointers to global layers for: regular, tooltip. LayersP[0] is owned by DrawData.</summary>
/// <source href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui_internal.h#L877"><a href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui_internal.h#L877">imgui_internal.h:877</a></source>
/// <br/>
/// <declaration><c>ImVector&lt;ImDrawList*&gt;* Layers[2]</c></declaration>
[FieldOffset(0)]
public ImDrawDataBuilderLayers Layers;
/// <summary/>
/// <source href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui_internal.h#L878"><a href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui_internal.h#L878">imgui_internal.h:878</a></source>
/// <br/>
/// <declaration><c>ImVector&lt;ImDrawList*&gt; LayerData1</c></declaration>
[FieldOffset(16)]
public ImVector<ImDrawListPtr> LayerData1;
}
/// <inheritdoc cref="ImDrawDataBuilder"/>
public unsafe partial struct ImDrawDataBuilderPtr(ImDrawDataBuilder* ptr) : INullable
{
private ImDrawDataBuilder* _ptr = ptr;
public ImDrawDataBuilder* Ptr => _ptr;
public bool IsNull() => _ptr is null;
public static implicit operator ImDrawDataBuilderPtr(ImDrawDataBuilder* ptr) => new(ptr);
public static implicit operator ImDrawDataBuilder*(ImDrawDataBuilderPtr wrapper) => wrapper.Ptr;
/// <inheritdoc cref="ImDrawDataBuilder.Layers"/>
public ref ImDrawDataBuilderLayers Layers => ref Unsafe.AsRef<ImDrawDataBuilderLayers>(&_ptr->Layers);
/// <inheritdoc cref="ImDrawDataBuilder.LayerData1"/>
public ref ImVector<ImDrawListPtr> LayerData1 => ref Unsafe.AsRef<ImVector<ImDrawListPtr>>(&_ptr->LayerData1);
}

View file

@ -0,0 +1,7 @@
namespace Brutal.ImGuiApi;
public partial struct ImGuiListClipper : IDisposable
{
/// <inheritdoc cref="ImGuiListClipperExtensions.End"/>
public void Dispose() => this.End();
}

View file

@ -0,0 +1,27 @@
namespace Brutal.ImGuiApi;
/// <summary>Helper: Execute a block of code at maximum once a frame. </summary>
/// <remarks>
/// Convenient if you want to quickly create a UI within deep-nested code that runs multiple times every frame.<br/>
/// Usage: static ImGuiOnceUponAFrame oaf = new(); if (oaf) ImGui.Text("This will be called only once per frame");
/// </remarks>
/// <source href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui.h#L194"><a href="https://github.com/ocornut/imgui/blob/v1.92.2-docking/imgui.h#L194">imgui.h:194</a></source>
/// <br/>
/// <declaration><c>struct ImGuiOnceUponAFrame</c></declaration>
// A class, not a struct, so the implicit bool operator mutates the shared instance's _refFrame.
public class ImGuiOnceUponAFrame
{
private int _refFrame = -1;
public static implicit operator bool(ImGuiOnceUponAFrame value)
{
var currentFrame = ImGui.GetFrameCount();
if (value._refFrame == currentFrame)
return false;
value._refFrame = currentFrame;
return true;
}
}

View file

@ -0,0 +1,22 @@
using System.Runtime.InteropServices;
namespace Brutal.ImGuiApi;
public partial struct ImGuiTextFilter
{
[StructLayout(LayoutKind.Explicit, Size = 16)]
public unsafe struct ImGuiTextRange
{
[FieldOffset(0)]
public byte* B;
[FieldOffset(8)]
public byte* E;
public ImGuiTextRange(ReadOnlySpan<byte> range)
{
B = range.AsPointer();
E = B + range.Length;
}
}
}

View file

@ -0,0 +1,6 @@
namespace Brutal.ImGuiApi;
public record struct ImFontAtlasRectId(int Value)
{
public static readonly ImFontAtlasRectId Invalid = new(-1);
}

View file

@ -0,0 +1,12 @@
namespace Brutal.ImGuiApi;
public record struct ImGuiID(uint Value)
{
public static implicit operator ImGuiID(uint value) => new(value);
public static implicit operator ImGuiID(int value) => new((uint)value);
public static implicit operator uint(ImGuiID value) => value.Value;
public static implicit operator int(ImGuiID value) => (int)value.Value;
}

View file

@ -0,0 +1,7 @@
namespace Brutal.ImGuiApi;
// Just a wrapper for ImGuiKey values, in the expectation that it will be a combination of Mod flags and a key value.
public record struct ImGuiKeyChord(ImGuiKey Flags)
{
public static implicit operator ImGuiKeyChord(ImGuiKey key) => new(key);
}

Some files were not shown because too many files have changed in this diff Show more