-
Notifications
You must be signed in to change notification settings - Fork 3
/
OscInputPlugin.cs
100 lines (83 loc) · 2.85 KB
/
OscInputPlugin.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using OscCore;
using OscCore.Address;
using System;
using System.Collections.Generic;
using Warudo.Core.Attributes;
using Warudo.Core.Plugins;
[PluginType(Id = "com.barinzaya.oscinput", Name = "OSC Input", Version = "0.2.5", Author = "Barinzaya", Description = "Adds an On OSC Message node.",
NodeTypes = new[] { typeof(OscInputNode) })]
public class OscInputPlugin : Plugin {
public const int OSC_SERVER_PORT = 19190;
private OscListener listener;
public delegate void OscMessageHandler(OscMessage message);
private Dictionary<string, HashSet<OscMessageHandler>> handlers = new();
protected override void OnCreate() {
base.OnCreate();
listener = new(OSC_SERVER_PORT);
}
protected override void OnDestroy() {
listener.Dispose();
base.OnDestroy();
}
public override void OnPreUpdate() {
base.OnPreUpdate();
while (listener.TryGetPacket(out var packet)) {
DispatchPacket(packet);
}
}
public bool AddHandler(string address, OscMessageHandler action) {
HashSet<OscMessageHandler> addressHandlers;
if (!handlers.TryGetValue(address, out addressHandlers)) {
addressHandlers = new();
handlers[address] = addressHandlers;
}
return addressHandlers.Add(action);
}
public bool RemoveHandler(string address, OscMessageHandler action) {
HashSet<OscMessageHandler> addressHandlers;
if (!handlers.TryGetValue(address, out addressHandlers)) {
return false;
}
var result = addressHandlers.Remove(action);
if (result && addressHandlers.Count == 0) {
handlers.Remove(address);
}
return result;
}
private void DispatchPacket(OscPacket packet) {
switch (packet) {
case OscBundle bundle:
for (var i = 0; i < bundle.Count; i++) {
DispatchPacket(bundle[i]);
}
break;
case OscMessage message:
DispatchMessage(message);
break;
}
}
private void DispatchMessage(OscMessage message) {
OscAddress address;
try {
address = new(message.Address);
} catch (ArgumentException) {
return;
}
if (address.IsLiteral) {
HashSet<OscMessageHandler> addressHandlers;
if (handlers.TryGetValue(message.Address, out addressHandlers)) {
foreach (var handler in addressHandlers) {
handler(message);
}
}
} else {
foreach (var pair in handlers) {
if (address.Match(pair.Key)) {
foreach (var handler in pair.Value) {
handler(message);
}
}
}
}
}
}