Skip to content
This repository was archived by the owner on Jul 11, 2026. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 82 additions & 26 deletions Runtime/Scripts/GemmaInterop.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Cysharp.Threading.Tasks;

namespace GemmaCpp
{
public class GemmaException : Exception
Expand All @@ -37,10 +39,15 @@ public class Gemma : IDisposable

static Gemma()
{
// Load DLL from specified path
if (LoadLibrary(DllPath) == IntPtr.Zero)
// Dynamically load the Win32 DLL only when running on Windows Desktop architecture.
// Other platforms (e.g., Android/Linux) rely on native engine-level linkage via DllImport fallbacks.
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
throw new DllNotFoundException($"Failed to load {DllPath}. Error: {Marshal.GetLastWin32Error()}");
if (LoadLibrary(DllPath) == IntPtr.Zero)
{
// Fallback to warning log as Unity may still resolve the native binary within specialized Plugins folders.
UnityEngine.Debug.LogWarning($"[Gemma] Initial LoadLibrary failed for {DllPath}. Delegating assembly resolution to OS fallback handlers. Error Code: {Marshal.GetLastWin32Error()}");
}
}
}

Expand Down Expand Up @@ -77,10 +84,10 @@ private static extern int GemmaGenerate(
private static extern int GemmaGenerateMultimodal(
IntPtr context,
[MarshalAs(UnmanagedType.LPUTF8Str)] string prompt,
IntPtr image_data, // Renamed param to match C API
int image_width, // Added dimension
int image_height, // Added dimension
[MarshalAs(UnmanagedType.LPUTF8Str)] StringBuilder output, // Output should be StringBuilder for multimodal
IntPtr image_data,
int image_width,
int image_height,
[MarshalAs(UnmanagedType.LPUTF8Str)] StringBuilder output,
int maxOutputChars,
GemmaTokenCallback callback,
IntPtr userData);
Expand Down Expand Up @@ -134,7 +141,7 @@ private static extern int GemmaHasConversation(
[MarshalAs(UnmanagedType.LPUTF8Str)] string conversationName);

[DllImport("gemma", CallingConvention = CallingConvention.Cdecl, EntryPoint = "GemmaGetCurrentConversation")]
[return: MarshalAs(UnmanagedType.LPUTF8Str)] // Marshal the const char* return value as a string
[return: MarshalAs(UnmanagedType.LPUTF8Str)]
private static extern string GemmaGetCurrentConversation(IntPtr context);

[DllImport("gemma", CallingConvention = CallingConvention.Cdecl, EntryPoint = "GemmaSaveConversation")]
Expand Down Expand Up @@ -235,7 +242,6 @@ public void SetDeterministic(bool deterministic)
Debug.WriteLine($"Gemma: Set deterministic to {(deterministic ? "true" : "false")}");
}

// Renamed public method
public void ResetConversation()
{
if (_disposed)
Expand All @@ -244,7 +250,7 @@ public void ResetConversation()
if (_context == IntPtr.Zero)
throw new GemmaException("Gemma context is invalid");

GemmaResetConversation(_context); // Call P/Invoke method
GemmaResetConversation(_context);
Debug.WriteLine("Gemma: Reset active conversation");
}

Expand All @@ -257,7 +263,7 @@ public bool CreateConversation(string conversationName)
if (_context == IntPtr.Zero)
throw new GemmaException("Gemma context is invalid");

bool result = GemmaCreateConversation(_context, conversationName) != 0; // Call P/Invoke method
bool result = GemmaCreateConversation(_context, conversationName) != 0;
Debug.WriteLine($"Gemma: Create conversation '{conversationName}' - {(result ? "succeeded" : "failed")}");
return result;
}
Expand All @@ -270,7 +276,7 @@ public bool SwitchConversation(string conversationName)
if (_context == IntPtr.Zero)
throw new GemmaException("Gemma context is invalid");

bool result = GemmaSwitchConversation(_context, conversationName) != 0; // Call P/Invoke method
bool result = GemmaSwitchConversation(_context, conversationName) != 0;
Debug.WriteLine($"Gemma: Switch to conversation '{conversationName}' - {(result ? "succeeded" : "failed")}");
return result;
}
Expand All @@ -283,7 +289,7 @@ public bool DeleteConversation(string conversationName)
if (_context == IntPtr.Zero)
throw new GemmaException("Gemma context is invalid");

bool result = GemmaDeleteConversation(_context, conversationName) != 0; // Call P/Invoke method
bool result = GemmaDeleteConversation(_context, conversationName) != 0;
Debug.WriteLine($"Gemma: Delete conversation '{conversationName}' - {(result ? "succeeded" : "failed")}");
return result;
}
Expand All @@ -296,7 +302,7 @@ public bool HasConversation(string conversationName)
if (_context == IntPtr.Zero)
throw new GemmaException("Gemma context is invalid");

bool result = GemmaHasConversation(_context, conversationName) != 0; // Call P/Invoke method
bool result = GemmaHasConversation(_context, conversationName) != 0;
Debug.WriteLine($"Gemma: Has conversation '{conversationName}' - {result}");
return result;
}
Expand All @@ -309,7 +315,7 @@ public string GetCurrentConversation()
if (_context == IntPtr.Zero)
throw new GemmaException("Gemma context is invalid");

string currentConversation = GemmaGetCurrentConversation(_context); // Call P/Invoke method
string currentConversation = GemmaGetCurrentConversation(_context);
Debug.WriteLine($"Gemma: Current conversation is '{currentConversation}'");
return currentConversation;
}
Expand Down Expand Up @@ -350,21 +356,16 @@ public string Generate(string prompt, TokenCallback callback, int maxOutputChars
if (_context == IntPtr.Zero)
throw new GemmaException("Gemma context is invalid");

var outputBuffer = new byte[maxOutputChars * 4]; // Allow for worst case UTF-8 size
var outputBuffer = new byte[maxOutputChars * 4];
GemmaTokenCallback nativeCallback = null;

// Track token count for debugging
int tokenCount = 0;

if (callback != null)
{
nativeCallback = (text, _) =>
{
tokenCount++;
// Log token for debugging
Debug.WriteLine($"Token {tokenCount}: '{text}'");

// Pass token to user callback
return callback(text);
};
_callbackHandle = GCHandle.Alloc(nativeCallback);
Expand All @@ -380,7 +381,6 @@ public string Generate(string prompt, TokenCallback callback, int maxOutputChars

Debug.WriteLine($"Generation complete: {tokenCount} tokens processed, result length: {length}");

// Convert the byte buffer to a string using UTF-8 encoding
string result = Encoding.UTF8.GetString(outputBuffer, 0, length);
return result;
}
Expand All @@ -393,7 +393,6 @@ public string Generate(string prompt, TokenCallback callback, int maxOutputChars

public string GenerateMultimodal(string prompt, float[] imageData, int imageWidth, int imageHeight, int maxOutputChars = 4096)
{
// Pass width and height to the overloaded method
return GenerateMultimodal(prompt, imageData, imageWidth, imageHeight, null, maxOutputChars);
}

Expand Down Expand Up @@ -423,14 +422,12 @@ public string GenerateMultimodal(string prompt, float[] imageData, int imageWidt
_callbackHandle = GCHandle.Alloc(nativeCallback);
}

// Pin the image data so it doesn't move during the native call
GCHandle imageHandle = GCHandle.Alloc(imageData, GCHandleType.Pinned);

try
{
IntPtr imagePtr = imageHandle.AddrOfPinnedObject();

// Pass image dimensions to the native call
int length = GemmaGenerateMultimodal(_context, prompt, imagePtr, imageWidth, imageHeight, output, maxOutputChars,
nativeCallback, IntPtr.Zero);

Expand All @@ -448,6 +445,65 @@ public string GenerateMultimodal(string prompt, float[] imageData, int imageWidt
}
}

/// <summary>
/// Asynchronously generates a response from the Gemma model without blocking the main execution thread.
/// </summary>
/// <param name="prompt">The input string token sequence for the model.</param>
/// <param name="callback">Optional delegate invoked per token generation step.</param>
/// <param name="maxOutputChars">Maximum allocation size for the return UTF-8 string buffer.</param>
/// <returns>A string containing the complete inference response text.</returns>
public async UniTask<string> GenerateAsync(string prompt, TokenCallback callback, int maxOutputChars = 4096)
{
if (_disposed)
throw new ObjectDisposedException(nameof(Gemma));

if (_context == IntPtr.Zero)
throw new GemmaException("Gemma native context handle is uninitialized or invalid.");

// Context switch execution to the non-blocking worker ThreadPool to prevent Unity Main Thread starvation (UI freeze).
await UniTask.SwitchToThreadPool();

string result;
try
{
// Involve the synchronous native P/Invoke bottleneck inside the isolated worker thread.
result = Generate(prompt, callback, maxOutputChars);
}
finally
{
// Safely synchronize execution back to the Unity Main Thread for secure GameObject and UI interaction.
await UniTask.SwitchToMainThread();
}

return result;
}

/// <summary>
/// Asynchronously generates a multimodal response (text + image input) without starving the Unity main thread lifecycle.
/// </summary>
public async UniTask<string> GenerateMultimodalAsync(string prompt, float[] imageData, int imageWidth, int imageHeight, TokenCallback callback, int maxOutputChars = 4096)
{
if (_disposed)
throw new ObjectDisposedException(nameof(Gemma));

if (_context == IntPtr.Zero)
throw new GemmaException("Gemma native context handle is uninitialized or invalid.");

await UniTask.SwitchToThreadPool();

string result;
try
{
result = GenerateMultimodal(prompt, imageData, imageWidth, imageHeight, callback, maxOutputChars);
}
finally
{
await UniTask.SwitchToMainThread();
}

return result;
}

public void Dispose()
{
if (!_disposed)
Expand All @@ -468,4 +524,4 @@ public void Dispose()
Dispose();
}
}
}
}
Loading