From 5c34066d8ed529b197a94a302754287abed80166 Mon Sep 17 00:00:00 2001 From: Pascal Serrarens Date: Tue, 27 May 2025 15:49:30 +0200 Subject: [PATCH] Code updated (untested) to v0.4 Roboidcontrol --- .../Scripts/Networking/Roboid/BoneThing.cs | 15 + .../Spherical.cs.meta => BoneThing.cs.meta} | 2 +- .../Roboid/ControlCore/.gitlab-ci.yml | 26 - .../Networking/Roboid/ControlCore/Client.cs | 109 -- .../Roboid/ControlCore/Client.cs.meta | 2 - .../Roboid/ControlCore/EchoStream.cs | 173 ---- .../Roboid/ControlCore/EchoStream.cs.meta | 2 - .../Roboid/ControlCore/LowLevelMessages.cs | 72 -- .../Networking/Roboid/ControlCore/Messages.cs | 535 ---------- .../Roboid/ControlCore/Messages.cs.meta | 11 - .../Networking/Roboid/ControlCore/Quat32.cs | 15 - .../Roboid/ControlCore/Quat32.cs.meta | 11 - .../Networking/Roboid/ControlCore/README.md | 93 -- .../Roboid/ControlCore/README.md.meta | 7 - .../Roboid/ControlCore/SiteServer.cs | 66 -- .../Roboid/ControlCore/SiteServer.cs.meta | 2 - .../Roboid/ControlCore/Spherical.cs | 15 - .../Networking/Roboid/HumanoidPlayerRoboid.cs | 935 ++++++++++-------- .../Networking/Roboid/HumanoidThing.cs | 6 + ...Messages.cs.meta => HumanoidThing.cs.meta} | 2 +- ...rolCore.meta => RoboidControl-csharp.meta} | 2 +- .../Scripts/Networking/Roboid/Spherical.cs | 57 -- .../Networking/Roboid/Spherical.cs.meta | 11 - .../Scripts/Networking/Roboid/Thing.cs | 54 - .../Scripts/Networking/Roboid/Thing.cs.meta | 2 - .../Scripts/Networking/Roboid/float16.cs | 258 ----- .../Scripts/Networking/Roboid/float16.cs.meta | 11 - 27 files changed, 546 insertions(+), 1948 deletions(-) create mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/BoneThing.cs rename Runtime/HumanoidControl/Scripts/Networking/Roboid/{ControlCore/Spherical.cs.meta => BoneThing.cs.meta} (83%) delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/.gitlab-ci.yml delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Client.cs delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Client.cs.meta delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/EchoStream.cs delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/EchoStream.cs.meta delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/LowLevelMessages.cs delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Messages.cs delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Messages.cs.meta delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Quat32.cs delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Quat32.cs.meta delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/README.md delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/README.md.meta delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/SiteServer.cs delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/SiteServer.cs.meta delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Spherical.cs create mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/HumanoidThing.cs rename Runtime/HumanoidControl/Scripts/Networking/Roboid/{ControlCore/LowLevelMessages.cs.meta => HumanoidThing.cs.meta} (83%) rename Runtime/HumanoidControl/Scripts/Networking/Roboid/{ControlCore.meta => RoboidControl-csharp.meta} (77%) delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/Spherical.cs delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/Spherical.cs.meta delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/Thing.cs delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/Thing.cs.meta delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/float16.cs delete mode 100644 Runtime/HumanoidControl/Scripts/Networking/Roboid/float16.cs.meta diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/BoneThing.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/BoneThing.cs new file mode 100644 index 0000000..a5e2570 --- /dev/null +++ b/Runtime/HumanoidControl/Scripts/Networking/Roboid/BoneThing.cs @@ -0,0 +1,15 @@ +using Passer.Humanoid; + +namespace RoboidControl +{ + + public class BoneThing : Thing + { + protected HumanoidTarget.TargetedBone bone; + + public BoneThing(HumanoidTarget.TargetedBone bone) + { + this.bone = bone; + } + } +} \ No newline at end of file diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Spherical.cs.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/BoneThing.cs.meta similarity index 83% rename from Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Spherical.cs.meta rename to Runtime/HumanoidControl/Scripts/Networking/Roboid/BoneThing.cs.meta index 5ba10b9..3724fd7 100644 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Spherical.cs.meta +++ b/Runtime/HumanoidControl/Scripts/Networking/Roboid/BoneThing.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 33f05ee51ff6f7042b3e22723bcfc4f5 +guid: a87af0c7c5ff3ac468fc4f1c5997a2da MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/.gitlab-ci.yml b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/.gitlab-ci.yml deleted file mode 100644 index e1ab762..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/.gitlab-ci.yml +++ /dev/null @@ -1,26 +0,0 @@ -# You can override the included template(s) by including variable overrides -# SAST customization: https://docs.gitlab.com/ee/user/application_security/sast/#customizing-the-sast-settings -# Secret Detection customization: https://docs.gitlab.com/ee/user/application_security/secret_detection/pipeline/#customization -# Dependency Scanning customization: https://docs.gitlab.com/ee/user/application_security/dependency_scanning/#customizing-the-dependency-scanning-settings -# Container Scanning customization: https://docs.gitlab.com/ee/user/application_security/container_scanning/#customizing-the-container-scanning-settings -# Note that environment variables can be set in several places -# See https://docs.gitlab.com/ee/ci/variables/#cicd-variable-precedence -stages: -- build -- test -- deploy -- review -- dast -- staging -- canary -- production -- incremental rollout 10% -- incremental rollout 25% -- incremental rollout 50% -- incremental rollout 100% -- performance -- cleanup -sast: - stage: test -include: -- template: Auto-DevOps.gitlab-ci.yml diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Client.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Client.cs deleted file mode 100644 index 27b474d..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Client.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System.Collections.Generic; -using System.Collections.Concurrent; -using System.Net.Sockets; -using System.IO; - -namespace Passer.Control { - - public class Client { - //public ConnectionMethod connection; - public UdpClient udpClient; - public string ipAddress; - public int port; - public Stream dataStream; - - public byte networkId = 0; - - public readonly ConcurrentQueue messageQueue = new(); - - public static Client GetClient(string ipAddress, int port) { - foreach (Client c in clients) { - if (c.ipAddress == ipAddress && c.port == port) - return c; - } - return null; - } - static public List clients = new List(); - - public Client(UdpClient udpClient, int port) { - this.udpClient = udpClient; - this.ipAddress = null; - this.port = port; - this.dataStream = new EchoStream(); - clients.Add(this); - } - - public virtual void ProcessMessages() { - while (this.messageQueue.TryDequeue(out IMessage msg)) - ProcessMessage(msg); - } - - public void ProcessMessage(IMessage msg) { - switch (msg) { - case ClientMsg clientMsg: - ProcessClient(clientMsg); - break; - case NetworkIdMsg networkId: - ProcessNetworkId(networkId); - break; - case InvestigateMsg investigate: - ProcessInvestigate(investigate); - break; - case ThingMsg thing: - ProcessThing(thing); - break; - case NameMsg name: - UnityEngine.Debug.Log($"Name [{name.networkId}/{name.thingId}] {name.name}"); - ProcessName(name); - break; - case ModelUrlMsg modelUrl: - ProcessModelUrl(modelUrl); - break; - case PoseMsg pose: - ProcessPose(pose); - break; - case CustomMsg custom: - ProcessCustom(custom); - break; - case TextMsg text: - ProcessText(text); - break; - case DestroyMsg destroy: - ProcessDestroy(destroy); - break; - default: - return; - } - ForwardMessage(msg); - } - - protected virtual void ProcessClient(ClientMsg client) { } - - protected virtual void ProcessNetworkId(NetworkIdMsg networkId) { } - - protected virtual void ProcessInvestigate(InvestigateMsg investigate) { } - - protected virtual void ProcessThing(ThingMsg thing) { } - - protected virtual void ProcessName(NameMsg name) { } - - protected virtual void ProcessModelUrl(ModelUrlMsg modelUrl) { } - - protected virtual void ProcessPose(PoseMsg pose) { } - - protected virtual void ProcessCustom(CustomMsg custom) { } - - protected virtual void ProcessText(TextMsg text) { } - - protected virtual void ProcessDestroy(DestroyMsg destroy) { } - - private void ForwardMessage(IMessage msg) { - foreach (Client client in Client.clients) { - if (client == this) - continue; - //UnityEngine.Debug.Log($"---> {client.ipAddress}"); - IMessage.SendMsg(client, msg); - } - } - } -} \ No newline at end of file diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Client.cs.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Client.cs.meta deleted file mode 100644 index c346934..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Client.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: db9cd79cff119a9438110ead000031c3 \ No newline at end of file diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/EchoStream.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/EchoStream.cs deleted file mode 100644 index c9ae949..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/EchoStream.cs +++ /dev/null @@ -1,173 +0,0 @@ -using System; -using System.IO; -using System.Threading.Tasks; -using System.Threading; -using System.Collections.Concurrent; - -public class EchoStream : Stream { - public override bool CanTimeout { get; } = true; - public override int ReadTimeout { get; set; } = Timeout.Infinite; - public override int WriteTimeout { get; set; } = Timeout.Infinite; - public override bool CanRead { get; } = true; - public override bool CanSeek { get; } = false; - public override bool CanWrite { get; } = true; - - public bool CopyBufferOnWrite { get; set; } = false; - - private readonly object _lock = new object(); - - // Default underlying mechanism for BlockingCollection is ConcurrentQueue, which is what we want - private readonly BlockingCollection _Buffers; - private int _maxQueueDepth = 10; - - private byte[] m_buffer = null; - private int m_offset = 0; - private int m_count = 0; - - private bool m_Closed = false; - private bool m_FinalZero = false; //after the stream is closed, set to true after returning a 0 for read() - public override void Close() { - m_Closed = true; - - // release any waiting writes - _Buffers.CompleteAdding(); - } - - public bool DataAvailable { - get { - return _Buffers.Count > 0; - } - } - - private long _Length = 0L; - public override long Length { - get { - return _Length; - } - } - - private long _Position = 0L; - public override long Position { - get { - return _Position; - } - set { - throw new NotImplementedException(); - } - } - - public EchoStream() : this(10) { - } - - public EchoStream(int maxQueueDepth) { - _maxQueueDepth = maxQueueDepth; - _Buffers = new BlockingCollection(_maxQueueDepth); - } - - // we override the xxxxAsync functions because the default base class shares state between ReadAsync and WriteAsync, which causes a hang if both are called at once - public new Task WriteAsync(byte[] buffer, int offset, int count) { - return Task.Run(() => Write(buffer, offset, count)); - } - - // we override the xxxxAsync functions because the default base class shares state between ReadAsync and WriteAsync, which causes a hang if both are called at once - public new Task ReadAsync(byte[] buffer, int offset, int count) { - return Task.Run(() => { - return Read(buffer, offset, count); - }); - } - - public override void Write(byte[] buffer, int offset, int count) { - if (m_Closed || buffer.Length - offset < count || count <= 0) - return; - - byte[] newBuffer; - if (!CopyBufferOnWrite && offset == 0 && count == buffer.Length) - newBuffer = buffer; - else { - newBuffer = new byte[count]; - System.Buffer.BlockCopy(buffer, offset, newBuffer, 0, count); - } - if (!_Buffers.TryAdd(newBuffer, WriteTimeout)) - throw new TimeoutException("EchoStream Write() Timeout"); - - _Length += count; - } - - public override int Read(byte[] buffer, int offset, int count) { - if (count == 0) - return 0; - lock (_lock) { - if (m_count == 0 && _Buffers.Count == 0) { - if (m_Closed) { - if (!m_FinalZero) { - m_FinalZero = true; - return 0; - } - else { - return -1; - } - } - - if (_Buffers.TryTake(out m_buffer, ReadTimeout)) { - m_offset = 0; - m_count = m_buffer.Length; - } - else { - if (m_Closed) { - if (!m_FinalZero) { - m_FinalZero = true; - return 0; - } - else { - return -1; - } - } - else { - return 0; - } - } - } - - int returnBytes = 0; - while (count > 0) { - if (m_count == 0) { - if (_Buffers.TryTake(out m_buffer, 0)) { - m_offset = 0; - m_count = m_buffer.Length; - } - else - break; - } - - var bytesToCopy = (count < m_count) ? count : m_count; - System.Buffer.BlockCopy(m_buffer, m_offset, buffer, offset, bytesToCopy); - m_offset += bytesToCopy; - m_count -= bytesToCopy; - offset += bytesToCopy; - count -= bytesToCopy; - - returnBytes += bytesToCopy; - } - - _Position += returnBytes; - - return returnBytes; - } - } - - public override int ReadByte() { - byte[] returnValue = new byte[1]; - return (Read(returnValue, 0, 1) <= 0 ? -1 : (int)returnValue[0]); - } - - public override void Flush() { - } - - public override long Seek(long offset, SeekOrigin origin) { - throw new NotImplementedException(); - } - - public override void SetLength(long value) { - throw new NotImplementedException(); - } -} \ No newline at end of file diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/EchoStream.cs.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/EchoStream.cs.meta deleted file mode 100644 index 063a4f2..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/EchoStream.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 422516a56cbf14d46aaa0b1bc09115bf \ No newline at end of file diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/LowLevelMessages.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/LowLevelMessages.cs deleted file mode 100644 index abeef3a..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/LowLevelMessages.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Passer; - -public class LowLevelMessages { - - public static void SendSpherical(byte[] buffer, ref byte ix, Spherical v) { - SendAngle8(buffer, ref ix, v.horizontal); - SendAngle8(buffer, ref ix, v.vertical); - SendFloat16(buffer, ref ix, new float16(v.distance)); - } - - public static Spherical ReceiveSpherical(byte[] data, ref byte ix) { - float horizontal = ReceiveAngle8(data, ref ix); - float vertical = ReceiveAngle8(data, ref ix); - float distance = ReceiveFloat16(data, ref ix); - Spherical v = new(distance, horizontal, vertical); - return v; - } - - public static void SendQuat32(byte[] buffer, ref byte ix, Quat32 q) { - int qx = (int)(q.x * 127 + 128); - int qy = (int)(q.y * 127 + 128); - int qz = (int)(q.z * 127 + 128); - int qw = (int)(q.w * 255); - if (q.w < 0) { - qx = -qx; - qy = -qy; - qz = -qz; - qw = -qw; - } - - buffer[ix++] = (byte)qx; - buffer[ix++] = (byte)qy; - buffer[ix++] = (byte)qz; - buffer[ix++] = (byte)qw; - } - public static Quat32 ReceiveQuat32(byte[] data, ref byte ix) { - Quat32 q = new( - (data[ix++] - 128.0F) / 127.0F, - (data[ix++] - 128.0F) / 127.0F, - (data[ix++] - 128.0F) / 127.0F, - data[ix++] / 255.0F); - return q; - } - - public static void SendAngle8(byte[] buffer, ref byte ix, float angle) { - // Normalize angle - while (angle >= 180) - angle -= 360; - while (angle < -180) - angle += 360; - buffer[ix++] = (byte)((angle / 360.0f) * 256.0f); - } - - public static float ReceiveAngle8(byte[] data, ref byte ix) { - float value = (data[ix++] * 180) / 128.0F; - return value; - } - - public static void SendFloat16(byte[] data, ref byte ix, float16 f) { - ushort binary = f.GetBinary(); - data[ix++] = (byte)(binary >> 8); - data[ix++] = (byte)(binary & 255); - } - - public static float ReceiveFloat16(byte[] data, ref byte ix) { - ushort value = (ushort)(data[ix++] << 8 | data[ix++]); - float16 f16 = new(); - f16.SetBinary(value); - float f = f16.toFloat(); - return f; - } -} diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Messages.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Messages.cs deleted file mode 100644 index 59439b0..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Messages.cs +++ /dev/null @@ -1,535 +0,0 @@ -using System.IO; -using System.Threading.Tasks; - -namespace Passer.Control { - - public class IMessage { - public IMessage() { } - public IMessage(byte[] buffer) { - Deserialize(buffer); - } - - public virtual byte[] Serialize() { return null; } - public virtual void Deserialize(byte[] buffer) { } - - public static bool SendMsg(Client client, IMessage msg) { - return SendMsg(client, msg.Serialize()); - } - public static bool SendMsg(Client client, byte[] buffer) { - if (client == null || client.ipAddress == null) - return false; - - //UnityEngine.Debug.Log($"Send msg {buffer[0]} to {client.ipAddress}"); - client.udpClient.Send(buffer, buffer.Length, client.ipAddress, client.port); - return true; - } - - public static bool PublishMsg(Client client, IMessage msg) { - return PublishMsg(client, msg.Serialize()); - } - public static bool PublishMsg(Client client, byte[] buffer) { - if (client == null) - return false; - - client.udpClient.Send(buffer, buffer.Length, "127.0.0.1", client.port); - return true; - } - - public static async Task Receive(Stream dataStream, byte packetSize) { - byte[] buffer = new byte[packetSize - 1]; // without msgId - int byteCount = dataStream.Read(buffer, 0, packetSize - 1); - while (byteCount < packetSize - 1) { - // not all bytes have been read, wait and try again - await Task.Delay(1); - byteCount += dataStream.Read(buffer, byteCount, packetSize - 1 - byteCount); - } - return buffer; - } - } - - #region Client - - public class ClientMsg : IMessage { - public const byte Id = 0xA0; - public const byte length = 2; - public byte networkId; - - public ClientMsg(byte networkId) { - this.networkId = networkId; - } - public ClientMsg(byte[] buffer) : base(buffer) { } - - public override byte[] Serialize() { - byte[] buffer = new byte[ClientMsg.length]; - buffer[0] = ClientMsg.Id; - buffer[1] = networkId; - return buffer; - } - public override void Deserialize(byte[] buffer) { - base.Deserialize(buffer); - uint ix = 0; - networkId = buffer[ix]; - } - - public static bool Send(Client client, byte networkId) { - ClientMsg msg = new(networkId); - return SendMsg(client, msg); - } - public static bool Publish(Client client, byte networkId) { - ClientMsg msg = new(networkId); - return PublishMsg(client, msg); - } - public static async Task Receive(Stream dataStream, Client client, byte packetSize) { - if (packetSize != length) - return false; - - byte[] buffer = await Receive(dataStream, packetSize); - ClientMsg msg = new(buffer); - - if (client.networkId == 0) { - client.networkId = (byte)(Client.clients.Count); - NetworkIdMsg.Send(client, client.networkId); - client.messageQueue.Enqueue(msg); - } - else if (msg.networkId == 0) { - NetworkIdMsg.Send(client, client.networkId); - client.messageQueue.Enqueue(msg); - } - - return true; - } - } - - #endregion Client - - #region Network Id - - public class NetworkIdMsg : IMessage { - public const byte Id = 0xA1; - public const byte length = 2; - public byte networkId; - - NetworkIdMsg(byte networkId) { - this.networkId = networkId; - } - NetworkIdMsg(byte[] buffer) : base(buffer) { } - - public override byte[] Serialize() { - byte[] buffer = new byte[NetworkIdMsg.length]; - buffer[0] = NetworkIdMsg.Id; - buffer[1] = this.networkId; - return buffer; - } - public override void Deserialize(byte[] buffer) { - uint ix = 0; - this.networkId = buffer[ix]; - } - - public static bool Send(Client client, byte networkId) { - NetworkIdMsg msg = new(networkId); - return SendMsg(client, msg); - } - public static async Task Receive(Stream dataStream, Client client, byte packetSize) { - if (packetSize != length) - return false; - - byte[] buffer = await Receive(dataStream, packetSize); - NetworkIdMsg msg = new(buffer); - client.messageQueue.Enqueue(msg); - return true; - } - } - - #endregion Network Id - - #region Investigate - - public class InvestigateMsg : IMessage { - public const byte Id = 0x81; - public const byte length = 3; - public byte networkId; - public byte thingId; - - public InvestigateMsg(byte networkId, byte thingId) { - this.networkId = networkId; - this.thingId = thingId; - } - public InvestigateMsg(byte[] buffer) : base(buffer) { } - - public override byte[] Serialize() { - byte[] buffer = new byte[InvestigateMsg.length]; - buffer[0] = InvestigateMsg.Id; - buffer[1] = this.networkId; - buffer[2] = this.thingId; - return buffer; - } - public override void Deserialize(byte[] buffer) { - uint ix = 0; - this.networkId = buffer[ix++]; - this.thingId = buffer[ix++]; - } - - public static bool Send(Client client, byte networkId, byte thingId) { - InvestigateMsg msg = new(networkId, thingId); - return SendMsg(client, msg); - } - public static async Task Receive(Stream dataStream, Client client, byte packetSize) { - if (packetSize != length) - return false; - - byte[] buffer = await Receive(dataStream, packetSize); - InvestigateMsg msg = new(buffer); - client.messageQueue.Enqueue(msg); - return true; - - } - } - - #endregion Investigate - - #region Thing - - public class ThingMsg : IMessage { - public const byte length = 5; - public const byte Id = 0x80; - public byte networkId; - public byte thingId; - public byte thingType; - public byte parentId; - - public ThingMsg(byte networkId, byte thingId, byte thingType, byte parentId) { - this.thingId = thingId; - this.thingType = thingType; - this.parentId = parentId; - } - public ThingMsg(byte[] buffer) : base(buffer) { } - - public override byte[] Serialize() { - byte[] buffer = new byte[ThingMsg.length]; - byte ix = 0; - buffer[ix++] = ThingMsg.Id; - buffer[ix++] = this.networkId; - buffer[ix++] = this.thingId; - buffer[ix++] = this.thingType; - buffer[ix] = this.parentId; - return buffer; - } - public override void Deserialize(byte[] buffer) { - uint ix = 0; - this.networkId = buffer[ix++]; - this.thingId = buffer[ix++]; - this.thingType = buffer[ix++]; - this.parentId = buffer[ix]; - } - - public static bool Send(Client client, byte thingId, byte thingType, byte parentId) { - ThingMsg msg = new(client.networkId, thingId, thingType, parentId); - return SendMsg(client, msg); - } - public static async Task Receive(Stream dataStream, Client client, byte packetSize) { - if (packetSize != length) - return false; - - byte[] buffer = await Receive(dataStream, packetSize); - ThingMsg msg = new(buffer); - - // Do no process poses with nwid == 0 (== local) - //if (msg.networkId == 0) - // return true; - - client.messageQueue.Enqueue(msg); - return true; - } - } - - #endregion Thing - - #region Name - - public class NameMsg : IMessage { - public const byte Id = 0x91; // 145 - public const byte length = 4; - public byte networkId; - public byte thingId; - public byte len; - public string name; - - public NameMsg(byte networkId, byte thingId, string name) { - this.networkId = networkId; - this.thingId = thingId; - this.name = name; - } - public NameMsg(byte[] buffer) : base(buffer) { } - - public override byte[] Serialize() { - byte[] buffer = new byte[length + this.name.Length]; - byte ix = 0; - buffer[ix++] = NameMsg.Id; - buffer[ix++] = this.networkId; - buffer[ix++] = this.thingId; - buffer[ix++] = (byte)this.name.Length; - for (int nameIx = 0; nameIx < this.name.Length; nameIx++, ix++) - buffer[ix] = (byte)this.name[nameIx]; - return buffer; - } - public override void Deserialize(byte[] buffer) { - byte ix = 0; - this.networkId = buffer[ix++]; - this.thingId = buffer[ix++]; - int strlen = buffer[ix++]; - this.name = System.Text.Encoding.UTF8.GetString(buffer, (int)ix, strlen); - } - - public static bool Send(Client client, byte networkId, byte thingId, string name) { - NameMsg msg = new(networkId, thingId, name); - return SendMsg(client, msg); - } - public static async Task Receive(Stream dataStream, Client client, byte packetSize) { - byte[] buffer = await Receive(dataStream, packetSize); - NameMsg msg = new(buffer); - - client.messageQueue.Enqueue(msg); - return true; - } - } - - #endregion - - #region Model URL - - public class ModelUrlMsg : IMessage { - public const byte Id = 0x90; // (144) Model URL - public byte networkId; - public byte thingId; - public Spherical position; - public float scale; - public string url; - - public ModelUrlMsg(byte networkId, byte thingId, string url, float scale = 1) { - this.networkId = networkId; - this.thingId = thingId; - this.url = url; - this.scale = scale; - this.position = Spherical.zero; - } - public ModelUrlMsg(byte[] buffer) : base(buffer) { } - - public override byte[] Serialize() { - byte[] buffer = new byte[this.url.Length + 6]; - byte ix = 0; - buffer[ix++] = ModelUrlMsg.Id; - buffer[ix++] = this.networkId; - buffer[ix++] = this.thingId; // Thing Id - LowLevelMessages.SendFloat16(buffer, ref ix, new float16(1.0f)); - - buffer[ix++] = (byte)url.Length; - for (int urlIx = 0; urlIx < this.url.Length; urlIx++, ix++) - buffer[ix] = (byte)url[urlIx]; - return buffer; - } - public override void Deserialize(byte[] buffer) { - byte ix = 0; - this.networkId = buffer[ix++]; - this.thingId = buffer[ix++]; - this.scale = LowLevelMessages.ReceiveFloat16(buffer, ref ix); - int strlen = buffer[ix++]; - url = System.Text.Encoding.UTF8.GetString(buffer, (int)ix, strlen); - } - - public static bool Send(Client client, byte networkId, byte thingId, string modelUrl) { - ModelUrlMsg msg = new(networkId, thingId, modelUrl); - return SendMsg(client, msg); - } - public static async Task Receive(Stream dataStream, Client client, byte packetSize) { - byte[] buffer = await Receive(dataStream, packetSize); - ModelUrlMsg msg = new(buffer); - client.messageQueue.Enqueue(msg); - return true; - } - } - - #endregion Model URL - - #region Pose - - public class PoseMsg : IMessage { - public const byte Id = 0x10; - public const byte length = 4 + 4 + 4; - public byte networkId; - public byte thingId; - - public byte poseType; - public const byte Pose_Position = 0x01; - public const byte Pose_Orientation = 0x02; - - public Spherical position; - public Quat32 orientation; - - public PoseMsg(byte networkId, byte thingId, Spherical position, Quat32 orientation) { - this.networkId = networkId; - this.thingId = thingId; - this.position = position; - this.orientation = orientation; - this.poseType = 0; - if (this.position != null) - this.poseType |= Pose_Position; - else - this.position = new Spherical(0, 0, 0); - if (this.orientation != null) - this.poseType |= Pose_Orientation; - else - this.orientation = new Quat32(0, 0, 0, 1); - } - public PoseMsg(byte[] buffer) : base(buffer) { } - - public override byte[] Serialize() { - byte[] buffer = new byte[PoseMsg.length]; - byte ix = 0; - buffer[ix++] = PoseMsg.Id; - buffer[ix++] = this.networkId; - buffer[ix++] = this.thingId; - buffer[ix++] = this.poseType; - - LowLevelMessages.SendSpherical(buffer, ref ix, this.position); - LowLevelMessages.SendQuat32(buffer, ref ix, this.orientation); - return buffer; - } - public override void Deserialize(byte[] buffer) { - byte ix = 0; - this.networkId = buffer[ix++]; - this.thingId = buffer[ix++]; - this.poseType = buffer[ix++]; - - //if ((poseType & Pose_Position) != 0) - this.position = LowLevelMessages.ReceiveSpherical(buffer, ref ix); - //if ((poseType & Pose_Orientation) != 0) { - this.orientation = LowLevelMessages.ReceiveQuat32(buffer, ref ix); - } - - public static bool Send(Client client, byte thingId, Spherical position, Quat32 orientation) { - PoseMsg msg = new(client.networkId, thingId, position, orientation); - return SendMsg(client, msg); - } - public static async Task Receive(Stream dataStream, Client client, byte packetSize) { - if (packetSize != length) - return false; - - byte[] buffer = await Receive(dataStream, packetSize); - PoseMsg msg = new(buffer); - - // Do no process poses with nwid == 0 (== local) - if (msg.networkId == 0) - return true; - - client.messageQueue.Enqueue(msg); - return true; - } - } - - #endregion Pose - - #region Custom - - public class CustomMsg : IMessage { - public const byte Id = 0xB1; - public byte networkId; - public byte thingId; - public byte[] bytes; - - public CustomMsg(byte[] buffer) : base(buffer) { } - public CustomMsg(byte networkId, byte thingId, byte[] bytes) : base() { - this.networkId = networkId; - this.thingId = thingId; - this.bytes = bytes; - } - - public override byte[] Serialize() { - byte[] buffer = new byte[3 + this.bytes.Length]; - byte ix = 0; - buffer[ix++] = CustomMsg.Id; - buffer[ix++] = this.networkId; - buffer[ix++] = this.thingId; - //buffer[ix++] = (byte)bytes.Length; - foreach (byte b in bytes) - buffer[ix++] = b; - - return buffer; - } - public override void Deserialize(byte[] buffer) { - byte ix = 0; - this.networkId = buffer[ix++]; - this.thingId = buffer[ix++]; - byte length = (byte)(buffer.Length - ix);//buffer[ix++]; - this.bytes = new byte[length]; - for (uint bytesIx = 0; bytesIx < length; bytesIx++) - this.bytes[bytesIx] = buffer[ix++]; - } - - public static void Send(Client client, byte thingId, byte[] bytes) { - CustomMsg msg = new(client.networkId, thingId, bytes); - SendMsg(client, msg); - } - public static async Task Receive(Stream dataStream, Client client, byte packetSize) { - byte[] buffer = await Receive(dataStream, packetSize); - CustomMsg msg = new(buffer); - client.messageQueue.Enqueue(msg); - return true; - } - } - - #endregion Custom - - #region Text - - public class TextMsg : IMessage { - public const byte Id = 0xB0; - public string text; - - public TextMsg(byte[] buffer) : base(buffer) { } - public override void Deserialize(byte[] buffer) { - uint ix = 0; - uint strlen = buffer[ix++]; - this.text = System.Text.Encoding.UTF8.GetString(buffer, (int)ix, (int)strlen); - } - - public static async Task Receive(Stream dataStream, Client client, byte packetSize) { - byte[] buffer = await Receive(dataStream, packetSize); - TextMsg msg = new(buffer); - - client.messageQueue.Enqueue(msg); - return true; - } - } - - #endregion - - #region Destroy - - public class DestroyMsg : IMessage { - public const byte Id = 0x20; - public const byte length = 2; - public byte networkId; - public byte thingId; - - public DestroyMsg(byte[] buffer) : base(buffer) { } - - public override void Deserialize(byte[] buffer) { - this.networkId = buffer[0]; - this.thingId = buffer[1]; - } - - public static async Task Receive(Stream dataStream, Client client, byte packetSize) { - if (packetSize != length) - return false; - - byte[] buffer = await Receive(dataStream, packetSize); - DestroyMsg msg = new(buffer); - - client.messageQueue.Enqueue(msg); - return true; - } - } - - - #endregion Destroy -} diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Messages.cs.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Messages.cs.meta deleted file mode 100644 index 60016bd..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Messages.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: d3f26f22a5422a44997b39a1844ab2ad -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Quat32.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Quat32.cs deleted file mode 100644 index dc6cbc4..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Quat32.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Passer { - public class Quat32 { - public float x; - public float y; - public float z; - public float w; - - public Quat32(float x, float y, float z, float w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - } -} \ No newline at end of file diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Quat32.cs.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Quat32.cs.meta deleted file mode 100644 index c3f81a4..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Quat32.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 96aa3cf18eaeb574d9265704d68000da -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/README.md b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/README.md deleted file mode 100644 index 8cff667..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/README.md +++ /dev/null @@ -1,93 +0,0 @@ -# ControlCore - - - -## Getting started - -To make it easy for you to get started with GitLab, here's a list of recommended next steps. - -Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! - -## Add your files - -- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files -- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - -``` -cd existing_repo -git remote add origin http://gitlab.passervr.com/passer/csharp/controlcore.git -git branch -M main -git push -uf origin main -``` - -## Integrate with your tools - -- [ ] [Set up project integrations](http://gitlab.passervr.com/passer/csharp/controlcore/-/settings/integrations) - -## Collaborate with your team - -- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) -- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) -- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) -- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/) -- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html) - -## Test and Deploy - -Use the built-in continuous integration in GitLab. - -- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) -- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) -- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) -- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) -- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) - -*** - -# Editing this README - -When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template. - -## Suggestions for a good README - -Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - -## Name -Choose a self-explaining name for your project. - -## Description -Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. - -## Badges -On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge. - -## Visuals -Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. - -## Installation -Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. - -## Usage -Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - -## Support -Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. - -## Roadmap -If you have ideas for releases in the future, it is a good idea to list them in the README. - -## Contributing -State if you are open to contributions and what your requirements are for accepting them. - -For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - -You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. - -## Authors and acknowledgment -Show your appreciation to those who have contributed to the project. - -## License -For open source projects, say how it is licensed. - -## Project status -If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/README.md.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/README.md.meta deleted file mode 100644 index f345b71..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/README.md.meta +++ /dev/null @@ -1,7 +0,0 @@ -fileFormatVersion: 2 -guid: 3b79b5b373e9ced4abe72eb4d2f83c6a -TextScriptImporter: - externalObjects: {} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/SiteServer.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/SiteServer.cs deleted file mode 100644 index 57460f3..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/SiteServer.cs +++ /dev/null @@ -1,66 +0,0 @@ -using System.IO; -using System.Threading.Tasks; - -namespace Passer.Control { - - public static class SiteServer { - - public static async Task ReceiveData(Stream dataStream, Client client) { - while (true) { - byte packetSize = (byte)dataStream.ReadByte(); - if (packetSize != 0xFF) - await ReceiveData(dataStream, client, packetSize); - // else timeout - } - } - - public static async Task ReceiveData(Stream dataStream, Client client, byte packetSize) { - byte msgId = (byte)dataStream.ReadByte(); - if (msgId == 0xFF) { - // Timeout - return; - } - - //UnityEngine.Debug.Log($"R {msgId} from {client.ipAddress}"); - bool result = false; - switch (msgId) { - case ClientMsg.Id: // 0xA0 / 160 - result = await ClientMsg.Receive(dataStream, client, packetSize); - break; - case NetworkIdMsg.Id: // 0xA1 / 161 - result = await NetworkIdMsg.Receive(dataStream, client, packetSize); - break; - case InvestigateMsg.Id: // 0x81 - result = await InvestigateMsg.Receive(dataStream, client, packetSize); - break; - case ThingMsg.Id: // 0x80 / 128 - result = await ThingMsg.Receive(dataStream, client, packetSize); - break; - case NameMsg.Id: // 0x91 / 145 - result = await NameMsg.Receive(dataStream, client, packetSize); - break; - case ModelUrlMsg.Id: // 0x90 / 144 - result = await ModelUrlMsg.Receive(dataStream, client, packetSize); - break; - case PoseMsg.Id: // 0x10 / 16 - result = await PoseMsg.Receive(dataStream, client, packetSize); - break; - case CustomMsg.Id: // 0xB1 / 177 - result = await CustomMsg.Receive(dataStream, client, packetSize); - break; - case TextMsg.Id: // 0xB0 / 176 - result = await TextMsg.Receive(dataStream, client, packetSize); - break; - case DestroyMsg.Id: // 0x20 / 32 - result = await DestroyMsg.Receive(dataStream, client, packetSize); - break; - default: - break; - } - if (result == false) { - packetSize = msgId; // skip 1 byte, msgId is possibly a packet size byte - await ReceiveData(dataStream, client, packetSize); - } - } - } -} \ No newline at end of file diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/SiteServer.cs.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/SiteServer.cs.meta deleted file mode 100644 index 02fd171..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/SiteServer.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: 53345abb9310d344baa67c19a8d8249f \ No newline at end of file diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Spherical.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Spherical.cs deleted file mode 100644 index 3ecb663..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/Spherical.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Passer { - public class Spherical { - public float distance; - public float horizontal; - public float vertical; - - public static Spherical zero = new(0, 0, 0); - - public Spherical(float distance, float horizontal, float vertical) { - this.distance = distance; - this.horizontal = horizontal; - this.vertical = vertical; - } - } -} \ No newline at end of file diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/HumanoidPlayerRoboid.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/HumanoidPlayerRoboid.cs index f1a1a85..b32424b 100644 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/HumanoidPlayerRoboid.cs +++ b/Runtime/HumanoidControl/Scripts/Networking/Roboid/HumanoidPlayerRoboid.cs @@ -5,39 +5,52 @@ using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using UnityEngine; -//using GLTFast; +using RoboidControl.Unity; + #if hNW_ROBOID -using Passer.Control; -using Passer.LinearAlgebra; +using RoboidControl; +using LinearAlgebra; -namespace Passer.Humanoid { +namespace Passer.Humanoid +{ - public partial class HumanoidPlayer : MonoBehaviour, IHumanoidNetworking { //}, ISiteServer { + public partial class HumanoidPlayer : MonoBehaviour, IHumanoidNetworking + { //}, ISiteServer { [SerializeField] protected float _sendRate = 25; - public float sendRate { + public float sendRate + { get { return _sendRate; } } [SerializeField] protected bool _createLocalRemotes = false; - public bool createLocalRemotes { + public bool createLocalRemotes + { get { return _createLocalRemotes; } set { _createLocalRemotes = value; } } public int sitePort = 7681; public string siteAddress = "127.0.0.1"; - protected UdpClient udpClient; - protected IPEndPoint endPoint; - protected object obj; - protected AsyncCallback receiveCallback; - protected HumanoidClient client; - protected Stream dataStream; + // protected UdpClient udpClient; + // protected IPEndPoint endPoint; + // protected object obj; + // protected AsyncCallback receiveCallback; + //protected HumanoidClient client; + //protected Stream dataStream; + + protected HumanoidParticipant participant; + // This should be one core thing per humanoid in the end + protected RoboidControl.Thing core; + + protected HumanoidControl humanoid; // we only support one humanoid ATM + protected RoboidControl.Thing headThing; + //public byte networkId; @@ -55,33 +68,42 @@ namespace Passer.Humanoid { public void Send(Vector3 v) { } public void Send(Quaternion q) { } - public bool ReceiveBool() { + public bool ReceiveBool() + { return false; } - public byte ReceiveByte() { + public byte ReceiveByte() + { return 0; } - public int ReceiveInt() { + public int ReceiveInt() + { return 0; } - public float ReceiveFloat() { + public float ReceiveFloat() + { return 0; } - public Vector3 ReceiveVector3() { + public Vector3 ReceiveVector3() + { return Vector3.zero; } - public Quaternion ReceiveQuaternion() { + public Quaternion ReceiveQuaternion() + { return Quaternion.identity; } - public ulong GetObjectIdentity(GameObject obj) { + public ulong GetObjectIdentity(GameObject obj) + { return 0; } - public GameObject GetGameObject(ulong objIdentity) { + public GameObject GetGameObject(ulong objIdentity) + { return this.gameObject; } - public void InstantiateHumanoid(HumanoidControl humanoid) { + public void InstantiateHumanoid(HumanoidControl humanoid) + { if (debug <= HumanoidNetworking.DebugLevel.Info) DebugLog("Send Instantiate Humanoid " + humanoid.humanoidId); @@ -92,7 +114,8 @@ namespace Passer.Humanoid { public void DestroyHumanoid(HumanoidControl humanoid) { } public void Grab(HandTarget handTarget, GameObject obj, bool rangeCheck, HandTarget.GrabType grabType = HandTarget.GrabType.HandGrab) { } public void LetGo(HandTarget handTarget) { } - public void ChangeAvatar(HumanoidControl humanoid, string avatarPrefabName, string possessionLocation = null) { + public void ChangeAvatar(HumanoidControl humanoid, string avatarPrefabName, string possessionLocation = null) + { if (debug <= HumanoidNetworking.DebugLevel.Info) Debug.Log(humanoid.nwId + ": Change Avatar: " + avatarPrefabName); @@ -105,13 +128,16 @@ namespace Passer.Humanoid { public void ReenableNetworkSync(GameObject obj) { } public void DisableNetworkSync(GameObject obj) { } - public void DebugLog(string s) { + public void DebugLog(string s) + { Debug.Log(s); } - public void DebugWarning(string s) { + public void DebugWarning(string s) + { Debug.LogWarning(s); } - public void DebugError(string s) { + public void DebugError(string s) + { Debug.LogError(s); } @@ -128,14 +154,18 @@ namespace Passer.Humanoid { #endregion Dummy Interface - public class HumanoidClient : Client { + public class HumanoidParticipant : RoboidControl.ParticipantUDP + { readonly HumanoidPlayer player; - public HumanoidClient(UdpClient udpClient, string ipAddress, int port, HumanoidPlayer player) : base(udpClient, port) { + public HumanoidParticipant(string ipAddress, int port, HumanoidPlayer player) : base(ipAddress, port) + { this.player = player; } - protected override void ProcessNetworkId(NetworkIdMsg msg) { + /* + protected override void Process(Participant sender, NetworkIdMsg msg) + { Debug.Log($"NetworkId [{msg.networkId}]"); if (this.networkId == msg.networkId) return; @@ -144,24 +174,24 @@ namespace Passer.Humanoid { player.ProcessNetworkId(this, msg); } - protected override void ProcessInvestigate(InvestigateMsg msg) { - Debug.Log($"Investigate [{msg.networkId}/{msg.thingId}]"); - Thing thing = Thing.GetThing(msg.networkId, msg.thingId); - Thing parentThing = thing.transform.parent.GetComponentInParent(); - if (parentThing != null) - ThingMsg.Send(this, thing.networkId, thing.thingId, thing.objectType, parentThing.thingId); - else - ThingMsg.Send(this, thing.networkId, thing.thingId, thing.objectType, 0); - NameMsg.Send(this, thing.networkId, thing.thingId, thing.name); - if (thing.modelUrl != null) - ModelUrlMsg.Send(this, thing.networkId, thing.thingId, thing.modelUrl); + protected override void Process(Participant sender, InvestigateMsg msg) { + // Debug.Log($"Investigate [{msg.networkId}/{msg.thingId}]"); + // Thing thing = Thing.GetThing(msg.networkId, msg.thingId); + // Thing parentThing = thing.transform.parent.GetComponentInParent(); + // if (parentThing != null) + // ThingMsg.Send(this, thing.networkId, thing.thingId, thing.objectType, parentThing.thingId); + // else + // ThingMsg.Send(this, thing.networkId, thing.thingId, thing.objectType, 0); + // NameMsg.Send(this, thing.networkId, thing.thingId, thing.name); + // if (thing.modelUrl != null) + // ModelUrlMsg.Send(this, thing.networkId, thing.thingId, thing.modelUrl); } - protected override void ProcessThing(ThingMsg thing) { + protected override void Process(Participant sender, ThingMsg thing) { player.ProcessThing(this, thing); } - protected override void ProcessName(NameMsg msg) { + protected override void Process(Participant sender, NameMsg msg) { Debug.Log($"Name [{msg.networkId}/{msg.thingId}] {msg.name}"); Thing thing = Thing.GetThing(msg.networkId, msg.thingId); if (thing == null) { @@ -171,21 +201,21 @@ namespace Passer.Humanoid { thing.gameObject.name = msg.name; } - protected override void ProcessModelUrl(ModelUrlMsg msg) { + protected override void Process(Participant sender, ModelUrlMsg msg) { Debug.Log($"Model [{msg.networkId}/{msg.thingId}] {msg.url}"); - int ix = msg.url.LastIndexOf("."); - if (ix < 0) - return; + // int ix = msg.url.LastIndexOf("."); + // if (ix < 0) + // return; - string extension = msg.url.Substring(msg.url.LastIndexOf(".")); - string extension3 = extension.Substring(0, 4); - string extension4 = extension.Substring(0, 5); - if (extension4 == ".gltf" || extension3 == ".glb") { - player.ProcessGltfModel(msg); - } + // string extension = msg.url.Substring(msg.url.LastIndexOf(".")); + // string extension3 = extension.Substring(0, 4); + // string extension4 = extension.Substring(0, 5); + // if (extension4 == ".gltf" || extension3 == ".glb") { + // player.ProcessGltfModel(msg); + // } } - protected override void ProcessPose(PoseMsg msg) { + protected override void Process(Participant sender, PoseMsg msg) { Thing thing = Thing.allThings.Find(thing => thing.networkId == msg.networkId && thing.thingId == msg.thingId); if (thing == null) { Debug.Log($"Pose for unknown thing [{msg.networkId}/{msg.thingId}] -> create thing"); @@ -200,74 +230,88 @@ namespace Passer.Humanoid { thing.transform.localRotation = ToQuaternion(msg.orientation); } } + */ } - protected virtual void Awake() { + protected virtual void Awake() + { mInstance = this; - endPoint = new IPEndPoint(IPAddress.Any, sitePort + 3); - udpClient = new UdpClient(endPoint); - receiveCallback = new System.AsyncCallback(result => ReceiveUDP(client, result)); - udpClient.BeginReceive(receiveCallback, obj); - client = new HumanoidClient(udpClient, siteAddress, sitePort, this); + Console.SetOut(new UnityLogWriter()); + this.participant = new HumanoidParticipant(siteAddress, sitePort, this); + + // endPoint = new IPEndPoint(IPAddress.Any, sitePort + 3); + // udpClient = new UdpClient(endPoint); + // receiveCallback = new System.AsyncCallback(result => ReceiveUDP(client, result)); + // udpClient.BeginReceive(receiveCallback, obj); + // client = new HumanoidClient(udpClient, siteAddress, sitePort, this); GameObject.DontDestroyOnLoad(this.gameObject); humanoids = HumanoidNetworking.FindLocalHumanoids(); - for (int i = 0; i < humanoids.Count; i++) { - HumanoidControl humanoid = humanoids[i]; - if (humanoid.isRemote) + for (int i = 0; i < humanoids.Count; i++) + { + HumanoidControl aHumanoid = humanoids[i]; + if (aHumanoid.isRemote) continue; - humanoid.humanoidNetworking = this; + aHumanoid.humanoidNetworking = this; + } + if (humanoids.Count != 1) + { + Debug.LogError("Roboid Networking only supports 1 humanoid"); + return; } + humanoid = humanoids[0]; + headThing = new BoneThing(humanoid.headTarget.head); + // this.participant.Send(new ThingMsg((byte)humanoid.nwId, headThing)); // //endpoint = new IPEndPoint(IPAddress.Any, sitePort); //udpClient = new UdpClient(sitePort); - //DebugLog($"Start receiving on port {sitePort}"); - dataStream = new EchoStream(); - //client = newClient ? Client.NewUDPClient(udpClient, endpoint.Address.ToString(), endpoint.Port) : Client.clients[0]; - //udpClient.BeginReceive(new System.AsyncCallback(result => ReceiveUDP(client, result)), null); - Task task = Task.Run(() => SiteServer.ReceiveData(dataStream, client)); + // //DebugLog($"Start receiving on port {sitePort}"); + // dataStream = new EchoStream(); + // //client = newClient ? Client.NewUDPClient(udpClient, endpoint.Address.ToString(), endpoint.Port) : Client.clients[0]; + // //udpClient.BeginReceive(new System.AsyncCallback(result => ReceiveUDP(client, result)), null); + // Task task = Task.Run(() => SiteServer.ReceiveData(dataStream, client)); } - protected void ReceiveUDP(Client client, IAsyncResult result) { - if (udpClient == null) - return; + // protected void ReceiveUDP(Client client, IAsyncResult result) { + // if (udpClient == null) + // return; - if (udpClient.Client.Connected) { - try { - byte[] data = udpClient.EndReceive(result, ref endPoint); - dataStream.WriteByte((byte)data.Length); - dataStream.Write(data, 0, data.Length); - if (client.ipAddress == null) { - client.ipAddress = endPoint.Address.ToString(); - client.port = endPoint.Port; - // I thing sending now is too soon, we are currenlty processing a message... - //SendNetworkId(client); - //if (string.IsNullOrEmpty(sceneUrl) == false) - // SendModelUrl(client, sceneUrl); - } - } - catch (Exception _) { - Debug.Log("connection error"); - } - } - else { - Debug.Log("Client disconnected"); - } - udpClient.BeginReceive(new System.AsyncCallback(result => ReceiveUDP(client, result)), null); - } + // if (udpClient.Client.Connected) { + // try { + // byte[] data = udpClient.EndReceive(result, ref endPoint); + // dataStream.WriteByte((byte)data.Length); + // dataStream.Write(data, 0, data.Length); + // if (client.ipAddress == null) { + // client.ipAddress = endPoint.Address.ToString(); + // client.port = endPoint.Port; + // // I thing sending now is too soon, we are currenlty processing a message... + // //SendNetworkId(client); + // //if (string.IsNullOrEmpty(sceneUrl) == false) + // // SendModelUrl(client, sceneUrl); + // } + // } + // catch (Exception e) { + // Debug.Log("connection error " + e); + // } + // } + // else { + // Debug.Log("Client disconnected"); + // } + // udpClient.BeginReceive(new System.AsyncCallback(result => ReceiveUDP(client, result)), null); + // } - protected void OnApplicationQuit() { - if (udpClient != null) { - udpClient.Client.Close(); - udpClient.Close(); - udpClient = null; - } - } + // protected void OnApplicationQuit() { + // if (udpClient != null) { + // udpClient.Client.Close(); + // udpClient.Close(); + // udpClient = null; + // } + // } #region Update @@ -275,26 +319,49 @@ namespace Passer.Humanoid { const float clientMsgInterval = 3; float lastClientMsg = -clientMsgInterval; - protected virtual void LateUpdate() { - foreach (Client client in Client.clients) { - if (client is HumanoidClient humanoidClient) { - while (humanoidClient.messageQueue.TryDequeue(out Passer.Control.IMessage msg)) - humanoidClient.ProcessMessage(msg); - } - } + protected void Update() + { + while (this.participant.updateQueue.TryDequeue(out RoboidControl.Participant.UpdateEvent e)) + HandleUpdateEvent(e); + } - if (Time.time > lastSend + 1 / sendRate) { - if (humanoids != null) { - foreach (HumanoidControl humanoid in humanoids) { - if (!humanoid.isRemote) { + private void HandleUpdateEvent(RoboidControl.Participant.UpdateEvent e) + { + switch (e.messageId) + { + case NetworkIdMsg.Id: + ProcessNetworkId(); + break; + } + } + + protected virtual void LateUpdate() + { + // foreach (Client client in Client.clients) { + // if (client is HumanoidParticipant humanoidClient) { + // while (humanoidClient.messageQueue.TryDequeue(out Passer.Control.IMessage msg)) + // humanoidClient.ProcessMessage(msg); + // } + // } + + if (Time.time > lastSend + 1 / sendRate) + { + if (humanoids != null) + { + foreach (HumanoidControl humanoid in humanoids) + { + if (!humanoid.isRemote) + { UpdateHumanoidPose(humanoid); } } } lastSend = Time.time; } - if (Time.time > lastClientMsg + clientMsgInterval) { - SendClientMsg(humanoids[0]); // We just need it for the networkId + if (Time.time > lastClientMsg + clientMsgInterval) + { + //SendClientMsg(humanoids[0]); // We just need it for the networkId + this.participant.Send(new ParticipantMsg((byte)humanoid.nwId)); lastClientMsg = Time.time; } } @@ -302,170 +369,181 @@ namespace Passer.Humanoid { #endregion Update #region Client + /* + //class ClientMsg : HumanoidNetworking.IMessage { + // public const byte Id = 0xA0; // 160 + // public const byte length = 2; + // public byte networkId; - //class ClientMsg : HumanoidNetworking.IMessage { - // public const byte Id = 0xA0; // 160 - // public const byte length = 2; - // public byte networkId; + // public ClientMsg(byte networkId) { + // this.networkId = networkId; + // } + // public ClientMsg(byte[] data) : base(data) { } - // public ClientMsg(byte networkId) { - // this.networkId = networkId; - // } - // public ClientMsg(byte[] data) : base(data) { } + // public override byte[] Serialize() { + // byte[] data = new byte[ClientMsg.length]; + // data[0] = ClientMsg.Id; + // data[1] = this.networkId; + // return data; + // } + // public override void Deserialize(byte[] data) { + // base.Deserialize(data); + // uint ix = 0; + // networkId = data[ix++]; + // } + //} - // public override byte[] Serialize() { - // byte[] data = new byte[ClientMsg.length]; - // data[0] = ClientMsg.Id; - // data[1] = this.networkId; - // return data; - // } - // public override void Deserialize(byte[] data) { - // base.Deserialize(data); - // uint ix = 0; - // networkId = data[ix++]; - // } - //} - - protected void SendClientMsg(HumanoidControl humanoid) { - if (debug <= HumanoidNetworking.DebugLevel.Debug) - Debug.Log("Send ClientMsg " + humanoid.nwId); - //ClientMsg clientMsg = new((byte)humanoid.nwId); - //SendMsg(clientMsg); - ClientMsg.Publish(client, (byte)humanoid.nwId); - } + protected void SendClientMsg(HumanoidControl humanoid) { + if (debug <= HumanoidNetworking.DebugLevel.Debug) + Debug.Log("Send ClientMsg " + humanoid.nwId); + //ClientMsg clientMsg = new((byte)humanoid.nwId); + //SendMsg(clientMsg); + ClientMsg.Publish(client, (byte)humanoid.nwId); + } + */ #endregion Client #region Investigate + /* + protected void ProcessInvestigate(InvestigateMsg investigate) { - protected void ProcessInvestigate(InvestigateMsg investigate) { - - } - + } + */ #endregion Investigate #region Thing + /* + protected virtual void Process(Participant client, ThingMsg msg) { + DebugLog($"Process Thing [{msg.networkId}/{msg.thingId}] parent:{msg.parentId} type: {msg.thingType}"); - protected virtual void ProcessThing(Client client, ThingMsg msg) { - DebugLog($"Process Thing [{msg.networkId}/{msg.thingId}] parent:{msg.parentId} type: {msg.thingType}"); + Thing thing = Thing.GetThing(msg.networkId, msg.thingId); + if (thing == null) + CreateThing(client, msg.networkId, msg.thingId, msg.thingType, msg.parentId); - Thing thing = Thing.GetThing(msg.networkId, msg.thingId); - if (thing == null) - CreateThing(client, msg.networkId, msg.thingId, msg.thingType, msg.parentId); - - else { - thing.objectType = msg.thingType; - if (msg.parentId != 0) { - Thing parentThing = Thing.GetThing(msg.networkId, msg.parentId); - if (parentThing != null) { - if (thing.transform.parent != parentThing.transform) { - Debug.Log($"Changed parent to {parentThing.gameObject.name} {parentThing.thingId}"); - thing.transform.SetParent(parentThing.transform, true); + else { + thing.objectType = msg.thingType; + if (msg.parentId != 0) { + Thing parentThing = Thing.GetThing(msg.networkId, msg.parentId); + if (parentThing != null) { + if (thing.transform.parent != parentThing.transform) { + Debug.Log($"Changed parent to {parentThing.gameObject.name} {parentThing.thingId}"); + thing.transform.SetParent(parentThing.transform, true); + } + } + else { + Debug.LogWarning($"Could not find the parent {msg.parentId} for {msg.thingId}"); + thing.transform.SetParent(this.transform); + } } } - else { - Debug.LogWarning($"Could not find the parent {msg.parentId} for {msg.thingId}"); - thing.transform.SetParent(this.transform); + } + + protected virtual Thing CreateThing(Participant client, byte networkId, byte thingId, byte thingType, byte parentId) { + DebugLog($"Create new thing [{networkId}/{thingId}]"); + GameObject thingObject = new("Thing " + thingId); + Thing thing = Thing.Create(thingObject, client, networkId, thingId, thingType); + if (parentId != 0) { + Thing parentThing = Thing.allThings.Find(thing => thing.networkId == networkId && thing.thingId == parentId); + if (parentThing != null) + thing.transform.SetParent(parentThing.transform); + else { + Debug.LogWarning($"Could not find the parent {parentId} for {thingId}"); + thing.transform.SetParent(this.transform); + } } + + return thing; } - } - } - - protected virtual Thing CreateThing(Client client, byte networkId, byte thingId, byte thingType, byte parentId) { - DebugLog($"Create new thing [{networkId}/{thingId}]"); - GameObject thingObject = new("Thing " + thingId); - Thing thing = Thing.Create(thingObject, client, networkId, thingId, thingType); - if (parentId != 0) { - Thing parentThing = Thing.allThings.Find(thing => thing.networkId == networkId && thing.thingId == parentId); - if (parentThing != null) - thing.transform.SetParent(parentThing.transform); - else { - Debug.LogWarning($"Could not find the parent {parentId} for {thingId}"); - thing.transform.SetParent(this.transform); - } - } - - return thing; - } - + */ #endregion Thing #region Pose - public virtual void UpdateHumanoidPose(HumanoidControl humanoid) { + public virtual void UpdateHumanoidPose(HumanoidControl humanoid) + { if (debug <= HumanoidNetworking.DebugLevel.Debug) Debug.Log("Send Pose Humanoid " + humanoid.humanoidId + " nwId: " + humanoid.nwId); - SendBone(humanoid.hipsTarget.hips, true); - SendBone(humanoid.hipsTarget.spine); - SendBone(humanoid.hipsTarget.chest); - SendBone(humanoid.headTarget.neck); - SendBone(humanoid.headTarget.head); + this.participant.Send(new PoseMsg((byte)humanoid.nwId, headThing)); + // SendBone(humanoid.hipsTarget.hips, true); + // SendBone(humanoid.hipsTarget.spine); + // SendBone(humanoid.hipsTarget.chest); + // SendBone(humanoid.headTarget.neck); + // SendBone(humanoid.headTarget.head); - SendBone(humanoid.leftHandTarget.upperArm); - SendBone(humanoid.leftHandTarget.forearm); - SendBone(humanoid.leftHandTarget.hand, false, true); + // SendBone(humanoid.leftHandTarget.upperArm); + // SendBone(humanoid.leftHandTarget.forearm); + // SendBone(humanoid.leftHandTarget.hand, false, true); - SendBone(humanoid.rightHandTarget.upperArm); - SendBone(humanoid.rightHandTarget.forearm); - SendBone(humanoid.rightHandTarget.hand, false, true); + // SendBone(humanoid.rightHandTarget.upperArm); + // SendBone(humanoid.rightHandTarget.forearm); + // SendBone(humanoid.rightHandTarget.hand, false, true); - SendBone(humanoid.leftFootTarget.upperLeg); - SendBone(humanoid.leftFootTarget.lowerLeg); - SendBone(humanoid.leftFootTarget.foot); + // SendBone(humanoid.leftFootTarget.upperLeg); + // SendBone(humanoid.leftFootTarget.lowerLeg); + // SendBone(humanoid.leftFootTarget.foot); - SendBone(humanoid.rightFootTarget.upperLeg); - SendBone(humanoid.rightFootTarget.lowerLeg); - SendBone(humanoid.rightFootTarget.foot); + // SendBone(humanoid.rightFootTarget.upperLeg); + // SendBone(humanoid.rightFootTarget.lowerLeg); + // SendBone(humanoid.rightFootTarget.foot); } - private void SendBone(HumanoidTarget.TargetedBone bone, bool isRoot = false, bool calculateOrientation = false) { - //RoboidBonePose bonePose = new(bone, isRoot); - //byte[] data = bonePose.Serialize(); - //if (bonePose.bonePosition != null) { - // Debug.Log($"bone position {bone.bone.transform.position.x} {bone.bone.transform.position.y} {bone.bone.transform.position.z}"); - // Debug.Log($"bone pos {bonePose.bonePosition.horizontal} {bonePose.bonePosition.vertical} {bonePose.bonePosition.distance}"); - //} - //SendMsg(data); + // private void SendBone(HumanoidTarget.TargetedBone bone, bool isRoot = false, bool calculateOrientation = false) { + // //RoboidBonePose bonePose = new(bone, isRoot); + // //byte[] data = bonePose.Serialize(); + // //if (bonePose.bonePosition != null) { + // // Debug.Log($"bone position {bone.bone.transform.position.x} {bone.bone.transform.position.y} {bone.bone.transform.position.z}"); + // // Debug.Log($"bone pos {bonePose.bonePosition.horizontal} {bonePose.bonePosition.vertical} {bonePose.bonePosition.distance}"); + // //} + // //SendMsg(data); - if (isRoot) { - Quaternion orientation = bone.bone.transform.rotation; - Quat32 boneOrientation = new(orientation.x, orientation.y, orientation.z, orientation.w); - FromVector3(bone.bone.transform.position, out float distance, out float horizontal, out float vertical); - Spherical bonePosition = new(distance, horizontal, vertical); - PoseMsg.Send(client, (byte)bone.boneId, bonePosition, boneOrientation); - } - else { - Quaternion orientation = bone.bone.transform.localRotation; - if (calculateOrientation) - orientation = Quaternion.Inverse(bone.parent.bone.transform.rotation) * bone.bone.transform.rotation; - //orientation = Quaternion.Inverse(bone.bone.transform.parent.rotation) * bone.bone.transform.rotation; - Quat32 boneOrientation = new(orientation.x, orientation.y, orientation.z, orientation.w); - PoseMsg.Send(client, (byte)bone.boneId, null, boneOrientation); - } - } + // if (isRoot) + // { + // Quaternion orientation = bone.bone.transform.rotation; + // Quat32 boneOrientation = new(orientation.x, orientation.y, orientation.z, orientation.w); + // FromVector3(bone.bone.transform.position, out float distance, out float horizontal, out float vertical); + // Spherical bonePosition = new(distance, horizontal, vertical); + // PoseMsg.Send(client, (byte)bone.boneId, bonePosition, boneOrientation); + // this.participant.Send(new PoseMsg(networkId, boneThing)) + // } + // else + // { + // Quaternion orientation = bone.bone.transform.localRotation; + // if (calculateOrientation) + // orientation = Quaternion.Inverse(bone.parent.bone.transform.rotation) * bone.bone.transform.rotation; + // //orientation = Quaternion.Inverse(bone.bone.transform.parent.rotation) * bone.bone.transform.rotation; + // Quat32 boneOrientation = new(orientation.x, orientation.y, orientation.z, orientation.w); + // PoseMsg.Send(client, (byte)bone.boneId, null, boneOrientation); + // } + // } #endregion Pose //#region Messages - //#region NetworkId + #region NetworkId - void ProcessNetworkId(Client client, NetworkIdMsg msg) { + void ProcessNetworkId() + { //this.networkId = msg.networkId; - GameObject networkingObj = this.GetGameObject(msg.networkId); - if (networkingObj == null) { + GameObject networkingObj = this.GetGameObject(this.participant.networkId); + if (networkingObj == null) + { if (this.debug <= HumanoidNetworking.DebugLevel.Error) - this.DebugLog("Could not find Networking for Instantiate Humanoid " + msg.networkId + "/0"); + this.DebugLog("Could not find Networking for Instantiate Humanoid " + this.participant.networkId + "/0"); return; } HumanoidControl remoteHumanoid = humanoids[0]; //FindRemoteHumanoid(humanoids, 0); - if (remoteHumanoid == null) { + if (remoteHumanoid == null) + { if (debug <= HumanoidNetworking.DebugLevel.Warning) - DebugLog("Remote Humanoid " + msg.networkId + "/" + 0 + "not found"); + DebugLog("Remote Humanoid " + this.participant.networkId + "/" + 0 + "not found"); return; } - remoteHumanoid.nwId = msg.networkId; + remoteHumanoid.nwId = this.participant.networkId; + this.participant.Send(new ThingMsg((byte)humanoid.nwId, headThing)); +/* //SendThing(client, remoteHumanoid); ThingMsg.Send(client, msg.networkId, 0, 1, 0); NameMsg.Send(client, msg.networkId, 0, "Humanoid"); @@ -503,18 +581,20 @@ namespace Passer.Humanoid { InitBone(client, remoteHumanoid, remoteHumanoid.rightFootTarget.lowerLeg); InitBone(client, remoteHumanoid, remoteHumanoid.rightFootTarget.foot); InitBone(client, remoteHumanoid, remoteHumanoid.rightFootTarget.toes); +*/ } - protected void InitBone(Client client, HumanoidControl humanoid, HumanoidTarget.TargetedBone bone) { - Thing thing = Thing.Create(bone.bone.transform.gameObject, client, client.networkId, (byte)bone.boneId, 0x00); - if (bone.parent != null) - ThingMsg.Send(client, thing.networkId, thing.thingId, thing.objectType, (byte)bone.parent.boneId); - else - ThingMsg.Send(client, thing.networkId, thing.thingId, thing.objectType, 0); - NameMsg.Send(client, thing.networkId, thing.thingId, bone.bone.transform.name); - } + // protected void InitBone(Client client, HumanoidControl humanoid, HumanoidTarget.TargetedBone bone) + // { + // Thing thing = Thing.Create(bone.bone.transform.gameObject, client, client.networkId, (byte)bone.boneId, 0x00); + // if (bone.parent != null) + // ThingMsg.Send(client, thing.networkId, thing.thingId, thing.objectType, (byte)bone.parent.boneId); + // else + // ThingMsg.Send(client, thing.networkId, thing.thingId, thing.objectType, 0); + // NameMsg.Send(client, thing.networkId, thing.thingId, bone.bone.transform.name); + // } - //#endregion + #endregion //#region Thing @@ -588,33 +668,34 @@ namespace Passer.Humanoid { // ModelUrlMsg.Send(client, 0, url); //} - bool loaded = false; - protected async void ProcessModelURL(Client client, ModelUrlMsg msg) { - if (loaded) - return; + // bool loaded = false; + // protected async void ProcessModelURL(Client client, ModelUrlMsg msg) + // { + // if (loaded) + // return; - Debug.Log("Loading GLTF model from :" + msg.url); - GltfImport gltfImport = new GltfImport(); - loaded = true; - // for .gltf... - bool success = await gltfImport.Load(msg.url); - if (success) { - Transform parentTransform = this.transform; - await gltfImport.InstantiateMainSceneAsync(parentTransform); - if (!success) - return; - //Camera camera = FindObjectOfType(); // assuming just one camera per scene - //if (camera != null) - // camera.enabled = true; - Light[] lights = FindObjectsByType(FindObjectsSortMode.None); - foreach (Light light in lights) - light.intensity = 1; // light.intensity / 1000; + // Debug.Log("Loading GLTF model from :" + msg.url); + // GltfImport gltfImport = new GltfImport(); + // loaded = true; + // // for .gltf... + // bool success = await gltfImport.Load(msg.url); + // if (success) { + // Transform parentTransform = this.transform; + // await gltfImport.InstantiateMainSceneAsync(parentTransform); + // if (!success) + // return; + // //Camera camera = FindObjectOfType(); // assuming just one camera per scene + // //if (camera != null) + // // camera.enabled = true; + // Light[] lights = FindObjectsByType(FindObjectsSortMode.None); + // foreach (Light light in lights) + // light.intensity = 1; // light.intensity / 1000; - Renderer[] renderers = parentTransform.GetComponentsInChildren(); - foreach (Renderer renderer in renderers) - renderer.gameObject.AddComponent(); - } - } + // Renderer[] renderers = parentTransform.GetComponentsInChildren(); + // foreach (Renderer renderer in renderers) + // renderer.gameObject.AddComponent(); + // } + // } //void ISiteServer.ProcessModelUrl(Client client, ModelUrlMsg msg) { @@ -633,48 +714,48 @@ namespace Passer.Humanoid { #region GLTF private bool loadingModel = false; - private Dictionary gltfCache = new(); + //private Dictionary gltfCache = new(); - private async void ProcessGltfModel(ModelUrlMsg msg) { - Transform parentTransform = this.transform; - Thing parentThing = Thing.GetThing(msg.networkId, msg.thingId); - if (parentThing != null) { - if (parentThing.modelUrl == msg.url) { - // Thing already has this model - Debug.Log($"thing [{msg.networkId}/{msg.thingId}] already has model {msg.url}"); - return; - } - else - parentThing.modelUrl = msg.url; - parentTransform = parentThing.transform; - } + // private async void ProcessGltfModel(ModelUrlMsg msg) { + // Transform parentTransform = this.transform; + // Thing parentThing = Thing.GetThing(msg.networkId, msg.thingId); + // if (parentThing != null) { + // if (parentThing.modelUrl == msg.url) { + // // Thing already has this model + // Debug.Log($"thing [{msg.networkId}/{msg.thingId}] already has model {msg.url}"); + // return; + // } + // else + // parentThing.modelUrl = msg.url; + // parentTransform = parentThing.transform; + // } - if (gltfCache.TryGetValue(msg.url, out GltfImport gltfImport)) { - Debug.Log($"Instantiate [{msg.networkId}/{msg.thingId}] ***** buffered GLTF: " + msg.url); - await gltfImport.InstantiateMainSceneAsync(parentTransform); - } - else { - Debug.Log("Loading GLTF model from: " + msg.url); - gltfImport = new(); - bool success = await gltfImport.Load(msg.url); - if (success == false) - return; + // if (gltfCache.TryGetValue(msg.url, out GltfImport gltfImport)) { + // Debug.Log($"Instantiate [{msg.networkId}/{msg.thingId}] ***** buffered GLTF: " + msg.url); + // await gltfImport.InstantiateMainSceneAsync(parentTransform); + // } + // else { + // Debug.Log("Loading GLTF model from: " + msg.url); + // gltfImport = new(); + // bool success = await gltfImport.Load(msg.url); + // if (success == false) + // return; - gltfCache.Add(msg.url, gltfImport); - Debug.Log($"Instantiate [{msg.networkId}/{msg.thingId}] ***** loaded GLTF: " + msg.url); - await gltfImport.InstantiateMainSceneAsync(parentTransform); - } - parentTransform.localScale = Vector3.one * msg.scale; + // gltfCache.Add(msg.url, gltfImport); + // Debug.Log($"Instantiate [{msg.networkId}/{msg.thingId}] ***** loaded GLTF: " + msg.url); + // await gltfImport.InstantiateMainSceneAsync(parentTransform); + // } + // parentTransform.localScale = Vector3.one * msg.scale; - ScanModelForThings(parentTransform); + // ScanModelForThings(parentTransform); - // Correct lights - if (parentTransform != null) { - Light[] lights = parentTransform.GetComponentsInChildren(); - foreach (Light light in lights) - light.intensity = 1; // light.intensity / 1000; - } - } + // // Correct lights + // if (parentTransform != null) { + // Light[] lights = parentTransform.GetComponentsInChildren(); + // foreach (Light light in lights) + // light.intensity = 1; // light.intensity / 1000; + // } + // } //private async Task InstantiateGltf(GltfImport gltfImport, byte objectId, float scale) { // Debug.Log("Instantiate GLTF model"); @@ -687,101 +768,121 @@ namespace Passer.Humanoid { // return parentTransform; //} - private void ScanModelForThings(Transform parentTransform) { - if (parentTransform == null) - return; + // private void ScanModelForThings(Transform parentTransform) + // { + // if (parentTransform == null) + // return; - Debug.Log("scanning model for things....."); - SkinnedMeshRenderer[] meshRenderers = parentTransform.GetComponentsInChildren(); - if (meshRenderers.Length > 0) { - foreach (SkinnedMeshRenderer meshRenderer in meshRenderers) { - if (meshRenderer.rootBone != null) { - Debug.Log("Found a skinned mesh with bones"); - ScanForThings(parentTransform);//meshRenderer.rootBone); - break; - } - } - } - else { - Renderer[] renderers = parentTransform.GetComponentsInChildren(); - foreach (Renderer renderer in renderers) { - MeshCollider c = renderer.gameObject.AddComponent(); - c.convex = true; - } + // Debug.Log("scanning model for things....."); + // SkinnedMeshRenderer[] meshRenderers = parentTransform.GetComponentsInChildren(); + // if (meshRenderers.Length > 0) + // { + // foreach (SkinnedMeshRenderer meshRenderer in meshRenderers) + // { + // if (meshRenderer.rootBone != null) + // { + // Debug.Log("Found a skinned mesh with bones"); + // ScanForThings(parentTransform);//meshRenderer.rootBone); + // break; + // } + // } + // } + // else + // { + // Renderer[] renderers = parentTransform.GetComponentsInChildren(); + // foreach (Renderer renderer in renderers) + // { + // MeshCollider c = renderer.gameObject.AddComponent(); + // c.convex = true; + // } - ScanForThings(parentTransform); - } - } + // ScanForThings(parentTransform); + // } + // } - private void ScanForThings(Transform rootTransform) { - Thing[] thingArray = Thing.allThings.ToArray(); + // private void ScanForThings(Transform rootTransform) + // { + // Thing[] thingArray = Thing.allThings.ToArray(); - for (int thingIx = 0; thingIx < thingArray.Length; thingIx++) { - Thing thing = thingArray[thingIx]; - //Debug.Log($"find {thing.name}"); - GameObject foundObj = FindThingByName(thing, rootTransform); - if (foundObj != null) { - Thing foundThing = foundObj.GetComponent(); - if (foundObj != thing.gameObject) { - if (foundThing == null) { - Debug.Log($"move thing [{thing.networkId}/{thing.thingId}] to {foundObj.name}"); - Thing.allThings.Remove(thing); - foundThing = thing.CopyTo(foundObj); - Thing.allThings.Add(foundThing); - } - } - if (thing.transform.childCount > foundObj.transform.childCount) { - CopyChildren(thing, foundObj.transform); - } - } - //else - // Debug.LogWarning($"Could not find thing {thing.name}"); - } - } + // for (int thingIx = 0; thingIx < thingArray.Length; thingIx++) + // { + // Thing thing = thingArray[thingIx]; + // //Debug.Log($"find {thing.name}"); + // GameObject foundObj = FindThingByName(thing, rootTransform); + // if (foundObj != null) + // { + // Thing foundThing = foundObj.GetComponent(); + // if (foundObj != thing.gameObject) + // { + // if (foundThing == null) + // { + // Debug.Log($"move thing [{thing.networkId}/{thing.thingId}] to {foundObj.name}"); + // Thing.allThings.Remove(thing); + // foundThing = thing.CopyTo(foundObj); + // Thing.allThings.Add(foundThing); + // } + // } + // if (thing.transform.childCount > foundObj.transform.childCount) + // { + // CopyChildren(thing, foundObj.transform); + // } + // } + // //else + // // Debug.LogWarning($"Could not find thing {thing.name}"); + // } + // } - private GameObject FindThingByName(Thing thing, Transform rootTransform) { - if (rootTransform == null || thing == null) - return null; + // private GameObject FindThingByName(Thing thing, Transform rootTransform) + // { + // if (rootTransform == null || thing == null) + // return null; - if (rootTransform.name == thing.name) - return rootTransform.gameObject; + // if (rootTransform.name == thing.name) + // return rootTransform.gameObject; - for (int childIx = 0; childIx < rootTransform.childCount; childIx++) { - Transform child = rootTransform.GetChild(childIx); - GameObject foundObj = FindThingByName(thing, child); - if (foundObj != null) - return foundObj; - } - return null; - } + // for (int childIx = 0; childIx < rootTransform.childCount; childIx++) + // { + // Transform child = rootTransform.GetChild(childIx); + // GameObject foundObj = FindThingByName(thing, child); + // if (foundObj != null) + // return foundObj; + // } + // return null; + // } - private void CopyChildren(Thing from, Transform to) { - for (int childIx = 0; childIx < from.transform.childCount; childIx++) { - Transform child = from.transform.GetChild(childIx); - //Debug.Log(child.name); - bool found = false; - foreach (Transform toChild in to) { - if (child.name == toChild.name) { - found = true; - break; - } - } - if (!found) { - //Debug.Log("...not found"); - Thing childThing = child.GetComponent(); - if (childThing != null) { - Thing.allThings.Remove(childThing); - GameObject newChildObj = new GameObject(child.name); - newChildObj.transform.SetParent(to.transform); - //newChildObj.transform.SetLocalPositionAndRotation( - // child.transform.localPosition, child.transform.localRotation); - //newChildObj.transform.localScale = Vector3.one; - Thing newThing = childThing.CopyTo(newChildObj); - Thing.allThings.Add(newThing); - } - } - } - } + // private void CopyChildren(Thing from, Transform to) + // { + // for (int childIx = 0; childIx < from.transform.childCount; childIx++) + // { + // Transform child = from.transform.GetChild(childIx); + // //Debug.Log(child.name); + // bool found = false; + // foreach (Transform toChild in to) + // { + // if (child.name == toChild.name) + // { + // found = true; + // break; + // } + // } + // if (!found) + // { + // //Debug.Log("...not found"); + // Thing childThing = child.GetComponent(); + // if (childThing != null) + // { + // Thing.allThings.Remove(childThing); + // GameObject newChildObj = new GameObject(child.name); + // newChildObj.transform.SetParent(to.transform); + // //newChildObj.transform.SetLocalPositionAndRotation( + // // child.transform.localPosition, child.transform.localRotation); + // //newChildObj.transform.localScale = Vector3.one; + // Thing newThing = childThing.CopyTo(newChildObj); + // Thing.allThings.Add(newThing); + // } + // } + // } + // } //private void ReplaceSkinnedBones(SkinnedMeshRenderer meshRenderer) { // Transform[] bones = meshRenderer.bones; @@ -926,27 +1027,32 @@ namespace Passer.Humanoid { // } //} - private static void FromVector3(Vector3 v, out float distance, out float horizontal, out float vertical) { - distance = v.magnitude; - if (distance == 0.0f) { - horizontal = 0; - vertical = 0; - } - else { - vertical = (Mathf.PI / 2 - Mathf.Acos(v.y / distance)) * Mathf.Rad2Deg; - horizontal = Mathf.Atan2(v.x, v.z) * Mathf.Rad2Deg; - } - } + // private static void FromVector3(Vector3 v, out float distance, out float horizontal, out float vertical) + // { + // distance = v.magnitude; + // if (distance == 0.0f) + // { + // horizontal = 0; + // vertical = 0; + // } + // else + // { + // vertical = (Mathf.PI / 2 - Mathf.Acos(v.y / distance)) * Mathf.Rad2Deg; + // horizontal = Mathf.Atan2(v.x, v.z) * Mathf.Rad2Deg; + // } + // } - protected static Vector3 ToVector3(Spherical s) { - Vector3 v = Quaternion.AngleAxis(s.horizontal, Vector3.up) * Quaternion.AngleAxis(s.vertical, Vector3.left) * (Vector3.forward * s.distance); - return v; - } + // protected static Vector3 ToVector3(Spherical s) + // { + // Vector3 v = Quaternion.AngleAxis(s.horizontal, Vector3.up) * Quaternion.AngleAxis(s.vertical, Vector3.left) * (Vector3.forward * s.distance); + // return v; + // } - protected static Quaternion ToQuaternion(Quat32 q32) { - Quaternion q = new(q32.x, q32.y, q32.z, q32.w); - return q; - } + // protected static Quaternion ToQuaternion(Quat32 q32) + // { + // Quaternion q = new(q32.x, q32.y, q32.z, q32.w); + // return q; + // } //#endregion Pose @@ -982,12 +1088,14 @@ namespace Passer.Humanoid { #region Receive - protected static float ReceiveAngle8(byte[] data, ref uint ix) { + protected static float ReceiveAngle8(byte[] data, ref uint ix) + { float value = (data[ix++] * 180) / 128.0F; return value; } - protected static Vector3 ReceiveSpherical(byte[] data, ref uint ix) { + protected static Vector3 ReceiveSpherical(byte[] data, ref uint ix) + { float horizontal = ReceiveAngle8(data, ref ix); float vertical = ReceiveAngle8(data, ref ix); float distance = ReceiveFloat16(data, ref ix); @@ -995,7 +1103,8 @@ namespace Passer.Humanoid { return v; } - protected static float ReceiveFloat16(byte[] data, ref uint ix) { + protected static float ReceiveFloat16(byte[] data, ref uint ix) + { ushort value = (ushort)(data[ix++] << 8 | data[ix++]); float16 f16 = new float16(); f16.SetBinary(value); diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/HumanoidThing.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/HumanoidThing.cs new file mode 100644 index 0000000..e989e77 --- /dev/null +++ b/Runtime/HumanoidControl/Scripts/Networking/Roboid/HumanoidThing.cs @@ -0,0 +1,6 @@ +using RoboidControl; + +public class HumanoidThing : Thing +{ + public HumanoidThing(bool invokeEvent = true) : base(Type.HUmanoid, invokeEvent) {} +} diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/LowLevelMessages.cs.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/HumanoidThing.cs.meta similarity index 83% rename from Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/LowLevelMessages.cs.meta rename to Runtime/HumanoidControl/Scripts/Networking/Roboid/HumanoidThing.cs.meta index 9980c38..4f14fe7 100644 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore/LowLevelMessages.cs.meta +++ b/Runtime/HumanoidControl/Scripts/Networking/Roboid/HumanoidThing.cs.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 157cf85b523c1f648adc007539f8b736 +guid: 4ec67072d500b33449ba4485378f7b22 MonoImporter: externalObjects: {} serializedVersion: 2 diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/RoboidControl-csharp.meta similarity index 77% rename from Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore.meta rename to Runtime/HumanoidControl/Scripts/Networking/Roboid/RoboidControl-csharp.meta index b6e25b9..ba73cb4 100644 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/ControlCore.meta +++ b/Runtime/HumanoidControl/Scripts/Networking/Roboid/RoboidControl-csharp.meta @@ -1,5 +1,5 @@ fileFormatVersion: 2 -guid: 98ee056958e257046a58cddcbcb661e3 +guid: 0e93fb67f760ca94092664257138720b folderAsset: yes DefaultImporter: externalObjects: {} diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/Spherical.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/Spherical.cs deleted file mode 100644 index 5a7204b..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/Spherical.cs +++ /dev/null @@ -1,57 +0,0 @@ -using Passer.Humanoid.Tracking; -using UnityEngine; - -namespace Passer.LinearAlgebra { - - public class Spherical16 { - - public float16 distance; - public byte horizontal; - public byte vertical; - - public Spherical16(float distance, float horizontal = 0, float vertical = 0) { - horizontal = Angle.Normalize(horizontal); - vertical = Angle.Normalize(vertical); - this.distance = new float16(distance); - this.horizontal = (byte)(horizontal * 128.0f / 180.0f); - this.vertical = (byte)(vertical * 128.0f / 180.0f); - } - - public static Spherical16 FromVector3(Vector3 v) { - float distance = v.magnitude; - if (distance == 0.0f) { - return new Spherical16(distance); - } - else { - float verticalAngle = (Mathf.PI / 2 - Mathf.Acos(v.y / distance)) * Mathf.Rad2Deg; - float horizontalAngle = Mathf.Atan2(v.x, v.z) * Mathf.Rad2Deg; - Debug.Log($"sph {horizontalAngle} {verticalAngle} {distance}"); - return new Spherical16(distance, horizontalAngle, verticalAngle); - } - } - } - - public class Quat32 { - public byte qx; - public byte qy; - public byte qz; - public byte qw; - - public Quat32(Quaternion q) { - int qx = (int)(q.x * 127 + 128); - int qy = (int)(q.y * 127 + 128); - int qz = (int)(q.z * 127 + 128); - int qw = (int)(q.w * 255); - if (q.w < 0) { - qx = -qx; - qy = -qy; - qz = -qz; - qw = -qw; - } - this.qx = (byte)(qx); - this.qy = (byte)(qy); - this.qz = (byte)(qz); - this.qw = (byte)(qw); - } - } -} \ No newline at end of file diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/Spherical.cs.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/Spherical.cs.meta deleted file mode 100644 index 53d3cd2..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/Spherical.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: 79bdc65d83f2c8e43bac904e283c6c46 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/Thing.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/Thing.cs deleted file mode 100644 index bc336c3..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/Thing.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Collections.Generic; -using UnityEngine; -using Passer.Control; - -public class Thing : MonoBehaviour { - public Client client; - public byte networkId; - public byte thingId; - public byte objectType; - public string modelUrl; - //protected Sensor sensor; - - public static List allThings = new(); - - public static Thing GetThing(byte networkId, byte thingId) { - Thing thing = allThings.Find(aThing => aThing.networkId == networkId && aThing.thingId == thingId); - return thing; - } - - protected virtual void Init() { - //if (this.objectType == 2) { - // sensor = this.gameObject.AddComponent(); - // sensor.thing = this; - //} - } - - public static Thing Create(GameObject obj, Client client, byte networkId, byte objId, byte objType) { - Thing thing = obj.AddComponent(); - thing.client = client; - thing.thingId = objId; - thing.objectType = objType; - thing.networkId = networkId; - thing.Init(); - allThings.Add(thing); - - return thing; - } - - public virtual Thing CopyTo(GameObject obj) { - //Debug.Log($"copy {obj}"); - Thing foundThing = Thing.Create(obj, this.client, this.networkId, this.thingId, this.objectType); - Destroy(this.gameObject); - return foundThing; - } - - public void ProcessBytes(byte[] bytes) { - //if (sensor != null) - // sensor.ProcessBytes(bytes); - } - //public void Update() { - // if (objectId == 0) - // Debug.Log(this.transform.eulerAngles); - //} -} diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/Thing.cs.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/Thing.cs.meta deleted file mode 100644 index 2abfee7..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/Thing.cs.meta +++ /dev/null @@ -1,2 +0,0 @@ -fileFormatVersion: 2 -guid: dbfb00fc659e2d8489a48aafec5ddfc5 \ No newline at end of file diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/float16.cs b/Runtime/HumanoidControl/Scripts/Networking/Roboid/float16.cs deleted file mode 100644 index d3081e3..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/float16.cs +++ /dev/null @@ -1,258 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using UnityEngine; - -public class float16 { - // - // FILE: float16.cpp - // AUTHOR: Rob Tillaart - // VERSION: 0.1.8 - // PURPOSE: library for Float16s for Arduino - // URL: http://en.wikipedia.org/wiki/Half-precision_floating-point_format - - ushort _value; - - public float16() { _value = 0; } - - public float16(float f) { - _value = f32tof16(f); - } - - public float toFloat() { - return f16tof32(_value); - } - - public ushort GetBinary() { return _value; } - public void SetBinary(ushort value) { _value = value; } - - ////////////////////////////////////////////////////////// - // - // EQUALITIES - // - /* - bool float16::operator ==(const float16 &f) { return (_value == f._value); } - -bool float16::operator !=(const float16 &f) { return (_value != f._value); } - -bool float16::operator >(const float16 &f) { - if ((_value & 0x8000) && (f._value & 0x8000)) - return _value < f._value; - if (_value & 0x8000) - return false; - if (f._value & 0x8000) - return true; - return _value > f._value; -} - -bool float16::operator >=(const float16 &f) { - if ((_value & 0x8000) && (f._value & 0x8000)) - return _value <= f._value; - if (_value & 0x8000) - return false; - if (f._value & 0x8000) - return true; - return _value >= f._value; -} - -bool float16::operator <(const float16 &f) { - if ((_value & 0x8000) && (f._value & 0x8000)) - return _value > f._value; - if (_value & 0x8000) - return true; - if (f._value & 0x8000) - return false; - return _value < f._value; -} - -bool float16::operator <=(const float16 &f) { - if ((_value & 0x8000) && (f._value & 0x8000)) - return _value >= f._value; - if (_value & 0x8000) - return true; - if (f._value & 0x8000) - return false; - return _value <= f._value; -} - -////////////////////////////////////////////////////////// -// -// NEGATION -// -float16 float16::operator -() { - float16 f16; - f16.setBinary(_value ^ 0x8000); - return f16; -} - -////////////////////////////////////////////////////////// -// -// MATH -// -float16 float16::operator +(const float16 &f) { - return float16(this->toDouble() + f.toDouble()); -} - -float16 float16::operator -(const float16 &f) { - return float16(this->toDouble() - f.toDouble()); -} - -float16 float16::operator *(const float16 &f) { - return float16(this->toDouble() * f.toDouble()); -} - -float16 float16::operator /(const float16 &f) { - return float16(this->toDouble() / f.toDouble()); -} - -float16 & float16::operator+=(const float16 &f) { - *this = this->toDouble() + f.toDouble(); - return *this; -} - -float16 & float16::operator-=(const float16 &f) { - *this = this->toDouble() - f.toDouble(); - return *this; -} - -float16 & float16::operator*=(const float16 &f) { - *this = this->toDouble() * f.toDouble(); - return *this; -} - -float16 & float16::operator/=(const float16 &f) { - *this = this->toDouble() / f.toDouble(); - return *this; -} - -////////////////////////////////////////////////////////// -// -// MATH HELPER FUNCTIONS -// -int float16::sign() { - if (_value & 0x8000) - return -1; - if (_value & 0xFFFF) - return 1; - return 0; -} - -bool float16::isZero() { return ((_value & 0x7FFF) == 0x0000); } - -bool float16::isNaN() { - if ((_value & 0x7C00) != 0x7C00) - return false; - if ((_value & 0x03FF) == 0x0000) - return false; - return true; -} - -bool float16::isInf() { return ((_value == 0x7C00) || (_value == 0xFC00)); } - */ - ////////////////////////////////////////////////////////// - // - // CORE CONVERSION - // - float f16tof32(ushort _value) { - //ushort sgn; - ushort man; - int exp; - float f; - - //Debug.Log($"{_value}"); - - bool sgn = (_value & 0x8000) > 0; - exp = (_value & 0x7C00) >> 10; - man = (ushort)(_value & 0x03FF); - - //Debug.Log($"{sgn} {exp} {man}"); - - // ZERO - if ((_value & 0x7FFF) == 0) { - return sgn ? -0 : 0; - } - // NAN & INF - if (exp == 0x001F) { - if (man == 0) - return sgn ? float.NegativeInfinity : float.PositiveInfinity; //-INFINITY : INFINITY; - else - return float.NaN; // NAN; - } - - // SUBNORMAL/NORMAL - if (exp == 0) - f = 0; - else - f = 1; - - // PROCESS MANTISSE - for (int i = 9; i >= 0; i--) { - f *= 2; - if ((man & (1 << i)) != 0) - f = f + 1; - } - //Debug.Log($"{f}"); - f = f * Mathf.Pow(2.0f, exp - 25); - if (exp == 0) { - f = f * Mathf.Pow(2.0f, -13); // 5.96046447754e-8; - } - //Debug.Log($"{f}"); - return sgn ? -f : f; - } - - ushort f32tof16(float f) { - //uint t = *(uint*)&f; - uint t = (uint)BitConverter.SingleToInt32Bits(f); - // man bits = 10; but we keep 11 for rounding - ushort man = (ushort)((t & 0x007FFFFF) >> 12); - short exp = (short)((t & 0x7F800000) >> 23); - bool sgn = (t & 0x80000000) != 0; - - // handle 0 - if ((t & 0x7FFFFFFF) == 0) { - return sgn ? (ushort)0x8000 : (ushort)0x0000; - } - // denormalized float32 does not fit in float16 - if (exp == 0x00) { - return sgn ? (ushort)0x8000 : (ushort)0x0000; - } - // handle infinity & NAN - if (exp == 0x00FF) { - if (man != 0) - return 0xFE00; // NAN - return sgn ? (ushort)0xFC00 : (ushort)0x7C00; // -INF : INF - } - - // normal numbers - exp = (short)(exp - 127 + 15); - // overflow does not fit => INF - if (exp > 30) { - return sgn ? (ushort)0xFC00 : (ushort)0x7C00; // -INF : INF - } - // subnormal numbers - if (exp < -38) { - return sgn ? (ushort)0x8000 : (ushort)0x0000; // -0 or 0 ? just 0 ? - } - if (exp <= 0) // subnormal - { - man >>= (exp + 14); - // rounding - man++; - man >>= 1; - if (sgn) - return (ushort)(0x8000 | man); - return man; - } - - // normal - // TODO rounding - exp <<= 10; - man++; - man >>= 1; - if (sgn) - return (ushort)(0x8000 | exp | man); - return (ushort)(exp | man); - } - - // -- END OF FILE -- -} diff --git a/Runtime/HumanoidControl/Scripts/Networking/Roboid/float16.cs.meta b/Runtime/HumanoidControl/Scripts/Networking/Roboid/float16.cs.meta deleted file mode 100644 index fc907e4..0000000 --- a/Runtime/HumanoidControl/Scripts/Networking/Roboid/float16.cs.meta +++ /dev/null @@ -1,11 +0,0 @@ -fileFormatVersion: 2 -guid: ebe91dca635b85f4f94fb2469970b423 -MonoImporter: - externalObjects: {} - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: