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

View file

@ -0,0 +1,60 @@
// Context reference
// https://www.glfw.org/docs/latest/group__context.html
// Hand-written members of the Context library. GetCurrentContext and GetProcAddress are in the
// generator's ManualMethods set (no P/Invoke is generated for them - see Manual/Glfw.PInvoke.cs),
// so they cannot be generated and live here. The rest of the Context library is generated into
// Generated/Libraries/Glfw.Context.gen.cs and merges into this same partial class.
namespace Brutal.GlfwApi;
public static unsafe partial class Glfw
{
/// <summary>Returns the window whose context is current on the calling thread.</summary>
/// <remarks>
/// This function returns the window whose OpenGL or OpenGL ES context is current on the calling thread.
/// </remarks>
/// <returns>The window whose context is current, or <c>null</c> if no window's context is current.</returns>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />
/// </possibleErrors>
/// <threadSafety>This function may be called from any thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/context_guide.html#context_current">Current context</seealso>
public static nint GetCurrentContext()
{
return (nint)PInvoke.GetCurrentContext();
}
/// <summary>Returns the address of the specified function for the current context.</summary>
/// <remarks>
/// This function returns the address of the specified OpenGL or OpenGL ES core or extension function, if it is
/// supported by the current context.
/// <para />
/// A context must be current on the calling thread. Calling this function without a current context will cause a
/// <see cref="GlfwErrorCode.NoCurrentContext" /> error.
/// <para />
/// This function does not apply to Vulkan. If you are rendering with Vulkan, see
/// <see cref="GetInstanceProcAddress">GetInstanceProcAddress</see>,
/// <see cref="InstanceLibrary.GetProcAddr">InstanceLibrary.GetProcAddr</see> and
/// <see cref="DeviceLibrary.GetProcAddr">DeviceLibrary.GetProcAddr</see> instead.
/// <para />
/// The address of a given function is not guaranteed to be the same between contexts.
/// <para />
/// This function may return a non-null address despite the associated version or extension not being available.
/// Always check the context version or extension string first.
/// </remarks>
/// <returns>The address of the function, or <c>null</c> if an error occurred.</returns>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />,
/// <see cref="GlfwErrorCode.NoCurrentContext" />,
/// <see cref="GlfwErrorCode.PlatformError" />
/// </possibleErrors>
/// <pointerLifetime>The returned function pointer is valid until the context is destroyed or the library is terminated.</pointerLifetime>
/// <threadSafety>This function may be called from any thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/context_guide.html#context_glext">OpenGL and OpenGL ES extensions</seealso>
public static nint GetProcAddress(ReadOnlySpan<byte> procName)
{
fixed (byte* pProcName = procName)
return PInvoke.GetProcAddress(pProcName);
}
}

View file

@ -0,0 +1,120 @@
using System.Runtime.InteropServices.Marshalling;
// Hand-written members of the Cursor library: the GlfwCursor handle type, its custom marshaller,
// and the custom-image CreateCursor factory (which bundles a CreateInfo struct and fixed-pins the
// image - not mechanically derivable). The standard-shape CreateCursor overload is generated into
// Generated/Libraries/Glfw.Cursor.gen.cs and merges into this same partial class.
namespace Brutal.GlfwApi;
public static unsafe partial class Glfw
{
/// <summary>Creates a custom cursor.</summary>
/// <remarks>
/// Creates a new custom cursor image that can be set for a window with <see cref="GlfwWindow.SetCursor">GlfwWindow.SetCursor</see>
/// . The cursor can be destroyed with <see cref="GlfwCursor.Dispose">GlfwCursor.Dispose</see>. Any remaining cursors are destroyed by
/// <see cref="Terminate" />.
/// <para />
/// The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight bits per channel with the red channel
/// first. They are arranged canonically as packed sequential rows, starting from the top-left corner.
/// <para />
/// The cursor hotspot is specified in pixels, relative to the upper-left corner of the cursor image. Like all other
/// coordinate systems in GLFW, the X-axis points to the right and the Y-axis points down.
/// </remarks>
/// <returns>The handle of the new cursor, or <c>null</c> if an error occurred.</returns>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso cref="GlfwCursor.Dispose">GlfwCursor.Dispose</seealso>
/// <seealso cref="CreateCursor(GlfwStandardCursor)" />
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#cursor_object">Cursor objects</seealso>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />
/// <see cref="GlfwErrorCode.InvalidValue" />
/// <see cref="GlfwErrorCode.PlatformError" />
/// </possibleErrors>
public static GlfwCursor CreateCursor(in GlfwCursor.CreateInfo info)
{
fixed (GlfwImage* imagePtr = &info.Image)
{
return PInvoke.CreateCursor(imagePtr, info.Hot.X, info.Hot.Y);
}
}
}
/// <summary>
/// Wrapper around a <see cref="GlfwCursorHandle" />*
/// </summary>
[NativeMarshalling(typeof(GlfwCursorMarshaller))]
public unsafe struct GlfwCursor : IDisposable, INullable
{
/// <summary>
/// Information required to create a custom cursor.
/// </summary>
public struct CreateInfo
{
/// <summary>
/// The image to use for the cursor.
/// </summary>
public GlfwImage Image;
/// <summary>
/// The position of the cursor hotspot, relative to the upper-left corner of the image.
/// </summary>
public int2 Hot;
}
internal GlfwCursor(GlfwCursorHandle* inPointer)
{
Pointer = inPointer;
}
internal GlfwCursorHandle* Pointer { get; private set; }
/// <summary>
/// Gets the native Glfw handle for this cursor
/// </summary>
public nint NativeHandle => (nint)Pointer;
/// <summary>Destroys a cursor.</summary>
/// <remarks>
/// This function destroys a cursor previously created with <see cref="Glfw.CreateCursor(in Brutal.GlfwApi.GlfwCursor.CreateInfo)" /> or
/// <see cref="Glfw.CreateCursor(GlfwStandardCursor)" />. Any remaining cursors are destroyed by <see cref="Glfw.Terminate" />.
/// <para />
/// If the specified cursor is current for any window, that window will be reverted to the default cursor. This does
/// not affect the cursor mode.
/// </remarks>
/// <reentrancy>This function must not be called from a callback.</reentrancy>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso cref="Glfw.CreateCursor(in Brutal.GlfwApi.GlfwCursor.CreateInfo)" />
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#cursor_object">Cursor objects</seealso>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />
/// <see cref="GlfwErrorCode.PlatformError" />
/// </possibleErrors>
public void Dispose()
{
if (Pointer != null)
{
Glfw.PInvoke.DestroyCursor(this);
Pointer = null;
}
}
/// <summary>Returns whether this cursor handle is null (uninitialised or already destroyed).</summary>
/// <returns><c>true</c> if the underlying native handle is null; otherwise <c>false</c>.</returns>
public bool IsNull()
{
return Pointer == null;
}
}
[CustomMarshaller(
managedType: typeof(GlfwCursor),
marshalMode: MarshalMode.Default,
marshallerType: typeof(GlfwCursorMarshaller)
)]
internal static unsafe class GlfwCursorMarshaller
{
internal static GlfwCursorHandle* ConvertToUnmanaged(GlfwCursor managed) => managed.Pointer;
internal static GlfwCursor ConvertToManaged(GlfwCursorHandle* unmanaged) => new(unmanaged);
}

View file

@ -0,0 +1,264 @@
// Initialization, version and error reference
// https://www.glfw.org/docs/latest/group__init.html
// Hand-written members of the Initialization library: the static constructor (native library load,
// DllImportResolver, callback closure wiring), the Initialized state, the error callback wiring,
// Init/Terminate (guarded lifecycle), InitAllocator (delegate rooting), and the version accessors
// (VersionInfo struct packing + property forms). The mechanical SetInitHint and GetError wrappers
// are generated into Generated/Libraries/Glfw.Initialization.gen.cs and merge into this same
// partial class.
using System.Diagnostics;
namespace Brutal.GlfwApi;
/// <summary>The function pointer type for error callbacks.</summary>
public delegate void GlfwErrorCallback(GlfwErrorCode inError, string inDescription);
public static unsafe partial class Glfw
{
internal static bool Initialized { get; private set; }
// GLFW holds the function pointers marshalled from these delegates for the lifetime of the
// process, so the delegates must stay rooted or the pointers dangle. A static strong
// reference is sufficient for that: the three permanent callbacks live in static readonly
// fields, and allocator callbacks are appended to AllocatorCallbacks. Entries are never
// removed from the list: an allocator installed while the library is initialized keeps
// servicing that init cycle until Terminate, so dropping the previous set on replacement
// would reintroduce the dangling-pointer bug the list exists to prevent. Installing an
// allocator is a once-per-process event in practice, so the retained set stays bounded.
private static readonly GlfwMonitorUnmanagedCallback MonitorUnmanagedCallback;
private static readonly GlfwJoystickUnmanagedCallback JoystickUnmanagedCallback;
private static readonly GlfwErrorUnmanagedCallback ErrorUnmanagedCallback;
private static readonly List<Delegate> AllocatorCallbacks = [];
static Glfw()
{
// Load the GLFW native library
var glfwNative = NativeLibrary.Load(
OperatingSystem.IsWindows() ? "glfw3" : "glfw",
typeof(Glfw).Assembly,
DllImportSearchPath.AssemblyDirectory
);
// Assign the native library to the assembly resolver
NativeLibrary.SetDllImportResolver(
typeof(Glfw).Assembly,
(libraryName, _, _) =>
{
// We should only be resolving the GLFW library, any other name is unexpected
Debug.Assert(libraryName == "glfw", "Unexpected library name requested for resolution.");
return glfwNative;
}
);
MonitorUnmanagedCallback = (GlfwMonitorUnmanagedCallback)(
(monitor, eventType) =>
{
try
{
MonitorCallback?.Invoke(new GlfwMonitor(monitor), (GlfwMonitorEvent)eventType);
}
catch (Exception ex)
{
ExceptionAggregator.Push("An exception occurred in the monitor callback.", ex);
}
}
);
JoystickUnmanagedCallback = (GlfwJoystickUnmanagedCallback)(
(joystick, eventType) =>
{
try
{
JoystickCallback?.Invoke(joystick, (GlfwJoystickEvent)eventType);
}
catch (Exception ex)
{
ExceptionAggregator.Push("An exception occurred in the joystick callback.", ex);
}
}
);
ErrorUnmanagedCallback = (GlfwErrorUnmanagedCallback)(
(error, description) =>
{
try
{
if (ErrorCallback != null)
{
var desc = Marshal.PtrToStringUTF8((nint)description) ?? string.Empty;
ErrorCallback.Invoke((GlfwErrorCode)error, desc);
}
}
catch (Exception ex)
{
ExceptionAggregator.Push("An exception occurred in the error callback.", ex);
}
}
);
PInvoke.SetErrorCallback(ErrorUnmanagedCallback);
}
/// <summary>Sets the error callback.</summary>
/// <remarks>
/// This function sets the error callback, which is called with an error code and a human-readable description
/// each time a GLFW error occurs.
/// <para />
/// The error code is set before the callback is called. Calling <see cref="GetError" /> from the error
/// callback will return the same value as the error code argument.
/// <para />
/// The error callback is called on the thread where the error occurred. If you are using GLFW from multiple
/// threads, your error callback needs to be written accordingly.
/// <para />
/// Once set, the error callback remains set even after the library has been terminated.
/// <para />
/// This function may be called before <see cref="Init" />.
/// </remarks>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/intro_guide.html#error_handling">Error handling</seealso>
public static event GlfwErrorCallback? ErrorCallback;
/// <summary>Sets the init allocator to the desired value.</summary>
/// <remarks>
/// This function sets the memory allocator that GLFW uses for all internal allocations. The allocator is picked
/// up at the beginning of initialization, i.e. by the next call to <see cref="Init" />, and stays in use until
/// that init cycle is ended by <see cref="Terminate" />.
/// <para />
/// GLFW copies the callback pointers before this function returns; the wrapper keeps the managed delegates
/// rooted for the remaining lifetime of the process, so the caller does not need to hold references to them.
/// <para />
/// This function may be called before <see cref="Init" />.
/// </remarks>
/// <param name="allocate">The memory allocation callback. Must return a valid pointer or <c>null</c> to signal failure.</param>
/// <param name="reallocate">The memory reallocation callback.</param>
/// <param name="deallocate">The memory deallocation callback.</param>
/// <param name="user">An opaque pointer passed back to every callback invocation.</param>
/// <exception cref="ArgumentNullException">Any of the three callbacks is <c>null</c>.</exception>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/intro_guide.html#init_allocator">Custom heap memory allocator</seealso>
public static void InitAllocator(
GlfwAllocateUnmanagedCallback allocate,
GlfwReallocateUnmanagedCallback reallocate,
GlfwDeallocateUnmanagedCallback deallocate,
void* user = null
)
{
ArgumentNullException.ThrowIfNull(allocate);
ArgumentNullException.ThrowIfNull(reallocate);
ArgumentNullException.ThrowIfNull(deallocate);
AllocatorCallbacks.Add(allocate);
AllocatorCallbacks.Add(reallocate);
AllocatorCallbacks.Add(deallocate);
var allocator = new GlfwAllocator
{
AllocateCallback = Marshal.GetFunctionPointerForDelegate(allocate),
ReallocateCallback = Marshal.GetFunctionPointerForDelegate(reallocate),
DeallocateCallback = Marshal.GetFunctionPointerForDelegate(deallocate),
User = user,
};
PInvoke.InitAllocator(&allocator);
}
/// <summary>Initializes the GLFW library.</summary>
/// <remarks>
/// This function initializes the GLFW library. Before most GLFW functions can be used, GLFW must be initialized,
/// and before an application terminates GLFW should be terminated in order to free any resources allocated during
/// or after initialization.
/// <para />
/// If this function fails, it calls <see cref="Terminate" /> before returning. If it succeeds, you should call
/// <see cref="Terminate" /> before the application exits.
/// <para />
/// Additional calls to this function after successful initialization but before termination will return
/// <c>true</c> immediately.
/// </remarks>
/// <returns><c>true</c> if successful, or <c>false</c> if an error occurred.</returns>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.PlatformError" />
/// </possibleErrors>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/intro_guide.html#intro_init">Initialization and termination</seealso>
public static bool Init()
{
if (Initialized)
return true;
Initialized = PInvoke.Init() == Constants.GLFW_TRUE;
if (Initialized)
{
PInvoke.SetMonitorCallback(MonitorUnmanagedCallback);
PInvoke.SetJoystickCallback(JoystickUnmanagedCallback);
}
return Initialized;
}
/// <summary>Terminates the GLFW library.</summary>
/// <remarks>
/// This function destroys all remaining windows and cursors, restores any modified gamma ramps and frees any
/// other allocated resources. Once this function is called, you must again call <see cref="Init" /> successfully
/// before you will be able to use most GLFW functions.
/// <para />
/// If GLFW has been successfully initialized, this function should be called before the application exits.
/// If initialization fails, there is no need to call this function, as it is called by <see cref="Init" /> before
/// it returns failure
/// <para />
/// This function has no effect if GLFW is not initialized.
/// </remarks>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.PlatformError" />
/// </possibleErrors>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/intro_guide.html#intro_init">Initialization and termination</seealso>
public static void Terminate()
{
if (Initialized)
{
PInvoke.Terminate();
Initialized = false;
}
}
public struct VersionInfo
{
public int Major;
public int Minor;
public int Revision;
}
/// <summary>Retrieves the version of the GLFW library.</summary>
/// <remarks>
/// This function retrieves the major, minor and revision numbers of the GLFW library. It is intended for when you
/// are using GLFW as a shared library and want to ensure that you are using the minimum required version.
/// <para />
/// This function may be called before <see cref="Init" />
/// </remarks>
/// <returns>Major, Minor, Revision.</returns>
/// <seealso href="https://www.glfw.org/docs/latest/intro_guide.html#intro_version">Version management</seealso>
/// <threadSafety>This function may be called from any thread.</threadSafety>
public static VersionInfo Version
{
get
{
PInvoke.GetVersion(out var major, out var minor, out var rev);
return new VersionInfo
{
Major = major,
Minor = minor,
Revision = rev,
};
}
}
/// <summary>Returns a string describing the compile-time configuration.</summary>
/// <threadSafety>This function may be called from any thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/intro_guide.html#intro_version">Version management</seealso>
// glfwGetVersionString always returns a valid static string, so the null-preserving marshaller's
// nullable return can be safely forgiven here.
public static string VersionString => PInvoke.GetVersionString()!;
}

View file

@ -0,0 +1,239 @@
// Input reference
// https://www.glfw.org/docs/latest/group__input.html
// Hand-written members of the Input library: the managed callback delegate types, the
// JoystickCallback event, GetJoystickHats (ptr+count -> ReadOnlySpan with a Span.Cast to enum,
// not yet a generator transform), the clipboard accessors (glfwGet/SetClipboardString are in
// ManualMethods and hardcode a null window), and the Time property (Get/Set pairing -> property,
// not yet a generator transform). The mechanical wrappers - including the non-cast span returns
// GetJoystickAxes/GetJoystickButtons - are generated into Generated/Libraries/Glfw.Input.gen.cs
// and merge into this same partial class.
namespace Brutal.GlfwApi;
/// <summary>The function pointer type for mouse button callbacks.</summary>
/// <seealso cref="GlfwWindow.OnMouseButton">GlfwWindow.OnMouseButton</seealso>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#input_mouse_button">Mouse button input</seealso>
/// <param name="window">The window that received the event.</param>
/// <param name="button">The mouse button that was pressed or released.</param>
/// <param name="action">One of <see cref="GlfwButtonAction.Press" /> or <see cref="GlfwButtonAction.Release" />.</param>
/// <param name="mods">Bit field describing which modifier keys were held down.</param>
public delegate void GlfwMouseButtonCallback(
GlfwWindow window,
GlfwMouseButton button,
GlfwButtonAction action,
GlfwModifier mods
);
/// <summary>The function pointer type for cursor position callbacks.</summary>
/// <seealso cref="GlfwWindow.OnCursorPos">GlfwWindow.OnCursorPos</seealso>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#cursor_pos">Cursor position</seealso>
/// <param name="window">The window that received the event.</param>
/// <param name="pos">The new cursor coordinates, relative to the left edge of the content area.</param>
public delegate void GlfwCursorPosCallback(GlfwWindow window, double2 pos);
/// <summary>The function pointer type for cursor enter/leave callbacks.</summary>
/// <seealso cref="GlfwWindow.OnCursorEnter">GlfwWindow.OnCursorEnter</seealso>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#cursor_enter">Cursor enter/leave events</seealso>
/// <param name="window">The window that received the event.</param>
/// <param name="entered">
/// <see cref="Glfw.Constants.GLFW_TRUE" /> if the cursor entered the window's content area, or
/// <see cref="Glfw.Constants.GLFW_FALSE" /> if it left it.
/// </param>
public delegate void GlfwCursorEnterCallback(GlfwWindow window, bool entered);
/// <summary>The function pointer type for scroll callbacks.</summary>
/// <seealso cref="GlfwWindow.OnScroll">GlfwWindow.OnScroll</seealso>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#scrolling">Scroll input</seealso>
/// <param name="window">The window that received the event.</param>
/// <param name="offset">The scroll offset.</param>
public delegate void GlfwScrollCallback(GlfwWindow window, double2 offset);
/// <summary>The function pointer type for scroll detail callbacks.</summary>
/// <seealso cref="GlfwWindow.OnScrollDetail">GlfwWindow.OnScrollDetail</seealso>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#scrolling">Scroll input</seealso>
/// <param name="window">The window that received the event.</param>
/// <param name="offset">The scroll offset, zero when the event only marks a gesture boundary.</param>
/// <param name="flags">Where the offset came from and which gesture phase it belongs to.</param>
public delegate void GlfwScrollDetailCallback(GlfwWindow window, double2 offset, GlfwScrollFlags flags);
/// <summary>The function pointer type for trackpad zoom callbacks.</summary>
/// <seealso cref="GlfwWindow.OnTrackpadZoom">GlfwWindow.OnTrackpadZoom</seealso>
/// <param name="window">The window that received the event.</param>
/// <param name="scale">The zoom since the previous event, as a factor to multiply the current scale by.</param>
public delegate void GlfwTrackpadZoomCallback(GlfwWindow window, double scale);
/// <summary>The function pointer type for trackpad rotate callbacks.</summary>
/// <seealso cref="GlfwWindow.OnTrackpadRotate">GlfwWindow.OnTrackpadRotate</seealso>
/// <param name="window">The window that received the event.</param>
/// <param name="angle">The rotation since the previous event, in degrees, positive counter-clockwise.</param>
public delegate void GlfwTrackpadRotateCallback(GlfwWindow window, double angle);
/// <summary>The function pointer type for keyboard key callbacks.</summary>
/// <seealso cref="GlfwWindow.OnKey">GlfwWindow.OnKey</seealso>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#input_key">Key input</seealso>
/// <param name="window">The window that received the event.</param>
/// <param name="key">The keyboard key that was pressed or released.</param>
/// <param name="scancode">The system-specific scancode of the key.</param>
/// <param name="action">
/// <see cref="GlfwKeyAction.Press" />, <see cref="GlfwKeyAction.Release" /> or
/// <see cref="GlfwKeyAction.Repeat" />. Future releases may add more actions.
/// </param>
/// <param name="mods">Bit field describing which modifier keys were held down.</param>
public delegate void GlfwKeyCallback(
GlfwWindow window,
GlfwKey key,
int scancode,
GlfwKeyAction action,
GlfwModifier mods
);
/// <summary>The function pointer type for Unicode character callbacks.</summary>
/// <seealso cref="GlfwWindow.OnChar">GlfwWindow.OnChar</seealso>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#input_char">Text input</seealso>
/// <param name="window">The window that received the event.</param>
/// <param name="codepoint">The Unicode code point of the character.</param>
public delegate void GlfwCharCallback(GlfwWindow window, uint codepoint);
/// <summary>The function pointer type for Unicode character with modifiers callbacks.</summary>
/// <seealso cref="GlfwWindow.OnCharMods">GlfwWindow.OnCharMods</seealso>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#input_char">Text input</seealso>
/// <param name="window">The window that received the event.</param>
/// <param name="codepoint">The Unicode code point of the character.</param>
/// <param name="mods">Bit field describing which modifier keys were held down.</param>
public delegate void GlfwCharModsCallback(GlfwWindow window, uint codepoint, GlfwModifier mods);
/// <summary>The function pointer type for path drop callbacks.</summary>
/// <seealso cref="GlfwWindow.OnDrop">GlfwWindow.OnDrop</seealso>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#path_drop">Path drop input</seealso>
/// <param name="window">The window that received the event.</param>
/// <param name="count">The number of dropped paths.</param>
/// <param name="paths">An array of UTF-8 encoded file and directory path names.</param>
public delegate void GlfwDropCallback(GlfwWindow window, int count, string[] paths);
/// <summary>The function pointer type for joystick configuration callbacks.</summary>
/// <seealso cref="Glfw.JoystickCallback">Glfw.JoystickCallback</seealso>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#joystick_event">Joystick configuration changes</seealso>
/// <param name="inJoystickId">The joystick that was connected or disconnected.</param>
/// <param name="inEvent">
/// One of <see cref="GlfwJoystickEvent.Connected" /> or
/// <see cref="GlfwJoystickEvent.Disconnected" />. Future releases may add more events.
/// </param>
public delegate void GlfwJoystickCallback(int inJoystickId, GlfwJoystickEvent inEvent);
public static unsafe partial class Glfw
{
/// <summary>Sets the joystick configuration callback.</summary>
/// <remarks>
/// This function sets the joystick configuration callback, or removes the currently set callback. This is called when
/// a joystick is connected to or disconnected from the system.
/// <para />
/// For joystick connection and disconnection events to be delivered on all platforms, you need to call one of the
/// <see href="https://www.glfw.org/docs/latest/input_guide.html#events">event processing functions</see>. Joystick
/// disconnection may also be detected and the callback called by joystick functions. The function will then return
/// whatever it returns if the joystick is not present.
/// </remarks>
/// <returns>The previously set callback, or <c>null</c> if no callback was set or the library had not been initialized.</returns>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#joystick_event">Joystick configuration changes</seealso>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />
/// </possibleErrors>
public static event GlfwJoystickCallback? JoystickCallback;
/// <summary>Returns the state of all hats of the specified joystick.</summary>
/// <remarks>
/// This function returns the state of all hats of the specified joystick.
/// <para />
/// The diagonal directions are bitwise combinations of the primary (up, right, down and left) directions and you can
/// test for these individually by ANDing it with the corresponding direction.
/// <para />
/// If the specified joystick is not present this function will return <c>null</c> but will not generate an error. This
/// can be used instead of first calling <see cref="JoystickPresent(int)">Glfw.JoystickPresent</see>.
/// </remarks>
/// <param name="joystickId">The joystick ID to query.</param>
/// <returns>An array of hat states, or <c>null</c> if the joystick is not present or an error occurred.</returns>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#joystick_hat">Joystick hat states</seealso>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />
/// <see cref="GlfwErrorCode.InvalidEnum" />
/// <see cref="GlfwErrorCode.PlatformError" />
/// </possibleErrors>
public static ReadOnlySpan<GlfwJoystickHat> GetJoystickHats(int joystickId)
{
return new ReadOnlySpan<byte>(PInvoke.GetJoystickHats(joystickId, out var count), count).Cast<
byte,
GlfwJoystickHat
>();
}
/// <summary>Sets the clipboard to the specified string.</summary>
/// <remarks>
/// This function sets the system clipboard to the specified, UTF-8 encoded string.
/// </remarks>
/// <param name="string">The string to set the clipboard to.</param>
/// <seealso cref="Clipboard" />
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#clipboard">Clipboard input and output</seealso>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />
/// <see cref="GlfwErrorCode.PlatformError" />
/// </possibleErrors>
public static void SetClipboard(string @string)
{
PInvoke.SetClipboardString(null, @string);
}
/// <summary>Returns the contents of the clipboard as a string.</summary>
/// <remarks>
/// This function returns the contents of the system clipboard, if it contains or is convertible to a UTF-8 encoded
/// string. If the clipboard is empty or if its contents cannot be converted, <see langword="null" /> is returned and
/// a <see cref="GlfwErrorCode.FormatUnavailable" /> error is generated.
/// </remarks>
/// <returns>
/// The contents of the clipboard, or <see langword="null" /> if the clipboard is empty, its contents cannot be
/// converted, or an error occurred.
/// </returns>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso cref="SetClipboard" />
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#clipboard">Clipboard input and output</seealso>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />
/// <see cref="GlfwErrorCode.FormatUnavailable" />
/// <see cref="GlfwErrorCode.PlatformError" />
/// </possibleErrors>
public static string? Clipboard
{
get => PInvoke.GetClipboardString(null);
set
{
ArgumentNullException.ThrowIfNull(value);
PInvoke.SetClipboardString(null, value);
}
}
/// <summary>Returns the GLFW time.</summary>
/// <remarks>
/// This function returns the current GLFW time, in seconds. Unless the time has been set using <see cref="SetTime" />
/// it measures time elapsed since GLFW was initialized.
/// <para />
/// This function and <see cref="SetTime" /> are helper functions on top of <see cref="GetTimerFrequency" /> and
/// <see cref="GetTimerValue" />.
/// <para />
/// The resolution of the timer is system dependent, but is usually on the order of a few micro- or nanoseconds. It
/// uses the highest-resolution monotonic time source on each supported platform.
/// </remarks>
/// <returns>The current time, in seconds, or zero if an error occurred.</returns>
/// <threadSafety>
/// This function may be called from any thread. Reading and writing of the internal base time is not atomic,
/// so it needs to be externally synchronized with calls to <see cref="SetTime" />.
/// </threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/input_guide.html#time">Time input</seealso>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />
/// </possibleErrors>
public static double Time
{
get => PInvoke.GetTime();
set => PInvoke.SetTime(value);
}
}

