Skip to content

Commit

Permalink
com.virtualmaker.rpc 1.0.0-preview.3 (#3)
Browse files Browse the repository at this point in the history
- Fixes to make WebGL RPC work, add logging

---------

Co-authored-by: Stephen Hodgson <[email protected]>
  • Loading branch information
afarchy and StephenHodgson authored Jul 13, 2024
1 parent b9befdc commit dc5885f
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 32 deletions.
36 changes: 29 additions & 7 deletions VirtualMaker.RPC/Packages/com.virtualmaker.rpc/Runtime/UnityRpc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,16 @@ public void Stop()
{
_cancellationTokenSource?.Cancel();
_cancellationTokenSource?.Dispose();
_cancellationTokenSource = null;
}

public Task<T> CallAsync<T>(string evt, params object[] args)
public Task<T> CallAsync<T>(string func, params object[] args)
{
UnityRpcLog.Info($"Calling function: {func}");

var message = new Message
{
Event = evt,
Event = func,
Args = args.Select(JToken.FromObject).ToArray(),
RpcId = _rpcId++
};
Expand All @@ -84,6 +87,8 @@ public Task<T> CallAsync<T>(string evt, params object[] args)

public void RaiseEvent(string evt, params object[] args)
{
UnityRpcLog.Info($"Raising event: {evt}");

var message = new Message
{
Event = evt,
Expand All @@ -96,6 +101,8 @@ public void RaiseEvent(string evt, params object[] args)

public void SubscribeDelegate(string evt, Delegate callback)
{
UnityRpcLog.Info($"Subscribing to event: {evt}");

if (!_subscriptions.TryGetValue(evt, out var callbacks))
{
callbacks = new List<Delegate>();
Expand All @@ -107,6 +114,8 @@ public void SubscribeDelegate(string evt, Delegate callback)

public void UnsubscribeDelegate(string evt, Delegate callback)
{
UnityRpcLog.Info($"Unsubscribing from event: {evt}");

if (_subscriptions == null)
{
return;
Expand Down Expand Up @@ -158,12 +167,19 @@ public void RemoveRpc<T1, T2, T3, TResult>(string evt, Func<T1, T2, T3, TResult>

private async void ProcessQueue(CancellationToken cancellationToken)
{
while (_transport.ReceiveQueue.TryDequeue(out var message) &&
!cancellationToken.IsCancellationRequested)
while (!cancellationToken.IsCancellationRequested)
{
await Awaiters.UnityMainThread;

if (cancellationToken.IsCancellationRequested) { return; }
if (cancellationToken.IsCancellationRequested)
{
break;
}

if (!_transport.ReceiveQueue.TryDequeue(out var message))
{
continue;
}

try
{
Expand All @@ -173,15 +189,18 @@ private async void ProcessQueue(CancellationToken cancellationToken)
{
if (_rpcs == null || !_rpcs.Remove(parsed.ResponseId.Value, out var callback))
{
UnityRpcLog.Error($"No response callback found for RPC ID: {parsed.ResponseId}");
continue;
}

UnityRpcLog.Info($"Calling response callback for RPC ID {parsed.ResponseId} with value {parsed.Args[0]}");
callback(parsed.Args[0]);
continue;
}

if (_subscriptions == null || !_subscriptions.TryGetValue(parsed.Event, out var callbacks))
{
UnityRpcLog.Info($"No subscribers for event {parsed.Event}");
continue;
}

Expand All @@ -200,6 +219,7 @@ private async void ProcessQueue(CancellationToken cancellationToken)
args[i] = arg.ToObject(parameter.ParameterType);
}

UnityRpcLog.Info($"Calling subscriber with for event {parsed.Event} with RPC ID {parsed.RpcId} args {string.Join(", ", args)}");
var result = callback.DynamicInvoke(args);

if (result == null) { continue; }
Expand All @@ -211,18 +231,20 @@ private async void ProcessQueue(CancellationToken cancellationToken)
ResponseId = parsed.RpcId
};

UnityRpcLog.Info($"Responding to {parsed.Event} with RPC ID {parsed.RpcId} with value {result}");

var json = JsonConvert.SerializeObject(response);
_transport.SendMessage(json);
}
catch (Exception e)
{
Debug.LogException(e);
UnityRpcLog.Exception(e);
}
}
}
catch (Exception e)
{
Debug.LogException(e);
UnityRpcLog.Exception(e);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Licensed under the MIT License. See LICENSE in the project root for license information.

import { writable } from "svelte/store";
import { get, writable } from "svelte/store";

interface UnityRpcMessage {
event: string;
Expand All @@ -22,8 +22,7 @@ class UnityRpc {
this.rpcId = 1;
this.eventHandlers = {};
this.rpcs = {};
this.window.addEventListener('merciv-unity-to-js', this.onUnityMessage.bind(this) as EventListener);
this.started.set(true);
this.window.addEventListener('unity-to-js', this.onUnityMessage.bind(this) as EventListener);
}

public async call<T>(event: string, ...args: any[]): Promise<T> {
Expand Down Expand Up @@ -59,13 +58,18 @@ class UnityRpc {
}

private send(message: UnityRpcMessage) {
const event = new CustomEvent('merciv-js-to-unity', { detail: JSON.stringify(message) });
const event = new CustomEvent('js-to-unity', { detail: JSON.stringify(message) });
this.window?.dispatchEvent(event);
}

private onUnityMessage(event: CustomEvent<any>) { // Update the type of the event parameter
const customEvent = event as CustomEvent<any>;

if (!get(this.started) && customEvent.detail === 'unity-ready') {
this.started.set(true);
return;
}

const message = JSON.parse(customEvent.detail);

if (message['response-id']) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using UnityEngine;

namespace VirtualMaker.RPC
{
internal static class UnityRpcLog
{
[System.Diagnostics.Conditional("UNITY_RPC_DEBUG")]
public static void Info(string message)
{
Debug.Log($"[UnityRpc] {message}");
}

public static void Error(string message)
{
Debug.LogError($"[UnityRpc] {message}");
}

public static void Exception(Exception exception)
{
Debug.LogException(exception);
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Collections.Concurrent;
using UnityEngine;

namespace VirtualMaker.RPC
{
public class UnityRpcTransportNone : IUnityRpcTransport
{
public ConcurrentQueue<string> ReceiveQueue { get; } = new();

public void SendMessage(string message)
{
}

private void OnMessageInstance(string message)
{
}
}
}
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System.Collections.Concurrent;
using UnityEngine;

namespace VirtualMaker.RPC
{
public class UnityRpcTransportNone : IUnityRpcTransport
{
public ConcurrentQueue<string> ReceiveQueue { get; } = new();

public void SendMessage(string message)
{
}

private void OnMessageInstance(string message)
{
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,13 @@ public static void OnMessage(string message)

public void SendMessage(string message)
{
UnityRpcLog.Info($"[UnityRpcTransportWebGL] Send: {message}");
UnityRpcTransportWebGLSend(message);
}

private void OnMessageInstance(string message)
{
UnityRpcLog.Info($"[UnityRpcTransportWebGL] Receive: {message}");
ReceiveQueue.Enqueue(message);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ const UnityRpcTransportWebGL = {
_free(buffer);
}
});

window.dispatchEvent(new CustomEvent('unity-to-js', { detail: 'unity-ready' }));
},

UnityRpcTransportWebGLSend: function(data) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"displayName": "VirtualMaker.RPC",
"description": "A Bidirectional RPC package for Unity (UPM)",
"keywords": [],
"version": "1.0.0-preview.1",
"version": "1.0.0-preview.3",
"unity": "2021.3",
"documentationUrl": "https://github.com/virtual-maker-net/com.virtualmaker.rpc#documentation",
"changelogUrl": "https://github.com/virtual-maker-net/com.virtualmaker.rpc/releases",
Expand Down

0 comments on commit dc5885f

Please sign in to comment.