mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-29 14:38:25 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
8 changed files with 768360 additions and 0 deletions
156
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Events.cs
Normal file
156
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Events.cs
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
namespace Brutal.SdlApi;
|
||||
|
||||
/// <summary>
|
||||
/// A managed SDL event-watch callback registered with <see cref="Sdl.Events.AddEventWatch"/>.
|
||||
/// Receives each event as it is added to the queue, by reference so the handler can inspect it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// SDL ignores the return value of an event watch; the <c>bool</c> return exists to mirror SDL's
|
||||
/// <c>SDL_EventFilter</c> shape and reserve the same signature for a future filter overload.
|
||||
/// </remarks>
|
||||
/// <param name="ev">The event being delivered, by reference.</param>
|
||||
/// <returns><c>true</c> to indicate the event should be kept (ignored for watches).</returns>
|
||||
public delegate bool SdlEventWatch(ref SdlEvent ev);
|
||||
|
||||
public static unsafe partial class Sdl
|
||||
{
|
||||
public static unsafe partial class Events
|
||||
{
|
||||
// Registered event watches, keyed by the managed delegate the caller passed. The GCHandle
|
||||
// roots the delegate for as long as SDL holds the native function pointer, and its IntPtr is
|
||||
// the userdata SDL threads back to the trampoline so it can dispatch to the right delegate.
|
||||
// SDL_RemoveEventWatch matches on (function pointer, userdata), so the same handle value must
|
||||
// be handed back on removal — hence the map. Guarded by a lock because SDL permits adding and
|
||||
// removing watches from any thread.
|
||||
private static readonly Dictionary<SdlEventWatch, GCHandle> Watches = new();
|
||||
private static readonly Lock WatchLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Polls for the next pending event, removing it from the queue.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Registered event watches fire synchronously while SDL processes the queue during this
|
||||
/// call. Any exception they raise is captured (it cannot cross the native boundary) and
|
||||
/// rethrown here, after the poll completes, via the shared
|
||||
/// <see cref="Sdl.ExceptionAggregator"/>.
|
||||
/// </remarks>
|
||||
/// <param name="ev">Receives the next event, or a zeroed event when none is pending.</param>
|
||||
/// <returns><c>true</c> if an event was dequeued; otherwise <c>false</c>.</returns>
|
||||
/// <exception cref="Exception">A single event-watch callback threw.</exception>
|
||||
/// <exception cref="AggregateException">More than one event-watch callback threw.</exception>
|
||||
public static bool PollEvent(out SdlEvent ev)
|
||||
{
|
||||
ev = default;
|
||||
|
||||
bool dequeued;
|
||||
fixed (SdlEvent* p = &ev)
|
||||
dequeued = PInvoke.PollEvent(p) != 0;
|
||||
|
||||
Sdl.ExceptionAggregator.CheckExceptions();
|
||||
return dequeued;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers <paramref name="callback"/> to be invoked for every event added to the queue.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The delegate is rooted for the lifetime of the registration (SDL retains the native
|
||||
/// function pointer), and its invocations are wrapped so that any exception is routed to the
|
||||
/// aggregator and rethrown from the next <see cref="PollEvent(out SdlEvent)"/> rather than
|
||||
/// unwinding across native code. Registering the same delegate twice is a no-op.
|
||||
/// </remarks>
|
||||
/// <param name="callback">The watch to register.</param>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="callback"/> is <c>null</c>.</exception>
|
||||
/// <exception cref="SdlException">SDL failed to register the watch.</exception>
|
||||
public static void AddEventWatch(SdlEventWatch callback)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(callback);
|
||||
|
||||
lock (WatchLock)
|
||||
{
|
||||
if (Watches.ContainsKey(callback))
|
||||
return;
|
||||
|
||||
var handle = GCHandle.Alloc(callback);
|
||||
if (PInvoke.AddEventWatch(&EventWatchTrampoline, (void*)GCHandle.ToIntPtr(handle)) == 0)
|
||||
{
|
||||
handle.Free();
|
||||
throw SdlException.FromError("SDL_AddEventWatch failed");
|
||||
}
|
||||
|
||||
Watches[callback] = handle;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregisters a watch previously added with <see cref="AddEventWatch"/> and releases the
|
||||
/// delegate it was keeping alive. Does nothing if the delegate was not registered.
|
||||
/// </summary>
|
||||
/// <param name="callback">The watch to remove.</param>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="callback"/> is <c>null</c>.</exception>
|
||||
public static void RemoveEventWatch(SdlEventWatch callback)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(callback);
|
||||
|
||||
lock (WatchLock)
|
||||
{
|
||||
if (!Watches.Remove(callback, out var handle))
|
||||
return;
|
||||
|
||||
PInvoke.RemoveEventWatch(&EventWatchTrampoline, (void*)GCHandle.ToIntPtr(handle));
|
||||
handle.Free();
|
||||
}
|
||||
}
|
||||
|
||||
// Removes every registered watch and frees the GCHandle rooting each delegate. Called during
|
||||
// Sdl.Init.Quit teardown: SDL_Quit drops the native watch list wholesale, so without this the
|
||||
// GCHandles would leak and — worse — a subsequent re-init + re-AddEventWatch of the same
|
||||
// delegate would be a silent no-op (the managed map still believed it was registered). By
|
||||
// clearing the map here, add→Quit→re-init→re-add works. (F3)
|
||||
internal static void ClearWatches()
|
||||
{
|
||||
lock (WatchLock)
|
||||
{
|
||||
foreach (var (_, handle) in Watches)
|
||||
{
|
||||
// Remove the native registration first (still valid pre-SDL_Quit), then release
|
||||
// the managed root. Both are matched on (function pointer, userdata).
|
||||
PInvoke.RemoveEventWatch(&EventWatchTrampoline, (void*)GCHandle.ToIntPtr(handle));
|
||||
handle.Free();
|
||||
}
|
||||
|
||||
Watches.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
// The single native entry point for every registered watch. SDL passes the GCHandle IntPtr
|
||||
// back as userdata; we resolve it to the managed delegate and invoke it inside a try/catch so
|
||||
// no exception ever escapes into native code. Failures are parked in the aggregator and
|
||||
// rethrown from the next PollEvent.
|
||||
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
private static byte EventWatchTrampoline(void* userdata, SdlEvent* ev)
|
||||
{
|
||||
try
|
||||
{
|
||||
var handle = GCHandle.FromIntPtr((nint)userdata);
|
||||
if (handle.Target is SdlEventWatch filter)
|
||||
return filter(ref *ev) ? (byte)1 : (byte)0;
|
||||
|
||||
// The handle resolved but its target is not one of our watches: it was freed (dead)
|
||||
// or belongs to some other subsystem (foreign). Falling through silently would hide a
|
||||
// real lifecycle bug, so surface it through the aggregator rather than swallowing it.
|
||||
Sdl.ExceptionAggregator.Push(
|
||||
"An SDL event watch fired with a dead or foreign GCHandle (its target was not an "
|
||||
+ "SdlEventWatch); the callback was skipped."
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Sdl.ExceptionAggregator.Push("An exception occurred in an SDL event watch callback.", ex);
|
||||
}
|
||||
|
||||
// Event watches ignore the return value; permit by default.
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
58
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Gamepad.cs
Normal file
58
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Gamepad.cs
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
namespace Brutal.SdlApi;
|
||||
|
||||
public static unsafe partial class Sdl
|
||||
{
|
||||
public static unsafe partial class Gamepad
|
||||
{
|
||||
// SDL_GetGamepadTouchpadFinger's generated ergonomic wrapper (Phase 1 Task 5) promoted the
|
||||
// `float* x`/`y`/`pressure` out-parameters but left `bool* down` as a raw `byte*`: the
|
||||
// generic out-promotion in Generator.Libraries.cs deliberately excludes a bool pointee
|
||||
// (IsPureOutPointer's Bool case) because SDL's 1-byte C bool needs a shadow-byte-then-`!= 0`
|
||||
// conversion on the way back out, not the direct address-of-out that pipeline does for
|
||||
// scalar/enum pointees. This hand-written wrapper finishes the job: a fully `out bool`
|
||||
// signature, calling the existing raw `PInvoke.GetGamepadTouchpadFinger` (no new
|
||||
// `[LibraryImport]` here — the raw layer already binds `SDL_GetGamepadTouchpadFinger`).
|
||||
/// <summary>
|
||||
/// Gets the current state of a finger on a touchpad on a gamepad.
|
||||
/// </summary>
|
||||
/// <param name="gamepad">A gamepad.</param>
|
||||
/// <param name="touchpad">A touchpad.</param>
|
||||
/// <param name="finger">A finger.</param>
|
||||
/// <param name="down">Filled with <see langword="true"/> if the finger is down, <see langword="false"/> otherwise.</param>
|
||||
/// <param name="x">Filled with the x position, normalized 0 to 1, with the origin in the upper left.</param>
|
||||
/// <param name="y">Filled with the y position, normalized 0 to 1, with the origin in the upper left.</param>
|
||||
/// <param name="pressure">Filled with the pressure value.</param>
|
||||
/// <returns><see langword="true"/> on success, <see langword="false"/> on failure; call <see cref="Sdl.PInvoke.GetError"/> for more information.</returns>
|
||||
public static bool GetGamepadTouchpadFinger(
|
||||
SdlGamepad gamepad,
|
||||
int touchpad,
|
||||
int finger,
|
||||
out bool down,
|
||||
out float x,
|
||||
out float y,
|
||||
out float pressure
|
||||
)
|
||||
{
|
||||
// Pre-zero the bool shadow byte alongside the three float out-params: on failure SDL writes
|
||||
// NONE of *down/*x/*y/*pressure (verified in SDL_gamepad.c's SDL_GetGamepadTouchpadFinger —
|
||||
// every failure path returns false before touching the out-pointers), so an uninitialized
|
||||
// downByte would leave `out down` reading stack garbage. `= 0` makes it deterministically
|
||||
// false on the failure path, mirroring the `= default` treatment of the floats.
|
||||
byte downByte = 0;
|
||||
bool result;
|
||||
x = default;
|
||||
y = default;
|
||||
pressure = default;
|
||||
fixed (float* xPtr = &x)
|
||||
fixed (float* yPtr = &y)
|
||||
fixed (float* pressurePtr = &pressure)
|
||||
{
|
||||
result =
|
||||
PInvoke.GetGamepadTouchpadFinger(gamepad, touchpad, finger, &downByte, xPtr, yPtr, pressurePtr)
|
||||
!= 0;
|
||||
}
|
||||
down = downByte != 0;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
46
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Init.cs
Normal file
46
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Init.cs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
namespace Brutal.SdlApi;
|
||||
|
||||
public static unsafe partial class Sdl
|
||||
{
|
||||
public static unsafe partial class Init
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes the SDL subsystems selected by <paramref name="flags"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is the throwing, ergonomic entry point that replaces the raw <c>SDL_Init</c> binding
|
||||
/// (which stays available only as <see cref="Sdl.PInvoke.Init"/> because the name
|
||||
/// <c>Init</c> collides with this enclosing class). The first call into the P/Invoke layer
|
||||
/// installs the <see cref="NativeLibrary.SetDllImportResolver"/> that locates the SDL3 shared
|
||||
/// library, so no separate registration step is required. Call <see cref="Quit"/> before the
|
||||
/// application exits.
|
||||
/// </remarks>
|
||||
/// <param name="flags">The subsystems to initialize.</param>
|
||||
/// <exception cref="SdlException">SDL failed to initialize; the message carries the <c>SDL_GetError</c> text.</exception>
|
||||
public static void Initialize(SdlInitFlags flags)
|
||||
{
|
||||
// SDL_Init returns SDL bool (false = failure), rendered as a byte by the raw layer.
|
||||
if (PInvoke.Init(flags) == 0)
|
||||
throw SdlException.FromError("SDL_Init failed");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleans up all initialized SDL subsystems (<c>SDL_Quit</c>). Safe to call even if
|
||||
/// <see cref="Initialize"/> was never called.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This hand-written wrapper replaces the generated one so it can tear down the binding's
|
||||
/// managed state before handing control to native SDL: every registered event watch is
|
||||
/// removed and its rooting <see cref="GCHandle"/> freed, and any parked callback exceptions
|
||||
/// are discarded. <c>SDL_Quit</c> drops SDL's native watch list wholesale, so skipping this
|
||||
/// would leak the handles and leave the managed watch map out of sync with native reality —
|
||||
/// a later re-init and re-registration of the same delegate would silently do nothing.
|
||||
/// </remarks>
|
||||
public static void Quit()
|
||||
{
|
||||
Events.ClearWatches();
|
||||
Sdl.ExceptionAggregator.Clear();
|
||||
PInvoke.Quit();
|
||||
}
|
||||
}
|
||||
}
|
||||
63
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Keyboard.cs
Normal file
63
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Keyboard.cs
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
using System.Text;
|
||||
|
||||
namespace Brutal.SdlApi;
|
||||
|
||||
public static unsafe partial class Sdl
|
||||
{
|
||||
public static unsafe partial class Keyboard
|
||||
{
|
||||
// SDL_SetScancodeName stores the pointer we pass verbatim — `SDL_scancode_names[scancode] =
|
||||
// name;` in SDL_keymap.c, with no copy — and reads it back later from SDL_GetScancodeName.
|
||||
// The default string marshaller would free the temporary UTF-8 buffer as soon as the call
|
||||
// returned, leaving SDL holding a dangling pointer. So this is hand-written (the generator
|
||||
// auto-skips it because the LibraryImport below declares its EntryPoint): we allocate a
|
||||
// NUL-terminated UTF-8 copy in unmanaged memory that we own, hand SDL that, and keep it alive
|
||||
// in a per-scancode registry, freeing the previous copy when a scancode is renamed. (F1)
|
||||
private static readonly Dictionary<SdlScancode, nint> ScancodeNames = new();
|
||||
private static readonly Lock ScancodeNameLock = new();
|
||||
|
||||
[LibraryImport(Dll, EntryPoint = "SDL_SetScancodeName")]
|
||||
private static partial byte _SetScancodeName(SdlScancode scancode, byte* name);
|
||||
|
||||
/// <summary>
|
||||
/// Sets a human-readable name for a scancode (<c>SDL_SetScancodeName</c>).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// SDL retains the name pointer rather than copying it, so this binding keeps an unmanaged
|
||||
/// copy alive for the lifetime of the registration. Setting a new name for the same scancode
|
||||
/// releases the previous copy.
|
||||
/// </remarks>
|
||||
/// <param name="scancode">The scancode to name.</param>
|
||||
/// <param name="name">The name to assign.</param>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="name"/> is <c>null</c>.</exception>
|
||||
/// <exception cref="SdlException">SDL rejected the scancode or name.</exception>
|
||||
public static void SetScancodeName(SdlScancode scancode, string name)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(name);
|
||||
|
||||
// Copy `name` into unmanaged memory we own: a NUL-terminated UTF-8 buffer.
|
||||
var byteCount = Encoding.UTF8.GetByteCount(name);
|
||||
var buffer = (byte*)NativeMemory.Alloc((nuint)(byteCount + 1));
|
||||
var span = new Span<byte>(buffer, byteCount + 1);
|
||||
Encoding.UTF8.GetBytes(name, span);
|
||||
span[byteCount] = 0;
|
||||
|
||||
lock (ScancodeNameLock)
|
||||
{
|
||||
if (_SetScancodeName(scancode, buffer) == 0)
|
||||
{
|
||||
// SDL did not take the pointer; free our copy and surface the error.
|
||||
NativeMemory.Free(buffer);
|
||||
throw SdlException.FromError("SDL_SetScancodeName failed");
|
||||
}
|
||||
|
||||
// SDL now holds `buffer`. Any previous copy WE allocated for this scancode is no
|
||||
// longer referenced by SDL, so free it. (Default SDL names are static literals and
|
||||
// are never in this registry, so they are never freed.)
|
||||
if (ScancodeNames.TryGetValue(scancode, out var previous))
|
||||
NativeMemory.Free((void*)previous);
|
||||
ScancodeNames[scancode] = (nint)buffer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
88
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Log.cs
Normal file
88
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Log.cs
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
namespace Brutal.SdlApi;
|
||||
|
||||
public static unsafe partial class Sdl
|
||||
{
|
||||
/// <summary>
|
||||
/// Ergonomic wrappers over SDL's logging family (<c>SDL_Log</c>, <c>SDL_LogInfo</c>, …,
|
||||
/// <c>SDL_LogMessage</c>).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// SDL's logging functions are variadic in C and so were skipped by the raw generator; these
|
||||
/// fixed-arity wrappers expose them safely. Each routes through <see cref="Sdl.PInvoke.LogMessage"/>
|
||||
/// (<c>SDL_LogMessage</c>), passing the caller's text as the format string with no variadic
|
||||
/// arguments. Any <c>%</c> in the message is escaped to <c>%%</c> so the text is emitted literally
|
||||
/// and SDL's printf parser never reads a non-existent argument.
|
||||
/// <para>
|
||||
/// This nested class reclaims the <c>Sdl.Log</c> name for the SDL logging surface. The per-call
|
||||
/// trace category the generated P/Invoke wrappers use is the separate internal
|
||||
/// <see cref="Sdl.TraceLog"/> field, so there is no collision.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class Log
|
||||
{
|
||||
/// <summary>
|
||||
/// Logs <paramref name="message"/> with the given category and priority through SDL's logging
|
||||
/// system (<c>SDL_LogMessage</c>).
|
||||
/// </summary>
|
||||
/// <param name="category">The SDL log category.</param>
|
||||
/// <param name="priority">The message priority.</param>
|
||||
/// <param name="message">The message text (treated literally; <c>%</c> is not a format specifier).</param>
|
||||
public static void Message(SdlLogCategory category, SdlLogPriority priority, string message)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(message);
|
||||
PInvoke.LogMessage((int)category, priority, Escape(message));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Logs <paramref name="message"/> at <see cref="SdlLogPriority.Info"/> under the
|
||||
/// <see cref="SdlLogCategory.Application"/> category (the <c>SDL_Log</c> default).
|
||||
/// </summary>
|
||||
/// <param name="message">The message text.</param>
|
||||
public static void Message(string message) => Message(SdlLogCategory.Application, SdlLogPriority.Info, message);
|
||||
|
||||
/// <summary>Logs a message at <see cref="SdlLogPriority.Trace"/> (<c>SDL_LogTrace</c>).</summary>
|
||||
/// <param name="category">The SDL log category.</param>
|
||||
/// <param name="message">The message text.</param>
|
||||
public static void Trace(SdlLogCategory category, string message) =>
|
||||
Message(category, SdlLogPriority.Trace, message);
|
||||
|
||||
/// <summary>Logs a message at <see cref="SdlLogPriority.Verbose"/> (<c>SDL_LogVerbose</c>).</summary>
|
||||
/// <param name="category">The SDL log category.</param>
|
||||
/// <param name="message">The message text.</param>
|
||||
public static void Verbose(SdlLogCategory category, string message) =>
|
||||
Message(category, SdlLogPriority.Verbose, message);
|
||||
|
||||
/// <summary>Logs a message at <see cref="SdlLogPriority.Debug"/> (<c>SDL_LogDebug</c>).</summary>
|
||||
/// <param name="category">The SDL log category.</param>
|
||||
/// <param name="message">The message text.</param>
|
||||
public static void Debug(SdlLogCategory category, string message) =>
|
||||
Message(category, SdlLogPriority.Debug, message);
|
||||
|
||||
/// <summary>Logs a message at <see cref="SdlLogPriority.Info"/> (<c>SDL_LogInfo</c>).</summary>
|
||||
/// <param name="category">The SDL log category.</param>
|
||||
/// <param name="message">The message text.</param>
|
||||
public static void Info(SdlLogCategory category, string message) =>
|
||||
Message(category, SdlLogPriority.Info, message);
|
||||
|
||||
/// <summary>Logs a message at <see cref="SdlLogPriority.Warn"/> (<c>SDL_LogWarn</c>).</summary>
|
||||
/// <param name="category">The SDL log category.</param>
|
||||
/// <param name="message">The message text.</param>
|
||||
public static void Warn(SdlLogCategory category, string message) =>
|
||||
Message(category, SdlLogPriority.Warn, message);
|
||||
|
||||
/// <summary>Logs a message at <see cref="SdlLogPriority.Error"/> (<c>SDL_LogError</c>).</summary>
|
||||
/// <param name="category">The SDL log category.</param>
|
||||
/// <param name="message">The message text.</param>
|
||||
public static void Error(SdlLogCategory category, string message) =>
|
||||
Message(category, SdlLogPriority.Error, message);
|
||||
|
||||
/// <summary>Logs a message at <see cref="SdlLogPriority.Critical"/> (<c>SDL_LogCritical</c>).</summary>
|
||||
/// <param name="category">The SDL log category.</param>
|
||||
/// <param name="message">The message text.</param>
|
||||
public static void Critical(SdlLogCategory category, string message) =>
|
||||
Message(category, SdlLogPriority.Critical, message);
|
||||
|
||||
// Escapes printf conversion specifiers so the caller's text is logged verbatim.
|
||||
private static string Escape(string message) => message.Contains('%') ? message.Replace("%", "%%") : message;
|
||||
}
|
||||
}
|
||||
124
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Vulkan.cs
Normal file
124
brutal.sdl/Brutal.Sdl/Manual/Libraries/Sdl.Vulkan.cs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
namespace Brutal.SdlApi;
|
||||
|
||||
public static unsafe partial class Sdl
|
||||
{
|
||||
public static unsafe partial class PInvoke
|
||||
{
|
||||
// SDL_vulkan.h is not part of the umbrella header the generator's shim consumes
|
||||
// (Brutal.Sdl.Generate/sdl3_all.h only `#include <SDL3/SDL.h>`, which does not itself pull
|
||||
// in SDL_vulkan.h - unlike SDL_render.h, which is why SDL_AddVulkanRenderSemaphores exists in
|
||||
// the generated surface but nothing else Vulkan-related does). Rather than widen the
|
||||
// generator's input header - which would also mint brand-new generated VkInstance/
|
||||
// VkPhysicalDevice/VkSurfaceKHR handle types with no relationship to
|
||||
// RocketWerkz.Brutal.Vulkan's own types of the same name, the whole point of the cross-package
|
||||
// sample - the handful of entry points VulkanSurfaceSample actually needs are bound by hand
|
||||
// here, following the same manual-gap pattern as SDL_LogMessage in Sdl.PInvoke.cs.
|
||||
//
|
||||
// Vulkan's opaque handles (VkInstance, VkSurfaceKHR) are spelled as `nint` rather than
|
||||
// referencing Brutal.Vulkan's own VkInstance/VkSurfaceKHR types: this package takes no
|
||||
// dependency on Vulkan, and both handles are pointer-sized opaque values on every platform
|
||||
// this project targets (Windows x64, Linux x64, macOS arm64 - all 64-bit), so `nint`
|
||||
// round-trips losslessly through Brutal.Vulkan's own `Instance.VkHandle` (an `IntPtr`).
|
||||
|
||||
[LibraryImport(Dll, EntryPoint = "SDL_Vulkan_GetInstanceExtensions")]
|
||||
private static partial byte** _Vulkan_GetInstanceExtensions(uint* count);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static byte** Vulkan_GetInstanceExtensions(uint* count)
|
||||
{
|
||||
Sdl.TraceLog.Trace();
|
||||
return _Vulkan_GetInstanceExtensions(count);
|
||||
}
|
||||
|
||||
[LibraryImport(Dll, EntryPoint = "SDL_Vulkan_CreateSurface")]
|
||||
private static partial byte _Vulkan_CreateSurface(
|
||||
SdlWindow window,
|
||||
nint instance,
|
||||
nint allocator,
|
||||
nint* surface
|
||||
);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static byte Vulkan_CreateSurface(SdlWindow window, nint instance, nint allocator, nint* surface)
|
||||
{
|
||||
Sdl.TraceLog.Trace();
|
||||
return _Vulkan_CreateSurface(window, instance, allocator, surface);
|
||||
}
|
||||
|
||||
[LibraryImport(Dll, EntryPoint = "SDL_Vulkan_DestroySurface")]
|
||||
private static partial void _Vulkan_DestroySurface(nint instance, nint surface, nint allocator);
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void Vulkan_DestroySurface(nint instance, nint surface, nint allocator)
|
||||
{
|
||||
Sdl.TraceLog.Trace();
|
||||
_Vulkan_DestroySurface(instance, surface, allocator);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ergonomic wrappers over SDL's Vulkan support functions (<c>SDL_Vulkan_GetInstanceExtensions</c>,
|
||||
/// <c>SDL_Vulkan_CreateSurface</c>, <c>SDL_Vulkan_DestroySurface</c>). See
|
||||
/// <c>VulkanSurfaceSample</c> (in the samples project) for a full cross-package usage example
|
||||
/// pairing this with <c>RocketWerkz.Brutal.Vulkan</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Only the three entry points needed to create and tear down a <c>VkSurfaceKHR</c> for an
|
||||
/// <see cref="SdlWindow"/> are bound (see <see cref="PInvoke"/> for why the rest of
|
||||
/// <c>SDL_vulkan.h</c> is not). <c>SDL_Vulkan_LoadLibrary</c> is not called explicitly: creating a
|
||||
/// window with <see cref="SdlWindowFlags.Vulkan"/> loads the Vulkan library as a side effect.
|
||||
/// </remarks>
|
||||
public static unsafe class Vulkan
|
||||
{
|
||||
/// <summary>
|
||||
/// Ergonomic wrapper over <c>SDL_Vulkan_GetInstanceExtensions</c>. Returns the instance
|
||||
/// extension names SDL requires for <c>vkCreateInstance</c> to later succeed in creating a
|
||||
/// surface for a Vulkan-flagged window.
|
||||
/// </summary>
|
||||
/// <exception cref="SdlException">The SDL call failed; the message carries the
|
||||
/// <c>SDL_GetError</c> text.</exception>
|
||||
public static string[] GetInstanceExtensions()
|
||||
{
|
||||
uint count;
|
||||
var ptr = PInvoke.Vulkan_GetInstanceExtensions(&count);
|
||||
if (ptr is null)
|
||||
throw SdlException.FromError("SDL_Vulkan_GetInstanceExtensions failed");
|
||||
|
||||
// Owned by SDL - must not be freed here (see SDL_vulkan.h's doc comment).
|
||||
var result = new string[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
result[i] = Marshal.PtrToStringUTF8((nint)ptr[i])!;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ergonomic wrapper over <c>SDL_Vulkan_CreateSurface</c>. <paramref name="instance"/> must
|
||||
/// have been created with the extensions <see cref="GetInstanceExtensions"/> returned enabled,
|
||||
/// and <paramref name="window"/> must have been created with
|
||||
/// <see cref="SdlWindowFlags.Vulkan"/>.
|
||||
/// </summary>
|
||||
/// <param name="window">The Vulkan-flagged window to attach the surface to.</param>
|
||||
/// <param name="instance">The <c>VkInstance</c> handle, as a raw pointer-sized value
|
||||
/// (e.g. <c>Instance.VkHandle</c> from RocketWerkz.Brutal.Vulkan).</param>
|
||||
/// <returns>The newly created <c>VkSurfaceKHR</c>, as a raw pointer-sized value.</returns>
|
||||
/// <exception cref="SdlException">The SDL call failed; the message carries the
|
||||
/// <c>SDL_GetError</c> text.</exception>
|
||||
public static nint CreateSurface(SdlWindow window, nint instance)
|
||||
{
|
||||
nint surface;
|
||||
if (PInvoke.Vulkan_CreateSurface(window, instance, 0, &surface) == 0)
|
||||
throw SdlException.FromError("SDL_Vulkan_CreateSurface failed");
|
||||
return surface;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ergonomic wrapper over <c>SDL_Vulkan_DestroySurface</c>. Must be called before the
|
||||
/// <paramref name="instance"/> is destroyed, and before the window is destroyed if the
|
||||
/// surface was created after the window.
|
||||
/// </summary>
|
||||
/// <param name="instance">The <c>VkInstance</c> the surface was created against.</param>
|
||||
/// <param name="surface">The <c>VkSurfaceKHR</c> to destroy.</param>
|
||||
public static void DestroySurface(nint instance, nint surface) =>
|
||||
PInvoke.Vulkan_DestroySurface(instance, surface, 0);
|
||||
}
|
||||
}
|
||||
117
brutal.sdl/Brutal.Sdl/Manual/Sdl.PInvoke.cs
Normal file
117
brutal.sdl/Brutal.Sdl/Manual/Sdl.PInvoke.cs
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
using System.Reflection;
|
||||
|
||||
namespace Brutal.SdlApi;
|
||||
|
||||
public static unsafe partial class Sdl
|
||||
{
|
||||
public static unsafe partial class PInvoke
|
||||
{
|
||||
// The native SDL3 handle, resolved lazily by the DllImportResolver below and cached so the
|
||||
// library is loaded at most once regardless of how many entry points are resolved.
|
||||
private static nint _nativeHandle;
|
||||
|
||||
// Serializes resolution. The .NET resolver can be invoked concurrently from multiple threads
|
||||
// resolving different entry points; without this two threads could both observe a zero handle
|
||||
// and race to load, leaking one of the two library handles.
|
||||
private static readonly Lock ResolveLock = new();
|
||||
|
||||
// The resolver is registered in this static constructor rather than at Initialize time so
|
||||
// that it is in place before ANY P/Invoke is resolved. Accessing a member of the nested
|
||||
// PInvoke type triggers this constructor (and only this one — the enclosing Sdl type's
|
||||
// static constructor is not triggered by nested-member access), which guarantees the
|
||||
// resolver is installed even when a consumer calls Sdl.PInvoke.* (or an ergonomic wrapper)
|
||||
// before Sdl.Init.Initialize. CLR type-initialization semantics make this run exactly once
|
||||
// and are thread-safe, so no explicit locking or "registered?" flag is needed — and
|
||||
// SetDllImportResolver (which throws if called twice for one assembly) is therefore called
|
||||
// exactly once. This mirrors the Brutal.Slang pattern.
|
||||
static PInvoke()
|
||||
{
|
||||
NativeLibrary.SetDllImportResolver(typeof(Sdl).Assembly, Resolve);
|
||||
}
|
||||
|
||||
// Normalizes the "SDL3" import name to the platform-specific shared library filename
|
||||
// (SDL3.dll on Windows, libSDL3.dylib on macOS, libSDL3.so.0 on Linux). SDL's Linux build
|
||||
// installs a versioned soname (libSDL3.so.0) that the default probing conventions do not
|
||||
// try, so the candidate list is spelled out explicitly, most-specific first, with the
|
||||
// default convention name as a fallback.
|
||||
private static nint Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
|
||||
{
|
||||
// Only ever asked to resolve SDL3; anything else is left to the default resolver.
|
||||
if (libraryName != Dll)
|
||||
return IntPtr.Zero;
|
||||
|
||||
lock (ResolveLock)
|
||||
{
|
||||
if (_nativeHandle != IntPtr.Zero)
|
||||
return _nativeHandle;
|
||||
|
||||
var search = searchPath ?? DllImportSearchPath.AssemblyDirectory;
|
||||
|
||||
// Try each candidate with Load (not TryLoad): TryLoad reports only pass/fail and
|
||||
// discards the OS diagnostic, so a candidate that *exists but fails to load* (a missing
|
||||
// transitive dependency, an ABI mismatch — the classic Linux "libSDL3.so.0 is present
|
||||
// but unusable" case) would vanish. Load throws with the real dlerror/LoadLibrary text,
|
||||
// which we aggregate so the final exception names every attempt and why it failed. (F7)
|
||||
var failures = new List<string>();
|
||||
foreach (var candidate in Candidates())
|
||||
{
|
||||
try
|
||||
{
|
||||
_nativeHandle = NativeLibrary.Load(candidate, assembly, search);
|
||||
return _nativeHandle;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failures.Add($"'{candidate}': {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
throw new DllNotFoundException(
|
||||
"Could not load the SDL3 native library. Attempts (most specific first): "
|
||||
+ string.Join("; ", failures)
|
||||
+ "."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static string[] Candidates()
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
return ["SDL3.dll", "SDL3"];
|
||||
if (OperatingSystem.IsMacOS())
|
||||
return ["libSDL3.dylib", "SDL3"];
|
||||
// Linux and other Unix-likes.
|
||||
return ["libSDL3.so.0", "libSDL3.so", "SDL3"];
|
||||
}
|
||||
|
||||
// SDL_LogMessage is variadic in C (const char *fmt, ...) and so was skipped by the raw
|
||||
// generator (LibraryImport cannot express varargs). Binding it here as a fixed-arity
|
||||
// format-only import is portable across the Windows x64 / Linux x64 / macOS arm64 targets:
|
||||
// no variadic argument is ever passed, so there is no register-vs-stack ABI mismatch (the
|
||||
// classic AAPCS64 variadic trap). The managed logging wrappers in Sdl.Log.cs pre-escape the
|
||||
// caller's message and pass it as the entire format string, so the "..." is always empty.
|
||||
[LibraryImport(
|
||||
Dll,
|
||||
EntryPoint = "SDL_LogMessage",
|
||||
StringMarshalling = StringMarshalling.Custom,
|
||||
StringMarshallingCustomType = typeof(CustomStringMarshaller)
|
||||
)]
|
||||
private static partial void _LogMessage(int category, SdlLogPriority priority, string fmt);
|
||||
|
||||
/// <summary>
|
||||
/// Emits a single already-formatted message through <c>SDL_LogMessage</c>. The
|
||||
/// <paramref name="preformatted"/> text is passed as the format string itself (with no
|
||||
/// variadic arguments); callers are responsible for escaping any <c>%</c> characters.
|
||||
/// </summary>
|
||||
/// <param name="category">The SDL log category (an <c>SDL_LOG_CATEGORY_*</c> value).</param>
|
||||
/// <param name="priority">The message priority.</param>
|
||||
/// <param name="preformatted">The final message text, used verbatim as the format string.</param>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static void LogMessage(int category, SdlLogPriority priority, string preformatted)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(preformatted);
|
||||
Sdl.TraceLog.Trace();
|
||||
_LogMessage(category, priority, preformatted);
|
||||
}
|
||||
}
|
||||
}
|
||||
73
brutal.sdl/Brutal.Sdl/Manual/SdlGamepadBinding.cs
Normal file
73
brutal.sdl/Brutal.Sdl/Manual/SdlGamepadBinding.cs
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
namespace Brutal.SdlApi;
|
||||
|
||||
/// <summary>
|
||||
/// A mapping between one joystick input and a gamepad control (<c>SDL_GamepadBinding</c>).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Hand-written rather than generated: the native <c>SDL_GamepadBinding</c> struct contains two
|
||||
/// anonymous nested unions (<c>input</c>, <c>output</c>), which the generator's struct pass cannot
|
||||
/// mirror as a flat blittable type (see <c>Generated/SKIPPED.md</c>'s "Skipped struct types"
|
||||
/// section). This explicit-layout struct reproduces the native field offsets by hand instead, so
|
||||
/// Task 4's <see cref="Sdl.Gamepad.GetGamepadBindings"/> can copy the native bytes directly via a
|
||||
/// pointer cast.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Layout (verified against <c>SDL_gamepad.h</c>): <c>input_type</c> (4 bytes) at offset 0; the
|
||||
/// <c>input</c> union (its largest member, the axis triple of three <c>int</c>s, is 12 bytes) at
|
||||
/// offset 4; <c>output_type</c> (4 bytes) at offset 16; the <c>output</c> union (again a 12-byte
|
||||
/// axis triple at its largest) at offset 20. Total size 32 bytes, 4-byte aligned, no trailing
|
||||
/// padding needed.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
[StructLayout(LayoutKind.Explicit, Size = 32)]
|
||||
public struct SdlGamepadBinding
|
||||
{
|
||||
/// <summary>Which kind of joystick input <see cref="InputButton"/>/<see cref="InputAxis"/>/<see cref="InputHat"/> describes.</summary>
|
||||
[FieldOffset(0)]
|
||||
public SdlGamepadBindingType InputType;
|
||||
|
||||
/// <summary>Valid when <see cref="InputType"/> is <see cref="SdlGamepadBindingType.Button"/>.</summary>
|
||||
[FieldOffset(4)]
|
||||
public int InputButton;
|
||||
|
||||
/// <summary>Valid when <see cref="InputType"/> is <see cref="SdlGamepadBindingType.Axis"/>.</summary>
|
||||
[FieldOffset(4)]
|
||||
public int InputAxis;
|
||||
|
||||
/// <summary>Valid when <see cref="InputType"/> is <see cref="SdlGamepadBindingType.Axis"/>.</summary>
|
||||
[FieldOffset(8)]
|
||||
public int InputAxisMin;
|
||||
|
||||
/// <summary>Valid when <see cref="InputType"/> is <see cref="SdlGamepadBindingType.Axis"/>.</summary>
|
||||
[FieldOffset(12)]
|
||||
public int InputAxisMax;
|
||||
|
||||
/// <summary>Valid when <see cref="InputType"/> is <see cref="SdlGamepadBindingType.Hat"/>.</summary>
|
||||
[FieldOffset(4)]
|
||||
public int InputHat;
|
||||
|
||||
/// <summary>Valid when <see cref="InputType"/> is <see cref="SdlGamepadBindingType.Hat"/>.</summary>
|
||||
[FieldOffset(8)]
|
||||
public int InputHatMask;
|
||||
|
||||
/// <summary>Which kind of gamepad control <see cref="OutputButton"/>/<see cref="OutputAxis"/> describes.</summary>
|
||||
[FieldOffset(16)]
|
||||
public SdlGamepadBindingType OutputType;
|
||||
|
||||
/// <summary>Valid when <see cref="OutputType"/> is <see cref="SdlGamepadBindingType.Button"/>.</summary>
|
||||
[FieldOffset(20)]
|
||||
public SdlGamepadButton OutputButton;
|
||||
|
||||
/// <summary>Valid when <see cref="OutputType"/> is <see cref="SdlGamepadBindingType.Axis"/>.</summary>
|
||||
[FieldOffset(20)]
|
||||
public SdlGamepadAxis OutputAxis;
|
||||
|
||||
/// <summary>Valid when <see cref="OutputType"/> is <see cref="SdlGamepadBindingType.Axis"/>.</summary>
|
||||
[FieldOffset(24)]
|
||||
public int OutputAxisMin;
|
||||
|
||||
/// <summary>Valid when <see cref="OutputType"/> is <see cref="SdlGamepadBindingType.Axis"/>.</summary>
|
||||
[FieldOffset(28)]
|
||||
public int OutputAxisMax;
|
||||
}
|
||||
Loading…
Reference in a new issue