View file

@ -0,0 +1,228 @@
// Monitor reference
// https://www.glfw.org/docs/latest/group__monitor.html
// Hand-written members of the Monitor library: the GlfwMonitor handle struct scaffolding + its
// marshaller, the monitor-configuration callback delegate/event, GetMonitors (span - deferred),
// and the instance members not yet covered by a generator transform: Position/PhysicalSize/
// ContentScale (out-params -> vector), GetMonitorWorkArea (4 outs -> 2 vectors), Size (computed),
// VideoModes (span), VideoMode (pointer deref), and GammaRamp (GlfwGammaRampView get/set). The
// basic members - PrimaryMonitor, Name, UserPointer, SetGamma - are generated into
// Generated/Libraries/Glfw.Monitor.gen.cs and merge into these same partial declarations.
using System.Runtime.InteropServices.Marshalling;
namespace Brutal.GlfwApi;
/// <summary>The function pointer type for monitor configuration callbacks.</summary>
/// <param name="monitor">The monitor that was connected or disconnected.</param>
/// <param name="eventType">
/// One of <see cref="GlfwMonitorEvent.Connected" /> or
/// <see cref="GlfwMonitorEvent.Disconnected" />.
/// </param>
/// <seealso cref="Glfw.MonitorCallback" />
/// <seealso href="https://www.glfw.org/docs/latest/monitor_guide.html#monitor_event">Monitor configuration changes</seealso>
public delegate void GlfwMonitorCallback(GlfwMonitor monitor, GlfwMonitorEvent eventType);
public static unsafe partial class Glfw
{
/// <summary>Sets the monitor configuration function.</summary>
/// <remarks>
/// This function sets the monitor configuration callback, or removes the currently set callback. This is called when a
/// monitor is connected to or disconnected from the system.
/// </remarks>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />
/// </possibleErrors>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/monitor_guide.html#monitor_event">Monitor configuration changes</seealso>
public static event GlfwMonitorCallback? MonitorCallback;
}
/// <summary>
/// Wrapper around a <see cref="GlfwMonitorHandle" />*
/// </summary>
[NativeMarshalling(typeof(GlfwMonitorMarshaller))]
public readonly unsafe partial struct GlfwMonitor : INullable
{
public static readonly GlfwMonitor Null = new(null);
internal GlfwMonitor(GlfwMonitorHandle* inPointer)
{
Pointer = inPointer;
}
internal GlfwMonitorHandle* Pointer { get; }
/// <summary>
/// Gets the native Glfw handle for this monitor
/// </summary>
public nint NativeHandle => (nint)Pointer;
public bool IsNull()
{
return Pointer == null;
}
/// <summary>Retrieves the work area of the monitor.</summary>
/// <remarks>
/// This function returns the position, in screen coordinates, of the upper-left corner of the work area of the
/// monitor along with the work area size in screen coordinates. The work area is defined as the area
/// of the monitor not occluded by the operating system task bar where present. If no task bar exists then the
/// work area is the monitor resolution in screen coordinates.
/// <para />
/// If an error occurs, all values are set to zero.
/// </remarks>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />,
/// <see cref="GlfwErrorCode.PlatformError" />
/// </possibleErrors>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/monitor_guide.html#monitor_workarea">Work area</seealso>
public void GetMonitorWorkArea(out int2 pos, out int2 size)
{
Glfw.PInvoke.GetMonitorWorkArea(this, out var x, out var y, out var w, out var h);
pos = new int2(x, y);
size = new int2(w, h);
}
public int2 Size
{
get
{
var videoMode = VideoMode;
return new int2(videoMode.Width, videoMode.Height);
}
}
/// <summary>Returns the current mode of the monitor.</summary>
/// <remarks>
/// This function returns the current video mode of the monitor. If you have created a full screen window for
/// that monitor, the return value will depend on whether that window is iconified.
/// </remarks>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />
/// <see cref="GlfwErrorCode.PlatformError" />
/// </possibleErrors>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso cref="VideoModes">VideoModes</seealso>
/// <seealso href="https://www.glfw.org/docs/latest/monitor_guide.html#monitor_modes">Video modes</seealso>
public GlfwVidMode VideoMode
{
get
{
var videoMode = Glfw.PInvoke.GetVideoMode(this);
return videoMode != null ? *videoMode : default;
}
}
/// <summary>Gets/Sets the current gamma ramp for the monitor.</summary>
/// <remarks>
/// The getter returns the current gamma ramp of the monitor, or an empty view if an error occurred. The view
/// is valid until the monitor is disconnected, the gamma ramp is read again for that monitor or the library
/// is terminated.
/// <para />
/// The setter sets the current gamma ramp for the monitor. The original gamma ramp for that monitor is
/// saved by GLFW the first time the ramp is set and is restored by glfwTerminate. The specified gamma ramp
/// is copied before the setter returns.
/// <para />
/// The software controlled gamma ramp is applied in addition to the hardware gamma correction, which today is usually
/// an approximation of sRGB gamma. This means that setting a perfectly linear ramp, or gamma 1.0, will produce the
/// default (usually sRGB-like) behavior.
/// <para />
/// For gamma correct rendering with OpenGL or OpenGL ES, see the GLFW_SRGB_CAPABLE hint.
/// </remarks>
/// <exception cref="ArgumentException">The setter was given an empty ramp.</exception>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />
/// <see cref="GlfwErrorCode.PlatformError" />
/// </possibleErrors>
/// <threadSafety>This function must only be called from the main thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/monitor_guide.html#monitor_gamma">Gamma ramp</seealso>
public GlfwGammaRampView GammaRamp
{
get
{
var ramp = Glfw.PInvoke.GetGammaRamp(this);
if (ramp == null)
return default;
var size = (int)ramp->Size;
return new GlfwGammaRampView(
new ReadOnlySpan<ushort>(ramp->Red, size),
new ReadOnlySpan<ushort>(ramp->Green, size),
new ReadOnlySpan<ushort>(ramp->Blue, size)
);
}
set
{
if (value.IsEmpty)
throw new ArgumentException("Cannot set an empty gamma ramp.", nameof(value));
fixed (ushort* red = value.Red)
fixed (ushort* green = value.Green)
fixed (ushort* blue = value.Blue)
{
var ramp = new GlfwGammaRamp
{
Red = red,
Green = green,
Blue = blue,
Size = (uint)value.Size,
};
Glfw.PInvoke.SetGammaRamp(this, &ramp);
}
}
}
}
/// <summary>Describes the gamma ramp for a monitor.</summary>
/// <remarks>
/// Views returned by <see cref="GlfwMonitor.GammaRamp" /> borrow memory owned by GLFW; see that
/// property for the lifetime rules.
/// </remarks>
/// <seealso cref="GlfwMonitor.GammaRamp" />
/// <seealso href="https://www.glfw.org/docs/latest/monitor_guide.html#monitor_gamma">Gamma ramp</seealso>
public readonly ref struct GlfwGammaRampView
{
/// <summary>Creates a gamma ramp view over three equal-length channel buffers.</summary>
/// <param name="red">The response of the red channel.</param>
/// <param name="green">The response of the green channel.</param>
/// <param name="blue">The response of the blue channel.</param>
/// <exception cref="ArgumentException">The channels are not all the same length.</exception>
public GlfwGammaRampView(ReadOnlySpan<ushort> red, ReadOnlySpan<ushort> green, ReadOnlySpan<ushort> blue)
{
if (red.Length != green.Length || red.Length != blue.Length)
throw new ArgumentException("Gamma ramp channels must all be the same length.");
Red = red;
Green = green;
Blue = blue;
}
/// <summary>The response of the red channel.</summary>
public ReadOnlySpan<ushort> Red { get; }
/// <summary>The response of the green channel.</summary>
public ReadOnlySpan<ushort> Green { get; }
/// <summary>The response of the blue channel.</summary>
public ReadOnlySpan<ushort> Blue { get; }
/// <summary>The number of elements in each channel.</summary>
public int Size => Red.Length;
/// <summary>Whether the view holds no data.</summary>
public bool IsEmpty => Red.IsEmpty;
}
[CustomMarshaller(
managedType: typeof(GlfwMonitor),
marshalMode: MarshalMode.Default,
marshallerType: typeof(GlfwMonitorMarshaller)
)]
internal static unsafe class GlfwMonitorMarshaller
{
internal static GlfwMonitorHandle* ConvertToUnmanaged(GlfwMonitor managed) => managed.Pointer;
internal static GlfwMonitor ConvertToManaged(GlfwMonitorHandle* unmanaged) => new(unmanaged);
}

View file

@ -0,0 +1,63 @@
// Vulkan support reference
// https://www.glfw.org/docs/latest/group__vulkan.html
// Hand-written member of the Vulkan library. CreateWindowSurface fixed-pins the out-parameter into
// a pointer and hardcodes a null allocator - not mechanically derivable - so it stays here. The
// rest of the Vulkan library is generated into Generated/Libraries/Glfw.Vulkan.gen.cs and merges
// into this same partial class.
namespace Brutal.GlfwApi;
public static unsafe partial class Glfw
{
/// <summary>Creates a Vulkan surface for the specified window.</summary>
/// <remarks>
/// This function creates a Vulkan surface for the specified window.
/// <para />
/// If the Vulkan loader or at least one minimally functional ICD were not found, this function returns
/// <c>VK_ERROR_INITIALIZATION_FAILED</c> and generates a <see cref="GlfwErrorCode.ApiUnavailable" /> error. Call
/// <see cref="VulkanSupported">Glfw.VulkanSupported</see> to check whether Vulkan is at least minimally available.
/// <para />
/// If the required window surface creation instance extensions are not available or the specified instance was not
/// created with these extensions enabled,
/// this function returns <c>VK_ERROR_EXTENSION_NOT_PRESENT</c> and generates a <see cref="GlfwErrorCode.ApiUnavailable" /> error. Call
/// <see cref="GetRequiredInstanceExtensions">GetRequiredInstanceExtensions</see> to check what instance extensions
/// are required.
/// <para />
/// The window surface cannot be shared with another API so the window must have been created with the
/// <see cref="GlfwWindowHint.ClientApi"/> hint set to <see cref="Constants.GLFW_NO_API" /> otherwise it
/// generates a <see cref="GlfwErrorCode.InvalidValue" /> error and returns <c>VK_ERROR_NATIVE_WINDOW_IN_USE_KHR</c>.
/// <para />
/// The window surface must be destroyed before the specified Vulkan instance. It is the responsibility of the
/// caller to destroy the window surface. GLFW does not destroy it for you.
/// Call <c>vkGetInstanceProcAddr</c> on the surface to destroy it.
/// <para />
/// If an error occurs before the creation call is made, GLFW returns the Vulkan error code most appropriate for
/// the error. Appropriate use of <see cref="VulkanSupported">Glfw.VulkanSupported</see> and
/// <see cref="GetRequiredInstanceExtensions">GetRequiredInstanceExtensions</see> should eliminate
/// almost all occurrences of this error.
/// <para />
/// macOS: GLFW prefers the <c>VK_EXT_metal_surface</c> extension, with the <c>VK_MVK_macos_surface</c> extension
/// as a fallback. The <c>VK_EXT_metal_surface</c> extension is the preferred extension for macOS and is the only
/// one that supports Metal.
/// <para />
/// macOS: This function creates and sets a <c>CAMetalLayer</c> instance for the window content view, which is
/// required for MoltenVK to function.
/// </remarks>
/// <possibleErrors>
/// <see cref="GlfwErrorCode.NotInitialized" />,
/// <see cref="GlfwErrorCode.ApiUnavailable" />,
/// <see cref="GlfwErrorCode.PlatformError" />,
/// <see cref="GlfwErrorCode.InvalidValue" />
/// </possibleErrors>
/// <threadSafety>This function may be called from any thread.</threadSafety>
/// <seealso href="https://www.glfw.org/docs/latest/vulkan_guide.html#vulkan_surface">Creating a Vulkan window surface</seealso>
public static int CreateWindowSurface(nint instance, GlfwWindow window, out ulong surface)
{
fixed (ulong* surfacePtr = &surface)
{
// Call the internal function to create the window surface
return PInvoke.CreateWindowSurface(instance, window, null, surfacePtr);
}
}
}

File diff suppressed because it is too large Load diff