Skip to content

Commit

Permalink
feat: add RNG setter
Browse files Browse the repository at this point in the history
  • Loading branch information
lmichaelis committed May 2, 2024
1 parent 3228a56 commit 9119e41
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
6 changes: 6 additions & 0 deletions DirectMusic/Native.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ internal static class Native
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void DmLogHandler(IntPtr ctx, LogLevel lvl, string message);

[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate uint DmRng(IntPtr ctx);

private const string DllName = "dmusic";

[DllImport(DllName)]
Expand Down Expand Up @@ -100,6 +103,9 @@ public static extern DmResult DmPerformance_playTransition(IntPtr slf, IntPtr sg
[DllImport(DllName)]
public static extern DmResult DmPerformance_renderPcm(IntPtr slf, float[] buf, ulong len, DmRenderOptions opts);

[DllImport(DllName)]
public static extern void Dm_setRandomNumberGenerator(DmRng rng, IntPtr ctx);

public class Structs
{
}
Expand Down
37 changes: 37 additions & 0 deletions DirectMusic/RandomNumberGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Runtime.InteropServices;
using DirectMusic.Util;

namespace DirectMusic
{
public class RandomNumberGenerator
{
private static GCHandle? _handler;
private static readonly Native.DmRng NativeHandler = _nativeCallbackHandler;

/// <summary>
///
/// </summary>
public delegate int Callback();

/// <summary>
///
/// </summary>
public static void Set(Callback cb)
{
var handler = GCHandle.Alloc(cb);
Native.Dm_setRandomNumberGenerator(NativeHandler, GCHandle.ToIntPtr(handler));

_handler?.Free();
_handler = handler;
}

[MonoPInvokeCallback]
private static uint _nativeCallbackHandler(IntPtr ctx)
{
var gcHandle = GCHandle.FromIntPtr(ctx);
var cb = (Callback)gcHandle.Target;
return (uint) (cb() % uint.MaxValue);
}
}
}

0 comments on commit 9119e41

Please sign in to comment.