├── Assets ├── logo.png ├── Player.prefab ├── ExampleScene.unity ├── ExampleSceneFossilDelta.unity ├── ExampleScene.unity.meta ├── ColyseusClient.cs.meta ├── Enemy.cs ├── Player.cs ├── Entity.cs ├── Message.cs ├── State.cs ├── Plugins │ ├── Colyseus │ │ ├── Serializer │ │ │ ├── Serializer.cs │ │ │ ├── FossilDeltaSerializer.cs │ │ │ ├── Conversion │ │ │ │ ├── Endianness.cs │ │ │ │ ├── LittleEndianBitConverter.cs │ │ │ │ └── BigEndianBitConverter.cs │ │ │ └── SchemaSerializer.cs │ │ ├── Utils │ │ │ ├── HttpUtility.cs │ │ │ ├── ObjectExtensions.cs │ │ │ └── ExtensionMethods.cs │ │ ├── Properties │ │ │ └── AssemblyInfo.cs │ │ ├── Connection.cs │ │ ├── Protocol.cs │ │ ├── ColyseusManager.cs │ │ └── StateListener │ │ │ ├── Compare.cs │ │ │ └── StateContainer.cs │ ├── GameDevWare.Serialization │ │ ├── IValueInfo.cs │ │ ├── SerializationOptions.cs │ │ ├── GenerateTypeSerializerAttribute.cs │ │ ├── JsonToken.cs │ │ ├── TypeSerializer.cs │ │ ├── IJsonReader.cs │ │ ├── TypeSerializerAttribute.cs │ │ ├── MessagePack │ │ │ ├── MsgPackExtensionTypeHandler.cs │ │ │ ├── UnknownMsgPackFormatException.cs │ │ │ ├── UnknownMsgPackExtentionTypeException.cs │ │ │ ├── MsgPackType.cs │ │ │ ├── Endianness.cs │ │ │ ├── MsgPackTimestamp.cs │ │ │ ├── LittleEndianBitConverter.cs │ │ │ └── BigEndianBitConverter.cs │ │ ├── Serializers │ │ │ ├── UriSerializer.cs │ │ │ ├── VersionSerializer.cs │ │ │ ├── TimeSpanSerializer.cs │ │ │ ├── GuidSerializer.cs │ │ │ ├── Vector2Serializer.cs │ │ │ ├── DateTimeSerializer.cs │ │ │ ├── EnumNumberSerializer.cs │ │ │ ├── EnumSerializer.cs │ │ │ ├── MsgPackTimestampSerializer.cs │ │ │ ├── BoundsSerializer.cs │ │ │ ├── Vector3Serializer.cs │ │ │ ├── BinarySerializer.cs │ │ │ ├── DateTimeOffsetSerializer.cs │ │ │ ├── Vector4Serializer.cs │ │ │ ├── RectSerializer.cs │ │ │ ├── QuaternionSerializer.cs │ │ │ ├── StreamSerializer.cs │ │ │ ├── DictionaryEntrySerializer.cs │ │ │ ├── MsgPackExtensionTypeSerializer.cs │ │ │ ├── Matrix4x4Serializer.cs │ │ │ ├── ArraySerializer.cs │ │ │ └── PrimitiveTypeSerializer.cs │ │ ├── IJsonWriter.cs │ │ ├── Metadata │ │ │ ├── DataMemberDescription.cs │ │ │ ├── FieldDescription.cs │ │ │ ├── PropertyDescription.cs │ │ │ ├── MemberDescription.cs │ │ │ └── TypeDescription.cs │ │ ├── JsonTextReader.cs │ │ ├── JsonStreamReader.cs │ │ ├── JsonStringReader.cs │ │ ├── JsonStringBuilderReader.cs │ │ ├── JsonStreamWriter.cs │ │ ├── JsonTextWriter.cs │ │ ├── JsonStringBuilderWriter.cs │ │ ├── JsonMember.cs │ │ └── MsgPack.cs │ └── FossilDelta │ │ ├── Writer.cs │ │ ├── LICENSE │ │ ├── RollingHash.cs │ │ ├── Reader.cs │ │ └── README.md └── Editor │ └── ColyseusTests │ ├── Schema │ ├── InheritedTypes │ │ ├── Bot.cs │ │ ├── Player.cs │ │ ├── Entity.cs │ │ └── InheritedTypes.cs │ ├── BackwardsForwards │ │ ├── PlayerV1.cs │ │ ├── StateV1.cs │ │ ├── PlayerV2.cs │ │ └── StateV2.cs │ ├── ArraySchemaTypes │ │ ├── IAmAChild.cs │ │ └── ArraySchemaTypes.cs │ ├── ChildSchemaTypes │ │ ├── IAmAChild.cs │ │ └── ChildSchemaTypes.cs │ ├── MapSchemaTypes │ │ ├── IAmAChild.cs │ │ └── MapSchemaTypes.cs │ ├── MapSchemaInt8 │ │ └── MapSchemaInt8.cs │ └── PrimitiveTypes │ │ └── PrimitiveTypes.cs │ ├── ClientComponent.cs │ └── RoomTest.cs ├── .github └── ISSUE_TEMPLATE.md ├── ProjectSettings ├── AudioManager.asset ├── InputManager.asset ├── NavMeshAreas.asset ├── ProjectVersion.txt ├── TagManager.asset ├── TimeManager.asset ├── EditorSettings.asset ├── NetworkManager.asset ├── DynamicsManager.asset ├── GraphicsSettings.asset ├── Physics2DSettings.asset ├── ProjectSettings.asset ├── QualitySettings.asset ├── ClusterInputManager.asset ├── EditorBuildSettings.asset └── UnityConnectSettings.asset ├── Server ├── tsconfig.json ├── package.json ├── index.ts └── DemoRoom.ts ├── .editorconfig ├── .gitignore ├── LICENSE ├── azure-pipelines.yml └── README.md /Assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/Assets/logo.png -------------------------------------------------------------------------------- /Assets/Player.prefab: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/Assets/Player.prefab -------------------------------------------------------------------------------- /Assets/ExampleScene.unity: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/Assets/ExampleScene.unity -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 4 | -------------------------------------------------------------------------------- /ProjectSettings/AudioManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/AudioManager.asset -------------------------------------------------------------------------------- /ProjectSettings/InputManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/InputManager.asset -------------------------------------------------------------------------------- /ProjectSettings/NavMeshAreas.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/NavMeshAreas.asset -------------------------------------------------------------------------------- /ProjectSettings/ProjectVersion.txt: -------------------------------------------------------------------------------- 1 | m_EditorVersion: 2019.2.6f1 2 | m_EditorVersionWithRevision: 2019.2.6f1 (fe82a0e88406) 3 | -------------------------------------------------------------------------------- /ProjectSettings/TagManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/TagManager.asset -------------------------------------------------------------------------------- /ProjectSettings/TimeManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/TimeManager.asset -------------------------------------------------------------------------------- /Assets/ExampleSceneFossilDelta.unity: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/Assets/ExampleSceneFossilDelta.unity -------------------------------------------------------------------------------- /ProjectSettings/EditorSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/EditorSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/NetworkManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/NetworkManager.asset -------------------------------------------------------------------------------- /ProjectSettings/DynamicsManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/DynamicsManager.asset -------------------------------------------------------------------------------- /ProjectSettings/GraphicsSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/GraphicsSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/Physics2DSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/Physics2DSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/ProjectSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/ProjectSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/QualitySettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/QualitySettings.asset -------------------------------------------------------------------------------- /ProjectSettings/ClusterInputManager.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/ClusterInputManager.asset -------------------------------------------------------------------------------- /ProjectSettings/EditorBuildSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/EditorBuildSettings.asset -------------------------------------------------------------------------------- /ProjectSettings/UnityConnectSettings.asset: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stats/colyseus-unity3d/master/ProjectSettings/UnityConnectSettings.asset -------------------------------------------------------------------------------- /Server/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "module": "commonjs", 5 | "experimentalDecorators": true, 6 | "esModuleInterop": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*] 2 | end_of_line = lf 3 | charset = utf-8 4 | trim_trailing_whitespace = true 5 | indent_style = tab 6 | indent_size = 4 7 | 8 | [*.{js,ts}] 9 | indent_style = space 10 | indent_size = 2 11 | -------------------------------------------------------------------------------- /Assets/ExampleScene.unity.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: ed0a8eb3fa0fa413ea62f727658feb50 3 | timeCreated: 1478461878 4 | licenseType: Free 5 | DefaultImporter: 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /Assets/ColyseusClient.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: a3c711e869b6f47f6bb4ab688f168a71 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Assets/Enemy.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.5.5 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | public class Enemy : Entity { 11 | [Type(2, "number")] 12 | public float power = 0; 13 | } 14 | 15 | -------------------------------------------------------------------------------- /Assets/Player.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.5.5 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | public class Player : Entity { 11 | [Type(2, "boolean")] 12 | public bool connected = false; 13 | } 14 | 15 | -------------------------------------------------------------------------------- /Assets/Entity.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.5.5 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | public class Entity : Schema { 11 | [Type(0, "number")] 12 | public float x = 0; 13 | 14 | [Type(1, "number")] 15 | public float y = 0; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Assets/Message.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.5.5 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | public class Message : Schema { 11 | [Type(0, "number")] 12 | public float num = 0; 13 | 14 | [Type(1, "string")] 15 | public string str = ""; 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Assets/State.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.5.5 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | public class State : Schema { 11 | [Type(0, "map", typeof(MapSchema))] 12 | public MapSchema entities = new MapSchema(); 13 | } 14 | 15 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Serializer/Serializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using GameDevWare.Serialization; 3 | 4 | namespace Colyseus 5 | { 6 | public interface ISerializer 7 | { 8 | void SetState(byte[] data); 9 | T GetState(); 10 | //IndexedDictionary GetState(); 11 | void Patch(byte[] data); 12 | 13 | void Teardown (); 14 | void Handshake (byte[] bytes, int offset); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/InheritedTypes/Bot.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.32 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.InheritedTypes { 11 | public class Bot : Player { 12 | [Type(3, "number")] 13 | public float power = 0; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/InheritedTypes/Player.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.32 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.InheritedTypes { 11 | public class Player : Entity { 12 | [Type(2, "string")] 13 | public string name = ""; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/BackwardsForwards/PlayerV1.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.61 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.Backwards { 11 | public class PlayerV1 : Schema { 12 | [Type(0, "number")] 13 | public float x = 0; 14 | 15 | [Type(1, "number")] 16 | public float y = 0; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/InheritedTypes/Entity.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.32 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.InheritedTypes { 11 | public class Entity : Schema { 12 | [Type(0, "number")] 13 | public float x = 0; 14 | 15 | [Type(1, "number")] 16 | public float y = 0; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/ArraySchemaTypes/IAmAChild.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.54 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.ArraySchemaTypes { 11 | public class IAmAChild : Schema { 12 | [Type(0, "number")] 13 | public float x = 0; 14 | 15 | [Type(1, "number")] 16 | public float y = 0; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/ChildSchemaTypes/IAmAChild.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.32 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.ChildSchemaTypes { 11 | public class IAmAChild : Schema { 12 | [Type(0, "number")] 13 | public float x = 0; 14 | 15 | [Type(1, "number")] 16 | public float y = 0; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/MapSchemaTypes/IAmAChild.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.54 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.MapSchemaTypes { 11 | public class IAmAChild : Schema { 12 | [Type(0, "number")] 13 | public float x = 0; 14 | 15 | [Type(1, "number")] 16 | public float y = 0; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/MapSchemaInt8/MapSchemaInt8.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.54 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.MapSchemaInt8 { 11 | public class MapSchemaInt8 : Schema { 12 | [Type(0, "string")] 13 | public string status = ""; 14 | 15 | [Type(1, "map", "int8")] 16 | public MapSchema mapOfInt8 = new MapSchema(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/BackwardsForwards/StateV1.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.61 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.Backwards { 11 | public class StateV1 : Schema { 12 | [Type(0, "string")] 13 | public string str = ""; 14 | 15 | [Type(1, "map", typeof(MapSchema))] 16 | public MapSchema map = new MapSchema(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/ChildSchemaTypes/ChildSchemaTypes.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.32 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.ChildSchemaTypes { 11 | public class ChildSchemaTypes : Schema { 12 | [Type(0, "ref", typeof(IAmAChild))] 13 | public IAmAChild child = new IAmAChild(); 14 | 15 | [Type(1, "ref", typeof(IAmAChild))] 16 | public IAmAChild secondChild = new IAmAChild(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/BackwardsForwards/PlayerV2.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.61 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.Forwards { 11 | public class PlayerV2 : Schema { 12 | [Type(0, "number")] 13 | public float x = 0; 14 | 15 | [Type(1, "number")] 16 | public float y = 0; 17 | 18 | [Type(2, "string")] 19 | public string name = ""; 20 | 21 | [Type(3, "array", "string")] 22 | public ArraySchema arrayOfStrings = new ArraySchema(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/BackwardsForwards/StateV2.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.61 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.Forwards { 11 | public class StateV2 : Schema { 12 | [Type(0, "string")] 13 | public string str = ""; 14 | 15 | [System.Obsolete("field 'map' is deprecated.", true)] 16 | [Type(1, "map", typeof(MapSchema))] 17 | public MapSchema map = new MapSchema(); 18 | 19 | [Type(2, "number")] 20 | public float countdown = 0; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/InheritedTypes/InheritedTypes.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.32 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.InheritedTypes { 11 | public class InheritedTypes : Schema { 12 | [Type(0, "ref", typeof(Entity))] 13 | public Entity entity = new Entity(); 14 | 15 | [Type(1, "ref", typeof(Player))] 16 | public Player player = new Player(); 17 | 18 | [Type(2, "ref", typeof(Bot))] 19 | public Bot bot = new Bot(); 20 | 21 | [Type(3, "ref", typeof(Entity))] 22 | public Entity any; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/ClientComponent.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | using Colyseus; 4 | 5 | public class ClientComponent : MonoBehaviour 6 | { 7 | public Client client; 8 | public Room room; 9 | 10 | // Use this for initialization 11 | public async void Start () { 12 | client = new Client("ws://localhost:2567"); 13 | 14 | room = await client.Join("demo"); 15 | await room.Connect(); 16 | 17 | // OnApplicationQuit(); 18 | } 19 | 20 | async void OnDestroy () 21 | { 22 | // Make sure client will disconnect from the server 23 | await room.Leave (); 24 | } 25 | 26 | void OnApplicationQuit() 27 | { 28 | // Ensure the connection with server is closed immediatelly 29 | OnDestroy(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/RoomTest.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using UnityEngine.TestTools; 3 | using NUnit.Framework; 4 | using System.Threading.Tasks; 5 | 6 | 7 | public class RoomTest { 8 | ClientComponent component; 9 | 10 | [UnityTest] 11 | public async Task TestConnection() 12 | { 13 | var gameObject = new GameObject(); 14 | component = gameObject.AddComponent(); 15 | 16 | await Task.Run(() => 17 | { 18 | component.room.OnJoin += () => { 19 | Assert.NotNull(component.room.Id); 20 | Assert.NotNull(component.room.SessionId); 21 | }; 22 | 23 | component.room.OnStateChange += (State state, bool isFirstState) => { 24 | Assert.NotNull(component.room.State.entities); 25 | }; 26 | }); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/IValueInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | // ReSharper disable once CheckNamespace 4 | namespace GameDevWare.Serialization 5 | { 6 | public interface IValueInfo 7 | { 8 | bool HasValue { get; } 9 | object Raw { get; } 10 | Type Type { get; } 11 | bool AsBoolean { get; } 12 | byte AsByte { get; } 13 | short AsInt16 { get; } 14 | int AsInt32 { get; } 15 | long AsInt64 { get; } 16 | sbyte AsSByte { get; } 17 | ushort AsUInt16 { get; } 18 | uint AsUInt32 { get; } 19 | ulong AsUInt64 { get; } 20 | float AsSingle { get; } 21 | double AsDouble { get; } 22 | decimal AsDecimal { get; } 23 | string AsString { get; } 24 | DateTime AsDateTime { get; } 25 | 26 | int LineNumber { get; } 27 | int ColumnNumber { get; } 28 | } 29 | } -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/MapSchemaTypes/MapSchemaTypes.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.54 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.MapSchemaTypes { 11 | public class MapSchemaTypes : Schema { 12 | [Type(0, "map", typeof(MapSchema))] 13 | public MapSchema mapOfSchemas = new MapSchema(); 14 | 15 | [Type(1, "map", "number")] 16 | public MapSchema mapOfNumbers = new MapSchema(); 17 | 18 | [Type(2, "map", "string")] 19 | public MapSchema mapOfStrings = new MapSchema(); 20 | 21 | [Type(3, "map", "int32")] 22 | public MapSchema mapOfInt32 = new MapSchema(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "colyseus-unity3d", 3 | "private": true, 4 | "repository": { 5 | "type": "git", 6 | "url": "git://github.com/gamestdio/colyseus-unity3d.git" 7 | }, 8 | "scripts": { 9 | "schema-codegen": "schema-codegen DemoRoom.ts --csharp --output ../Assets/", 10 | "start": "nodemon --watch '**.ts' --exec ts-node ./index.ts" 11 | }, 12 | "engines": { 13 | "node": ">= 8.x" 14 | }, 15 | "dependencies": { 16 | "@colyseus/social": "^0.10.0", 17 | "colyseus": "^0.11.23-beta.1", 18 | "cors": "^2.8.5", 19 | "express": "^4.13.3", 20 | "express-jwt": "^5.3.1", 21 | "typescript": "^3.3.4000" 22 | }, 23 | "devDependencies": { 24 | "@types/express": "^4.16.1", 25 | "@types/node": "^11.12.0", 26 | "nodemon": "^1.18.10", 27 | "ts-node": "^8.0.3" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/ArraySchemaTypes/ArraySchemaTypes.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.54 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.ArraySchemaTypes { 11 | public class ArraySchemaTypes : Schema { 12 | [Type(0, "array", typeof(ArraySchema))] 13 | public ArraySchema arrayOfSchemas = new ArraySchema(); 14 | 15 | [Type(1, "array", "number")] 16 | public ArraySchema arrayOfNumbers = new ArraySchema(); 17 | 18 | [Type(2, "array", "string")] 19 | public ArraySchema arrayOfStrings = new ArraySchema(); 20 | 21 | [Type(3, "array", "int32")] 22 | public ArraySchema arrayOfInt32 = new ArraySchema(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | #User Specific 2 | *.userprefs 3 | *.usertasks 4 | .DS_Store 5 | .vs/ 6 | 7 | #Mono Project Files 8 | *.pidb 9 | *.resources 10 | test-results/ 11 | bin 12 | obj 13 | 14 | #NuGet packages 15 | Colyseus/packages 16 | !packages/repositories.config 17 | 18 | # Node.js 19 | node_modules 20 | npm-debug.log 21 | package-lock.json 22 | 23 | # Unity 24 | /[Ll]ibrary/ 25 | /[Tt]emp/ 26 | /[Oo]bj/ 27 | /[Bb]uild/ 28 | /[Bb]uilds/ 29 | /Assets/AssetStoreTools* 30 | 31 | # Autogenerated VS/MD/Consulo solution and project files 32 | ExportedObj/ 33 | .consulo/ 34 | *.csproj 35 | *.unityproj 36 | *.sln 37 | *.suo 38 | *.tmp 39 | *.user 40 | *.userprefs 41 | *.pidb 42 | *.booproj 43 | *.svd 44 | 45 | 46 | # Unity3D generated meta files 47 | *.pidb.meta 48 | *.meta 49 | 50 | # Unity3D Generated File On Crash Reports 51 | sysinfo.txt 52 | 53 | # Builds 54 | *.apk 55 | *.unitypackage 56 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Utils/HttpUtility.cs: -------------------------------------------------------------------------------- 1 | #if !NET_LEGACY 2 | 3 | using System.Text; 4 | using System.Collections.Specialized; 5 | using System.Net; 6 | 7 | namespace Colyseus 8 | { 9 | public class HttpQSCollection : NameValueCollection 10 | { 11 | public override string ToString() 12 | { 13 | int count = Count; 14 | if (count == 0) 15 | return ""; 16 | StringBuilder sb = new StringBuilder(); 17 | string[] keys = AllKeys; 18 | for (int i = 0; i < count; i++) 19 | { 20 | sb.AppendFormat("{0}={1}&", keys[i], WebUtility.UrlEncode(this[keys[i]])); 21 | } 22 | if (sb.Length > 0) 23 | sb.Length--; 24 | return sb.ToString(); 25 | } 26 | } 27 | 28 | public class HttpUtility 29 | { 30 | public static HttpQSCollection ParseQueryString(string str) 31 | { 32 | return new HttpQSCollection(); 33 | } 34 | } 35 | 36 | } 37 | 38 | #endif -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Utils/ObjectExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | using System.Text; 6 | 7 | namespace Colyseus 8 | { 9 | public static class ObjectExtensions 10 | { 11 | public static T ToObject(object source) where T : class, new() 12 | { 13 | var someObject = new T(); 14 | var someObjectType = someObject.GetType(); 15 | 16 | foreach (var item in (IDictionary)source) { 17 | var prop = someObjectType.GetProperty(item.Key); 18 | try 19 | { 20 | prop.SetValue(someObject, Convert.ChangeType(item.Value, prop.PropertyType), null); 21 | 22 | } catch (OverflowException) { 23 | // workaround for parsing Infinity on RoomAvailable.maxClients 24 | prop.SetValue(someObject, uint.MaxValue, null); 25 | } 26 | } 27 | 28 | return someObject; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Utils/ExtensionMethods.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Runtime.CompilerServices; 3 | 4 | using UnityEngine; 5 | using UnityEngine.Networking; 6 | 7 | public class UnityWebRequestAwaiter : INotifyCompletion 8 | { 9 | private UnityWebRequestAsyncOperation asyncOp; 10 | private Action continuation; 11 | 12 | public UnityWebRequestAwaiter(UnityWebRequestAsyncOperation asyncOp) 13 | { 14 | this.asyncOp = asyncOp; 15 | asyncOp.completed += OnRequestCompleted; 16 | } 17 | 18 | public bool IsCompleted { get { return asyncOp.isDone; } } 19 | 20 | public void GetResult() { } 21 | 22 | public void OnCompleted(Action continuation) 23 | { 24 | this.continuation = continuation; 25 | } 26 | 27 | private void OnRequestCompleted(AsyncOperation obj) 28 | { 29 | continuation(); 30 | } 31 | } 32 | 33 | public static class ExtensionMethods 34 | { 35 | public static UnityWebRequestAwaiter GetAwaiter(this UnityWebRequestAsyncOperation asyncOp) 36 | { 37 | return new UnityWebRequestAwaiter(asyncOp); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Server/index.ts: -------------------------------------------------------------------------------- 1 | import http from "http"; 2 | import express from "express"; 3 | import cors from "cors"; 4 | 5 | import { Server, serialize, FossilDeltaSerializer } from "colyseus"; 6 | import { DemoRoom } from "./DemoRoom"; 7 | 8 | import socialRoutes from "@colyseus/social/express"; 9 | 10 | const PORT = Number(process.env.PORT || 2567); 11 | 12 | const app = express(); 13 | 14 | /** 15 | * CORS should be used during development only. 16 | * Please remove CORS on production, unless you're hosting the server and client on different domains. 17 | */ 18 | app.use(cors()); 19 | 20 | const gameServer = new Server({ 21 | server: http.createServer(app), 22 | pingInterval: 0, 23 | }); 24 | 25 | // Register DemoRoom as "demo" 26 | gameServer.define("demo", DemoRoom); 27 | 28 | app.use("/", socialRoutes); 29 | 30 | app.get("/something", function (req, res) { 31 | console.log("something!", process.pid); 32 | res.send("Hey!"); 33 | }); 34 | 35 | // Listen on specified PORT number 36 | gameServer.listen(PORT); 37 | 38 | console.log("Running on ws://localhost:" + PORT); 39 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/SerializationOptions.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization 20 | { 21 | [Flags] 22 | public enum SerializationOptions 23 | { 24 | None = 0, 25 | SuppressTypeInformation = 0x1 << 1, 26 | PrettyPrint = 0x1 << 2, 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015-2016 Endel Dreyer 2 | 3 | MIT License: 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/GenerateTypeSerializerAttribute.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization 20 | { 21 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] 22 | public class GenerateTypeSerializerAttribute : Attribute 23 | { 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/JsonToken.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | // ReSharper disable once CheckNamespace 18 | namespace GameDevWare.Serialization 19 | { 20 | public enum JsonToken 21 | { 22 | None = 0, 23 | BeginArray, 24 | EndOfArray, 25 | BeginObject, 26 | EndOfObject, 27 | Member, 28 | Number, 29 | StringLiteral, 30 | DateTime, 31 | Null, 32 | Boolean, 33 | EndOfStream 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | 4 | // Information about this assembly is defined by the following attributes. 5 | // Change them to the values specific to your project. 6 | 7 | [assembly: AssemblyTitle("Colyseus")] 8 | [assembly: AssemblyDescription("C#/Unity3D client for Colyseus Multiplayer Game Server")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("gamestd.io")] 11 | [assembly: AssemblyProduct("Colyseus")] 12 | [assembly: AssemblyCopyright("Copyright © 2016")] 13 | [assembly: AssemblyTrademark ("")] 14 | [assembly: AssemblyCulture ("")] 15 | 16 | // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". 17 | // The form "{Major}.{Minor}.*" will automatically update the build and revision, 18 | // and "{Major}.{Minor}.{Build}.*" will update just the revision. 19 | 20 | [assembly: AssemblyVersion ("0.1.0.0")] 21 | 22 | // The following attributes are used to specify the signing key for the assembly, 23 | // if desired. See the Mono documentation for more information about signing. 24 | 25 | //[assembly: AssemblyDelaySign(false)] 26 | //[assembly: AssemblyKeyFile("")] 27 | 28 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/TypeSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | using System; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public abstract class TypeSerializer 23 | { 24 | public abstract Type SerializedType { get; } 25 | 26 | public abstract object Deserialize(IJsonReader reader); 27 | public abstract void Serialize(IJsonWriter writer, object value); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Serializer/FossilDeltaSerializer.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using System.IO; 3 | using GameDevWare.Serialization; 4 | 5 | namespace Colyseus 6 | { 7 | /* public class FossilDeltaSerializer : Serializer */ 8 | public class FossilDeltaSerializer : ISerializer> 9 | { 10 | public StateContainer State = new StateContainer(new IndexedDictionary()); 11 | protected byte[] previousState = null; 12 | 13 | public void SetState(byte[] encodedState) 14 | { 15 | State.Set(MsgPack.Deserialize> (new MemoryStream(encodedState))); 16 | previousState = encodedState; 17 | } 18 | 19 | public IndexedDictionary GetState() 20 | { 21 | return State.state; 22 | } 23 | 24 | public void Patch(byte[] bytes) 25 | { 26 | previousState = Fossil.Delta.Apply (previousState, bytes); 27 | var newState = MsgPack.Deserialize> (new MemoryStream(previousState)); 28 | State.Set(newState); 29 | } 30 | 31 | public void Teardown () 32 | { 33 | State.RemoveAllListeners(); 34 | } 35 | 36 | public void Handshake (byte[] bytes, int offset) 37 | { 38 | Debug.Log("Handshake FossilDeltaSerializer!"); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/IJsonReader.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | // ReSharper disable once CheckNamespace 18 | namespace GameDevWare.Serialization 19 | { 20 | public interface IJsonReader 21 | { 22 | SerializationContext Context { get; } 23 | 24 | JsonToken Token { get; } 25 | object RawValue { get; } 26 | IValueInfo Value { get; } 27 | 28 | bool NextToken(); 29 | 30 | bool IsEndOfStream(); 31 | 32 | /// 33 | /// Resets Line/Column numbers, CharactersReaded and Token information of reader 34 | /// 35 | void Reset(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Assets/Plugins/FossilDelta/Writer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace Fossil 5 | { 6 | public class Writer 7 | { 8 | static readonly uint[] zDigits = { 9 | '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 10 | 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 11 | 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_', 'a', 'b', 'c', 'd', 'e', 12 | 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 13 | 't', 'u', 'v', 'w', 'x', 'y', 'z', '~' 14 | }; 15 | 16 | private List a; 17 | 18 | public Writer () 19 | { 20 | this.a = new List(); 21 | } 22 | 23 | public void PutChar (char c) 24 | { 25 | this.a.Add ((byte) c); 26 | } 27 | 28 | public void PutInt (uint v) 29 | { 30 | int i, j; 31 | uint[] zBuf = new uint[20]; 32 | 33 | if (v == 0) { 34 | this.PutChar ('0'); 35 | return; 36 | } 37 | for (i = 0; v > 0; i++, v>>=6) { 38 | zBuf[i] = zDigits[v&0x3f]; 39 | } 40 | for (j = i - 1; j >= 0; j--) { 41 | this.a.Add ((byte) zBuf [j]); 42 | } 43 | } 44 | 45 | public void PutArray (byte[] a, int start, int end) { 46 | for (var i = start; i < end; i++) this.a.Add(a[i]); 47 | } 48 | 49 | public byte[] ToArray () 50 | { 51 | return this.a.ToArray(); 52 | } 53 | 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Connection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Collections.Generic; 4 | using System.Threading.Tasks; 5 | 6 | using NativeWebSocket; 7 | using GameDevWare.Serialization; 8 | 9 | namespace Colyseus 10 | { 11 | 12 | public class Connection : WebSocket 13 | { 14 | public bool IsOpen = false; 15 | protected Queue _enqueuedCalls = new Queue(); 16 | 17 | public Connection(string url, Dictionary headers) : base(url, headers) 18 | { 19 | Initialize(); 20 | } 21 | 22 | private void Initialize() 23 | { 24 | OnOpen += _OnOpen; 25 | OnClose += _OnClose; 26 | } 27 | 28 | public async Task Send(object[] data) 29 | { 30 | var serializationOutput = new MemoryStream (); 31 | MsgPack.Serialize (data, serializationOutput); 32 | 33 | byte[] packedData = serializationOutput.ToArray (); 34 | 35 | if (!this.IsOpen) { 36 | _enqueuedCalls.Enqueue(packedData); 37 | 38 | } else { 39 | 40 | await Send(packedData); 41 | } 42 | } 43 | 44 | protected async void _OnOpen () 45 | { 46 | IsOpen = true; 47 | 48 | // send enqueued commands while connection wasn't open 49 | if (_enqueuedCalls.Count > 0) { 50 | do { 51 | await Send(_enqueuedCalls.Dequeue()); 52 | } while (_enqueuedCalls.Count > 0); 53 | } 54 | } 55 | 56 | protected void _OnClose (WebSocketCloseCode code) 57 | { 58 | IsOpen = false; 59 | } 60 | } 61 | } 62 | 63 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/TypeSerializerAttribute.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | using System; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] 23 | public class TypeSerializerAttribute : Attribute 24 | { 25 | public Type SerializerType { get; private set; } 26 | 27 | public TypeSerializerAttribute(Type type) 28 | { 29 | if (type == null) throw new ArgumentNullException("type"); 30 | if (typeof(TypeSerializer).IsAssignableFrom(type) == false) throw new ArgumentException(string.Format("Type '{0}' should inherit from '{1}'.", type, typeof(TypeSerializer)), "type"); 31 | 32 | this.SerializerType = type; 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/MessagePack/MsgPackExtensionTypeHandler.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Linq; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.MessagePack 22 | { 23 | public abstract class MessagePackExtensionTypeHandler 24 | { 25 | public abstract IEnumerable ExtensionTypes { get; } 26 | 27 | public abstract bool TryRead(sbyte type, ArraySegment data, out object value); 28 | public abstract bool TryWrite(object value, out sbyte type, ref ArraySegment data); 29 | 30 | /// 31 | public override string ToString() 32 | { 33 | return string.Format("Extension Types: {0}", string.Join(", ", this.ExtensionTypes.Select(t => t.ToString()).ToArray())); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/UriSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class UriSerializer : TypeSerializer 22 | { 23 | public override Type SerializedType { get { return typeof(Uri); } } 24 | 25 | public override object Deserialize(IJsonReader reader) 26 | { 27 | if (reader == null) throw new ArgumentNullException("reader"); 28 | 29 | var uriStr = reader.ReadString(false); 30 | var value = new Uri(uriStr); 31 | return value; 32 | } 33 | 34 | public override void Serialize(IJsonWriter writer, object value) 35 | { 36 | if (writer == null) throw new ArgumentNullException("writer"); 37 | if (value == null) throw new ArgumentNullException("value"); 38 | 39 | var uri = (Uri)value; 40 | writer.WriteString(uri.OriginalString); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/MessagePack/UnknownMsgPackFormatException.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Runtime.Serialization; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.MessagePack 21 | { 22 | [Serializable] 23 | public sealed class UnknownMsgPackFormatException : SerializationException 24 | { 25 | public UnknownMsgPackFormatException(string message, Exception innerException) : base(message, innerException) 26 | { 27 | } 28 | 29 | public UnknownMsgPackFormatException(string message) : base(message) 30 | { 31 | } 32 | 33 | public UnknownMsgPackFormatException(byte invalidValue) 34 | : base(string.Format("Unknown MessagePack format '{0}' was readed from stream.", invalidValue)) 35 | { 36 | } 37 | 38 | private UnknownMsgPackFormatException(SerializationInfo info, StreamingContext context) 39 | : base(info, context) 40 | { 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/VersionSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class VersionSerializer : TypeSerializer 22 | { 23 | public override Type SerializedType { get { return typeof(Version); } } 24 | 25 | public override object Deserialize(IJsonReader reader) 26 | { 27 | if (reader == null) throw new ArgumentNullException("reader"); 28 | 29 | var versionStr = reader.ReadString(false); 30 | var value = new Version(versionStr); 31 | return value; 32 | } 33 | 34 | public override void Serialize(IJsonWriter writer, object value) 35 | { 36 | if (writer == null) throw new ArgumentNullException("writer"); 37 | if (value == null) throw new ArgumentNullException("value"); 38 | 39 | var version = (Version)value; 40 | writer.WriteString(version.ToString()); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Protocol.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Colyseus 4 | { 5 | /// 6 | /// Colyseus server protocol codes mapping. 7 | /// 8 | public class Protocol 9 | { 10 | /// When client receives its unique id. 11 | public static int USER_ID = 1; 12 | 13 | // 14 | // Room-related (9~19) 15 | // 16 | 17 | /// When JOIN is requested. 18 | public static int JOIN_REQUEST = 9; 19 | 20 | /// When JOIN request is accepted. 21 | public static int JOIN_ROOM = 10; 22 | 23 | /// When JOIN request is not accepted. 24 | public static int JOIN_ERROR = 11; 25 | 26 | /// When server explicitly removes from the 27 | public static int LEAVE_ROOM = 12; 28 | 29 | /// When server sends data to a particular 30 | public static int ROOM_DATA = 13; 31 | 32 | /// When server sends state to its clients. 33 | public static int ROOM_STATE = 14; 34 | 35 | /// When server sends state to its clients. 36 | public static int ROOM_STATE_PATCH = 15; 37 | 38 | /// When server sends a Schema-encoded message. 39 | public static int ROOM_DATA_SCHEMA = 16; 40 | 41 | // 42 | // Matchmaking messages (20~30) 43 | // 44 | public static int ROOM_LIST = 20; 45 | 46 | // 47 | // Generic messages (50~60) 48 | // 49 | 50 | /// When server doesn't understand a request, it returns to the 51 | public static int BAD_REQUEST = 50; 52 | 53 | // public Protocol (){} 54 | } 55 | } 56 | 57 | -------------------------------------------------------------------------------- /Assets/Plugins/FossilDelta/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2016 Endel Dreyer (C# port) 2 | Copyright 2014 Dmitry Chestnykh (JavaScript port) 3 | Copyright 2007 D. Richard Hipp (original C version) 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or 7 | without modification, are permitted provided that the 8 | following conditions are met: 9 | 10 | 1. Redistributions of source code must retain the above 11 | copyright notice, this list of conditions and the 12 | following disclaimer. 13 | 14 | 2. Redistributions in binary form must reproduce the above 15 | copyright notice, this list of conditions and the 16 | following disclaimer in the documentation and/or other 17 | materials provided with the distribution. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS 20 | OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 | ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE 23 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 24 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 25 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR 26 | BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 27 | WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 28 | OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 29 | EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | 31 | The views and conclusions contained in the software and documentation 32 | are those of the authors and contributors and should not be interpreted 33 | as representing official policies, either expressed or implied, of anybody 34 | else. 35 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/MessagePack/UnknownMsgPackExtentionTypeException.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Runtime.Serialization; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.MessagePack 21 | { 22 | [Serializable] 23 | public sealed class UnknownMsgPackExtentionTypeException : SerializationException 24 | { 25 | public UnknownMsgPackExtentionTypeException(string message, Exception innerException) : base(message, innerException) 26 | { 27 | } 28 | 29 | public UnknownMsgPackExtentionTypeException(string message) : base(message) 30 | { 31 | } 32 | 33 | public UnknownMsgPackExtentionTypeException(sbyte invalidExtType) 34 | : base(string.Format("Unknown MessagePack extention type '{0}' was readed from stream.", invalidExtType)) 35 | { 36 | } 37 | 38 | private UnknownMsgPackExtentionTypeException(SerializationInfo info, StreamingContext context) 39 | : base(info, context) 40 | { 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/IJsonWriter.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization 20 | { 21 | public interface IJsonWriter 22 | { 23 | SerializationContext Context { get; } 24 | 25 | void Flush(); 26 | 27 | void Write(string value); 28 | void Write(JsonMember value); 29 | void Write(int number); 30 | void Write(uint number); 31 | void Write(long number); 32 | void Write(ulong number); 33 | void Write(float number); 34 | void Write(double number); 35 | void Write(decimal number); 36 | void Write(bool value); 37 | void Write(DateTime dateTime); 38 | void Write(DateTimeOffset dateTimeOffset); 39 | void WriteObjectBegin(int numberOfMembers); 40 | void WriteObjectEnd(); 41 | void WriteArrayBegin(int numberOfMembers); 42 | void WriteArrayEnd(); 43 | void WriteNull(); 44 | 45 | void WriteJson(string jsonString); 46 | void WriteJson(char[] jsonString, int index, int charCount); 47 | 48 | void Reset(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Metadata/DataMemberDescription.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.ComponentModel; 18 | using System.Linq; 19 | using System.Reflection; 20 | 21 | // ReSharper disable once CheckNamespace 22 | namespace GameDevWare.Serialization.Metadata 23 | { 24 | internal abstract class DataMemberDescription : MemberDescription 25 | { 26 | public abstract bool CanGet { get; } 27 | public abstract bool CanSet { get; } 28 | public object DefaultValue { get; private set; } 29 | public abstract Type ValueType { get; } 30 | 31 | protected DataMemberDescription(TypeDescription typeDescription, MemberInfo member) 32 | : base(typeDescription, member) 33 | { 34 | var defaultValue = 35 | (DefaultValueAttribute) this.GetAttributesOrEmptyList(typeof (DefaultValueAttribute)).FirstOrDefault(); 36 | if (defaultValue != null) 37 | this.DefaultValue = defaultValue.Value; 38 | } 39 | 40 | public abstract object GetValue(object target); 41 | public abstract void SetValue(object target, object value); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Assets/Editor/ColyseusTests/Schema/PrimitiveTypes/PrimitiveTypes.cs: -------------------------------------------------------------------------------- 1 | // 2 | // THIS FILE HAS BEEN GENERATED AUTOMATICALLY 3 | // DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING 4 | // 5 | // GENERATED USING @colyseus/schema 0.4.32 6 | // 7 | 8 | using Colyseus.Schema; 9 | 10 | namespace SchemaTest.PrimitiveTypes { 11 | public class PrimitiveTypes : Schema { 12 | [Type(0, "int8")] 13 | public int int8 = 0; 14 | 15 | [Type(1, "uint8")] 16 | public uint uint8 = 0; 17 | 18 | [Type(2, "int16")] 19 | public short int16 = 0; 20 | 21 | [Type(3, "uint16")] 22 | public ushort uint16 = 0; 23 | 24 | [Type(4, "int32")] 25 | public int int32 = 0; 26 | 27 | [Type(5, "uint32")] 28 | public uint uint32 = 0; 29 | 30 | [Type(6, "int64")] 31 | public long int64 = 0; 32 | 33 | [Type(7, "uint64")] 34 | public ulong uint64 = 0; 35 | 36 | [Type(8, "float32")] 37 | public float float32 = 0; 38 | 39 | [Type(9, "float64")] 40 | public double float64 = 0; 41 | 42 | [Type(10, "number")] 43 | public float varint_int8 = 0; 44 | 45 | [Type(11, "number")] 46 | public float varint_uint8 = 0; 47 | 48 | [Type(12, "number")] 49 | public float varint_int16 = 0; 50 | 51 | [Type(13, "number")] 52 | public float varint_uint16 = 0; 53 | 54 | [Type(14, "number")] 55 | public float varint_int32 = 0; 56 | 57 | [Type(15, "number")] 58 | public float varint_uint32 = 0; 59 | 60 | [Type(16, "number")] 61 | public float varint_int64 = 0; 62 | 63 | [Type(17, "number")] 64 | public float varint_uint64 = 0; 65 | 66 | [Type(18, "number")] 67 | public float varint_float32 = 0; 68 | 69 | [Type(19, "number")] 70 | public float varint_float64 = 0; 71 | 72 | [Type(20, "string")] 73 | public string str = ""; 74 | 75 | [Type(21, "boolean")] 76 | public bool boolean = false; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/JsonTextReader.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.IO; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public sealed class JsonTextReader : JsonReader 23 | { 24 | private readonly TextReader reader; 25 | 26 | public JsonTextReader(TextReader reader, SerializationContext context, int bufferSize = DEFAULT_BUFFER_SIZE) 27 | : base(context, bufferSize) 28 | { 29 | if (reader == null) 30 | throw new ArgumentNullException("reader"); 31 | 32 | 33 | this.reader = reader; 34 | } 35 | 36 | protected override int FillBuffer(char[] buffer, int index) 37 | { 38 | if (buffer == null) 39 | throw new ArgumentNullException("buffer"); 40 | if (index < 0 || index >= buffer.Length) 41 | throw new ArgumentOutOfRangeException("index"); 42 | 43 | 44 | var count = buffer.Length - index; 45 | if (count <= 0) 46 | return index; 47 | 48 | var readed = reader.Read(buffer, index, count); 49 | return index + readed; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/TimeSpanSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class TimeSpanSerializer : TypeSerializer 22 | { 23 | public override Type SerializedType { get { return typeof(TimeSpan); } } 24 | 25 | public override object Deserialize(IJsonReader reader) 26 | { 27 | if (reader == null) throw new ArgumentNullException("reader"); 28 | 29 | if (reader.Token == JsonToken.Number) 30 | return new TimeSpan(reader.Value.AsInt64); 31 | 32 | var timeSpanStr = reader.ReadString(false); 33 | var value = TimeSpan.Parse(timeSpanStr); 34 | return value; 35 | } 36 | 37 | public override void Serialize(IJsonWriter writer, object value) 38 | { 39 | if (writer == null) throw new ArgumentNullException("writer"); 40 | if (value == null) throw new ArgumentNullException("value"); 41 | 42 | var timeSpan = (TimeSpan)value; 43 | writer.Write((long)timeSpan.Ticks); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # Add steps that build, run tests, deploy, and more: 2 | # https://aka.ms/yaml 3 | 4 | trigger: 5 | batch: true 6 | branches: 7 | include: 8 | - master 9 | - release/* 10 | 11 | stages: 12 | - stage: build 13 | jobs: 14 | - job: build 15 | pool: 16 | vmImage: 'windows-latest' 17 | steps: 18 | - task: PublishBuildArtifacts@1 19 | displayName: 'Publish Artifact: plugins' 20 | inputs: 21 | PathtoPublish: Assets/Plugins 22 | ArtifactName: plugins 23 | - stage: release 24 | dependsOn: build 25 | condition: and(succeeded(), startsWith(variables['Build.SourceBranch'], 'refs/heads/release/')) 26 | jobs: 27 | - job: github_release 28 | pool: 29 | vmImage: 'windows-latest' 30 | steps: 31 | - task: DownloadBuildArtifacts@0 32 | inputs: 33 | artifactName: plugins 34 | buildType: 'current' 35 | downloadType: 'single' 36 | downloadPath: '$(System.ArtifactsDirectory)' 37 | - task: ArchiveFiles@2 38 | inputs: 39 | rootFolderOrFile: '$(System.ArtifactsDirectory)/plugins' 40 | includeRootFolder: true 41 | archiveType: 'zip' 42 | archiveFile: '$(Build.ArtifactStagingDirectory)/plugins-$(Build.SourceBranchName).zip' 43 | replaceExistingArchive: true 44 | - task: GitHubRelease@1 45 | displayName: 'GitHub release (create)' 46 | inputs: 47 | gitHubConnection: 'github connection 2' 48 | repositoryName: '$(Build.Repository.Name)' 49 | action: 'create' 50 | target: '$(Build.SourceVersion)' 51 | tagSource: 'userSpecifiedTag' 52 | tag: '$(Build.SourceBranchName)' 53 | title: '$(Build.SourceBranchName)' 54 | assets: '$(Build.ArtifactStagingDirectory)/*.zip' 55 | isDraft: true 56 | changeLogCompareToRelease: 'lastFullRelease' 57 | changeLogType: 'commitBased' -------------------------------------------------------------------------------- /Assets/Plugins/FossilDelta/RollingHash.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Fossil 4 | { 5 | public class RollingHash 6 | { 7 | private UInt16 a; 8 | private UInt16 b; 9 | private UInt16 i; 10 | private byte[] z; 11 | static int ii = 0; 12 | 13 | public RollingHash () 14 | { 15 | this.a = 0; 16 | this.b = 0; 17 | this.i = 0; 18 | this.z = new byte[Delta.NHASH]; 19 | } 20 | 21 | /** 22 | * Initialize the rolling hash using the first NHASH characters of z[] 23 | */ 24 | public void Init (byte[] z, int pos) 25 | { 26 | UInt16 a = 0, b = 0, i, x; 27 | for(i = 0; i < Delta.NHASH; i++){ 28 | x = z[pos+i]; 29 | a = (UInt16) ((a + x) & 0xffff); 30 | b = (UInt16) ((b + (Delta.NHASH-i)*x) & 0xffff); 31 | this.z[i] = (byte) x; 32 | } 33 | this.a = (UInt16) (a & 0xffff); 34 | this.b = (UInt16) (b & 0xffff); 35 | this.i = 0; 36 | } 37 | 38 | /** 39 | * Advance the rolling hash by a single character "c" 40 | */ 41 | public void Next (byte c) { 42 | UInt16 old = this.z[this.i]; 43 | this.z[this.i] = c; 44 | this.i = (UInt16) ((this.i+1)&(Delta.NHASH-1)); 45 | this.a = (UInt16) (this.a - old + c); 46 | this.b = (UInt16) (this.b - Delta.NHASH*old + this.a); 47 | } 48 | 49 | 50 | /** 51 | * Return a 32-bit hash value 52 | */ 53 | public UInt32 Value () { 54 | RollingHash.ii ++; 55 | return (UInt32) (((UInt32)(this.a & 0xffff)) | (((UInt32)(this.b & 0xffff)) << 16)); 56 | } 57 | 58 | /* 59 | * Compute a hash on NHASH bytes. 60 | * 61 | * This routine is intended to be equivalent to: 62 | * hash h; 63 | * hash_init(&h, zInput); 64 | * return hash_32bit(&h); 65 | */ 66 | public static UInt32 Once (byte[] z) { 67 | UInt16 a, b, i; 68 | a = b = z[0]; 69 | for(i=1; i= buffer.Length) 41 | throw new ArgumentOutOfRangeException("index"); 42 | 43 | 44 | var count = buffer.Length - index; 45 | if (count <= 0) 46 | return index; 47 | 48 | var readed = reader.Read(buffer, index, count); 49 | return index + readed; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/MessagePack/MsgPackType.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | 17 | // ReSharper disable once CheckNamespace 18 | namespace GameDevWare.Serialization.MessagePack 19 | { 20 | public enum MsgPackType : byte 21 | { 22 | PositiveFixIntStart = 0x00, 23 | PositiveFixIntEnd = 0x7f, 24 | FixMapStart = 0x80, 25 | FixMapEnd = 0x8f, 26 | FixArrayStart = 0x90, 27 | FixArrayEnd = 0x9f, 28 | FixStrStart = 0xa0, 29 | FixStrEnd = 0xbf, 30 | Nil = 0xc0, 31 | Unused = 0xc1, 32 | False = 0xc2, 33 | True = 0xc3, 34 | Bin8 = 0xc4, 35 | Bin16 = 0xc5, 36 | Bin32 = 0xc6, 37 | Ext8 = 0xc7, 38 | Ext16 = 0xc8, 39 | Ext32 = 0xc9, 40 | Float32 = 0xca, 41 | Float64 = 0xcb, 42 | UInt8 = 0xcc, 43 | UInt16 = 0xcd, 44 | UInt32 = 0xce, 45 | UInt64 = 0xcf, 46 | Int8 = 0xd0, 47 | Int16 = 0xd1, 48 | Int32 = 0xd2, 49 | Int64 = 0xd3, 50 | FixExt1 = 0xd4, 51 | FixExt2 = 0xd5, 52 | FixExt4 = 0xd6, 53 | FixExt8 = 0xd7, 54 | FixExt16 = 0xd8, 55 | Str8 = 0xd9, 56 | Str16 = 0xda, 57 | Str32 = 0xdb, 58 | Array16 = 0xdc, 59 | Array32 = 0xdd, 60 | Map16 = 0xde, 61 | Map32 = 0xdf, 62 | NegativeFixIntStart = 0xe0, 63 | NegativeFixIntEnd = 0xff 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /Assets/Plugins/FossilDelta/Reader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | 4 | namespace Fossil 5 | { 6 | public class Reader 7 | { 8 | static readonly int[] zValue = { 9 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 11 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 12 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, 13 | -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 14 | 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36, 15 | -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 16 | 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1 17 | }; 18 | 19 | public byte[] a; 20 | public uint pos; 21 | 22 | public Reader (byte[] array) 23 | { 24 | this.a = array; 25 | this.pos = 0; 26 | } 27 | 28 | public bool HaveBytes () 29 | { 30 | return this.pos < this.a.Length; 31 | } 32 | 33 | public byte GetByte () 34 | { 35 | byte b = this.a[this.pos]; 36 | this.pos++; 37 | if (this.pos > this.a.Length) 38 | throw new IndexOutOfRangeException("out of bounds"); 39 | return b; 40 | } 41 | 42 | public char GetChar() 43 | { 44 | // return String.fromCharCode(this.getByte()); 45 | return (char) this.GetByte(); 46 | } 47 | 48 | /** 49 | * Read bytes from *pz and convert them into a positive integer. When 50 | * finished, leave *pz pointing to the first character past the end of 51 | * the integer. The *pLen parameter holds the length of the string 52 | * in *pz and is decremented once for each character in the integer. 53 | */ 54 | public uint GetInt () 55 | { 56 | uint v = 0; 57 | int c; 58 | while(this.HaveBytes() && (c = zValue[0x7f & this.GetByte()]) >= 0) { 59 | v = (uint) ((((Int32) v) << 6) + c); 60 | } 61 | this.pos--; 62 | return v; 63 | } 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/JsonStringReader.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization 20 | { 21 | public sealed class JsonStringReader : JsonReader 22 | { 23 | private readonly string jsonString; 24 | private int position; 25 | 26 | public JsonStringReader(string jsonString, SerializationContext context, int bufferSize = DEFAULT_BUFFER_SIZE) 27 | : base(context, bufferSize) 28 | { 29 | if (jsonString == null) 30 | throw new ArgumentNullException("jsonString"); 31 | 32 | 33 | this.jsonString = jsonString; 34 | this.position = 0; 35 | } 36 | 37 | protected override int FillBuffer(char[] buffer, int index) 38 | { 39 | if (buffer == null) 40 | throw new ArgumentNullException("buffer"); 41 | if (index < 0 || index >= buffer.Length) 42 | throw new ArgumentOutOfRangeException("index"); 43 | 44 | 45 | var block = Math.Min(jsonString.Length - position, buffer.Length - index); 46 | if (block <= 0) 47 | return index; 48 | 49 | jsonString.CopyTo(position, buffer, index, block); 50 | 51 | position += block; 52 | 53 | return index + block; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/ColyseusManager.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using UnityEngine; 5 | 6 | namespace Colyseus 7 | { 8 | public class ColyseusManager : MonoBehaviour 9 | { 10 | public Client Client; 11 | public List rooms = new List(); 12 | 13 | private const string SingletonName = "/[Colyseus]"; 14 | private static readonly object Lock = new object(); 15 | private static ColyseusManager _instance; 16 | 17 | /// 18 | /// The singleton instance of the Colyseus Manager. 19 | /// 20 | public static ColyseusManager Instance 21 | { 22 | get 23 | { 24 | lock (Lock) 25 | { 26 | if (_instance != null) return _instance; 27 | var go = GameObject.Find(SingletonName); 28 | if (go == null) 29 | { 30 | go = new GameObject(SingletonName); 31 | } 32 | 33 | if (go.GetComponent() == null) 34 | { 35 | go.AddComponent(); 36 | } 37 | DontDestroyOnLoad(go); 38 | _instance = go.GetComponent(); 39 | return _instance; 40 | } 41 | } 42 | } 43 | 44 | public Client CreateClient(string endpoint) 45 | { 46 | Client = new Client(endpoint); 47 | return Client; 48 | } 49 | 50 | public async Task AddRoom(IRoom room) 51 | { 52 | room.OnLeave += (code) => rooms.Remove(room); 53 | rooms.Add(room); 54 | await room.Connect(); 55 | } 56 | 57 | private void OnApplicationQuit() 58 | { 59 | if (Client != null) 60 | { 61 | foreach (var room in rooms) 62 | { 63 | room.Leave(false); 64 | } 65 | } 66 | } 67 | } 68 | } -------------------------------------------------------------------------------- /Assets/Plugins/FossilDelta/README.md: -------------------------------------------------------------------------------- 1 | Delta compression algorithm for C# 2 | === 3 | 4 | [![Build Status](https://secure.travis-ci.org/endel/FossilDelta.svg?branch=master)](https://travis-ci.org/endel/FossilDelta) 5 | 6 | > This is a port from the original C implementation. See references below. 7 | 8 | Fossil achieves efficient storage and low-bandwidth synchronization through the 9 | use of delta-compression. Instead of storing or transmitting the complete 10 | content of an artifact, fossil stores or transmits only the changes relative to 11 | a related artifact. 12 | 13 | * [Format](http://www.fossil-scm.org/index.html/doc/tip/www/delta_format.wiki) 14 | * [Algorithm](http://www.fossil-scm.org/index.html/doc/tip/www/delta_encoder_algorithm.wiki) 15 | * [Original implementation](http://www.fossil-scm.org/index.html/artifact/f3002e96cc35f37b) 16 | 17 | Other implementations: 18 | 19 | - [JavaScript](https://github.com/dchest/fossil-delta-js) ([Online demo](https://dchest.github.io/fossil-delta-js/)) 20 | 21 | Installation 22 | --- 23 | 24 | ### NuGet Gallery 25 | 26 | FossilDelta is available on the [NuGet Gallery](https://www.nuget.org/packages). 27 | 28 | - [NuGet Gallery: FossilDelta](https://www.nuget.org/packages/FossilDelta) 29 | 30 | You can add FossilDelta to your project with the **NuGet Package Manager**, by using the following command in the **Package Manager Console**. 31 | 32 | PM> Install-Package FossilDelta 33 | 34 | Usage 35 | --- 36 | 37 | ### Fossil.Delta.Create(byte[] origin, byte[] target) 38 | 39 | Returns the difference between `origin` and `target` as a byte array (`byte[]`) 40 | 41 | ### Fossil.Delta.Apply(byte[] origin, byte[] delta) 42 | 43 | Apply the `delta` patch on `origin`, returning the final value as byte array 44 | (`byte[]`). 45 | 46 | Throws an error if it fails to apply the delta 47 | (e.g. if it was corrupted). 48 | 49 | ### Fossil.Delta.OutputSize(byte[] delta) 50 | 51 | Returns a size of target for this delta. 52 | 53 | Throws an error if it can't read the size from delta. 54 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/JsonStringBuilderReader.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Text; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public sealed class JsonStringBuilderReader : JsonReader 23 | { 24 | private readonly StringBuilder jsonString; 25 | private int position; 26 | 27 | public JsonStringBuilderReader(StringBuilder stringBuilder, SerializationContext context, 28 | int bufferSize = DEFAULT_BUFFER_SIZE) 29 | : base(context, bufferSize) 30 | { 31 | if (stringBuilder == null) 32 | throw new ArgumentNullException("str"); 33 | 34 | 35 | this.jsonString = stringBuilder; 36 | this.position = 0; 37 | } 38 | 39 | protected override int FillBuffer(char[] buffer, int index) 40 | { 41 | if (buffer == null) 42 | throw new ArgumentNullException("buffer"); 43 | if (index < 0 || index >= buffer.Length) 44 | throw new ArgumentOutOfRangeException("index"); 45 | 46 | 47 | var block = Math.Min(jsonString.Length - position, buffer.Length - index); 48 | if (block <= 0) 49 | return index; 50 | 51 | jsonString.CopyTo(position, buffer, index, block); 52 | 53 | position += block; 54 | 55 | return index + block; 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/GuidSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using GameDevWare.Serialization.MessagePack; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.Serializers 21 | { 22 | public sealed class GuidSerializer : TypeSerializer 23 | { 24 | public override Type SerializedType { get { return typeof(Guid); } } 25 | 26 | public override object Deserialize(IJsonReader reader) 27 | { 28 | if (reader == null) throw new ArgumentNullException("reader"); 29 | 30 | var guidStr = reader.ReadString(false); 31 | var value = new Guid(guidStr); 32 | return value; 33 | } 34 | 35 | public override void Serialize(IJsonWriter writer, object value) 36 | { 37 | if (writer == null) throw new ArgumentNullException("writer"); 38 | if (value == null) throw new ArgumentNullException("value"); 39 | 40 | var messagePackWriter = writer as MsgPackWriter; 41 | if (messagePackWriter != null) 42 | { 43 | // try to write it as Message Pack extension type 44 | var extensionType = default(sbyte); 45 | var buffer = messagePackWriter.GetWriteBuffer(); 46 | if (messagePackWriter.Context.ExtensionTypeHandler.TryWrite(value, out extensionType, ref buffer)) 47 | { 48 | messagePackWriter.Write(extensionType, buffer); 49 | return; 50 | } 51 | // if not, continue default serialization 52 | } 53 | 54 | var guid = (Guid)value; 55 | var guidStr = guid.ToString(); 56 | writer.Write(guidStr); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/Vector2Serializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class Vector2Serializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Vector2); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Vector2(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | switch (memberName) 40 | { 41 | case "x": value.x = reader.ReadSingle(); break; 42 | case "y": value.y = reader.ReadSingle(); break; 43 | default: reader.ReadValue(typeof(object)); break; 44 | } 45 | } 46 | reader.ReadObjectEnd(nextToken: false); 47 | return value; 48 | } 49 | public override void Serialize(IJsonWriter writer, object value) 50 | { 51 | if (writer == null) throw new ArgumentNullException("writer"); 52 | if (value == null) throw new ArgumentNullException("value"); 53 | 54 | var vector2 = (Vector2)value; 55 | writer.WriteObjectBegin(2); 56 | writer.WriteMember("x"); 57 | writer.Write(vector2.x); 58 | writer.WriteMember("y"); 59 | writer.Write(vector2.y); 60 | writer.WriteObjectEnd(); 61 | } 62 | } 63 | } 64 | #endif 65 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Metadata/FieldDescription.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Reflection; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.Metadata 21 | { 22 | internal sealed class FieldDescription : DataMemberDescription 23 | { 24 | private readonly FieldInfo fieldInfo; 25 | private readonly Func getFn; 26 | private readonly Action setFn; 27 | 28 | public override bool CanGet { get { return true; } } 29 | public override bool CanSet { get { return this.fieldInfo.IsInitOnly == false; } } 30 | public override Type ValueType { get { return this.fieldInfo.FieldType; } } 31 | 32 | public FieldDescription(TypeDescription typeDescription, FieldInfo fieldInfo) 33 | : base(typeDescription, fieldInfo) 34 | { 35 | if (fieldInfo == null) throw new ArgumentNullException("fieldInfo"); 36 | 37 | this.fieldInfo = fieldInfo; 38 | 39 | GettersAndSetters.TryGetAssessors(fieldInfo, out this.getFn, out this.setFn); 40 | 41 | } 42 | 43 | public override object GetValue(object target) 44 | { 45 | if (!this.CanGet) throw new InvalidOperationException("Field is write-only."); 46 | 47 | if (this.getFn != null) 48 | return this.getFn(target); 49 | else 50 | return fieldInfo.GetValue(target); 51 | } 52 | 53 | public override void SetValue(object target, object value) 54 | { 55 | if (!this.CanSet) throw new InvalidOperationException("Field is read-only."); 56 | 57 | if (this.setFn != null) 58 | this.setFn(target, value); 59 | else 60 | this.fieldInfo.SetValue(target, value); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/DateTimeSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Globalization; 18 | using System.Linq; 19 | using System.Runtime.Serialization; 20 | 21 | // ReSharper disable once CheckNamespace 22 | namespace GameDevWare.Serialization.Serializers 23 | { 24 | public sealed class DateTimeSerializer : TypeSerializer 25 | { 26 | public override Type SerializedType { get { return typeof(DateTime); } } 27 | 28 | public override object Deserialize(IJsonReader reader) 29 | { 30 | if (reader == null) throw new ArgumentNullException("reader"); 31 | 32 | if (reader.Token == JsonToken.DateTime || reader.RawValue is DateTime) 33 | return reader.Value.AsDateTime; 34 | 35 | var dateTimeStr = reader.ReadString(false); 36 | try 37 | { 38 | var value = default(DateTime); 39 | if (!DateTime.TryParse(dateTimeStr, reader.Context.Format, DateTimeStyles.RoundtripKind, out value)) 40 | value = DateTime.ParseExact(dateTimeStr, reader.Context.DateTimeFormats, reader.Context.Format, DateTimeStyles.RoundtripKind); 41 | 42 | return value; 43 | } 44 | catch (FormatException fe) 45 | { 46 | throw new SerializationException(string.Format("Failed to parse date '{0}' in with pattern '{1}'.", dateTimeStr, reader.Context.DateTimeFormats[0]), fe); 47 | } 48 | } 49 | 50 | public override void Serialize(IJsonWriter writer, object value) 51 | { 52 | if (writer == null) throw new ArgumentNullException("writer"); 53 | if (value == null) throw new ArgumentNullException("value"); 54 | 55 | var dataTime = (DateTime)value; 56 | writer.Write(dataTime); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/EnumNumberSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class EnumNumberSerializer : TypeSerializer 22 | { 23 | private readonly Type enumType; 24 | private readonly Type enumBaseType; 25 | 26 | public override Type SerializedType { get { return this.enumType; } } 27 | 28 | public EnumNumberSerializer(Type enumType) 29 | { 30 | if (enumType == null) throw new ArgumentNullException("enumType"); 31 | if (!enumType.IsEnum) throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be a Enum"); 32 | 33 | this.enumType = enumType; 34 | this.enumBaseType = Enum.GetUnderlyingType(enumType); 35 | } 36 | 37 | public override object Deserialize(IJsonReader reader) 38 | { 39 | if (reader == null) throw new ArgumentNullException("reader"); 40 | 41 | if (reader.Token == JsonToken.StringLiteral) 42 | return Enum.Parse(this.enumType, reader.ReadString(false), true); 43 | else if (reader.Token == JsonToken.Number) 44 | return Enum.ToObject(this.enumType, reader.ReadValue(this.enumBaseType, false)); 45 | else 46 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.Number, JsonToken.StringLiteral); 47 | } 48 | 49 | public override void Serialize(IJsonWriter writer, object value) 50 | { 51 | if (writer == null) throw new ArgumentNullException("writer"); 52 | if (value == null) throw new ArgumentNullException("value"); 53 | 54 | writer.WriteValue(Convert.ChangeType(value, this.enumBaseType), this.enumBaseType); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/EnumSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class EnumSerializer : TypeSerializer 22 | { 23 | private readonly Type enumType; 24 | private readonly Type enumBaseType; 25 | 26 | public override Type SerializedType { get { return this.enumType; } } 27 | 28 | public EnumSerializer(Type enumType) 29 | { 30 | if (enumType == null) throw new ArgumentNullException("enumType"); 31 | if (!enumType.IsEnum) throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be a Enum"); 32 | 33 | this.enumType = enumType; 34 | this.enumBaseType = Enum.GetUnderlyingType(enumType); 35 | } 36 | 37 | public override object Deserialize(IJsonReader reader) 38 | { 39 | if (reader == null) throw new ArgumentNullException("reader"); 40 | 41 | if (reader.Token == JsonToken.StringLiteral) 42 | return Enum.Parse(this.enumType, reader.ReadString(false), true); 43 | else if (reader.Token == JsonToken.Number) 44 | return Enum.ToObject(this.enumType, reader.ReadValue(this.enumBaseType, false)); 45 | else 46 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.Number, JsonToken.StringLiteral); 47 | } 48 | 49 | public override void Serialize(IJsonWriter writer, object value) 50 | { 51 | if (writer == null) throw new ArgumentNullException("writer"); 52 | if (value == null) throw new ArgumentNullException("value"); 53 | 54 | var valueStr = Convert.ToString(value, writer.Context.Format); 55 | writer.WriteString(valueStr); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/MsgPackTimestampSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using GameDevWare.Serialization.MessagePack; 3 | 4 | // ReSharper disable once CheckNamespace 5 | namespace GameDevWare.Serialization.Serializers 6 | { 7 | public class MsgPackTimestampSerializer : TypeSerializer 8 | { 9 | private const string SECONDS_MEMBER_NAME = "$seconds"; 10 | private const string NANO_SECONDS_MEMBER_NAME = "$nanoSeconds"; 11 | 12 | /// 13 | public override Type SerializedType { get { return typeof(MessagePackTimestamp); } } 14 | 15 | public override object Deserialize(IJsonReader reader) 16 | { 17 | if (reader.RawValue is MessagePackTimestamp) 18 | { 19 | return (MessagePackTimestamp)reader.Value.Raw; 20 | } 21 | else if (reader.Token == JsonToken.Null) 22 | { 23 | return null; 24 | } 25 | 26 | reader.ReadObjectBegin(); 27 | var seconds = default(long); 28 | var nanoSeconds = default(uint); 29 | while (reader.Token != JsonToken.EndOfObject) 30 | { 31 | var member = reader.ReadMember(); 32 | switch (member) 33 | { 34 | case SECONDS_MEMBER_NAME: 35 | seconds = reader.ReadInt64(); 36 | break; 37 | case NANO_SECONDS_MEMBER_NAME: 38 | seconds = reader.ReadUInt32(); 39 | break; 40 | default: 41 | reader.ReadValue(typeof(object)); // skip value 42 | break; 43 | } 44 | } 45 | reader.ReadObjectEnd(false); 46 | 47 | var value = new MessagePackTimestamp(seconds, nanoSeconds); 48 | return value; 49 | } 50 | public override void Serialize(IJsonWriter writer, object value) 51 | { 52 | if (value == null) 53 | { 54 | writer.WriteNull(); 55 | return; 56 | } 57 | 58 | var messagePackWriter = writer as MsgPackWriter; 59 | if (messagePackWriter != null) 60 | { 61 | var extensionType = default(sbyte); 62 | var buffer = messagePackWriter.GetWriteBuffer(); 63 | if (messagePackWriter.Context.ExtensionTypeHandler.TryWrite(value, out extensionType, ref buffer)) 64 | { 65 | messagePackWriter.Write(extensionType, buffer); 66 | return; 67 | } 68 | } 69 | 70 | var timeStamp = (MessagePackTimestamp)value; 71 | writer.WriteObjectBegin(2); 72 | writer.WriteMember(SECONDS_MEMBER_NAME); 73 | writer.Write(timeStamp.Seconds); 74 | writer.WriteMember(NANO_SECONDS_MEMBER_NAME); 75 | writer.Write(timeStamp.NanoSeconds); 76 | writer.WriteObjectEnd(); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/JsonStreamWriter.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.IO; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public sealed class JsonStreamWriter : JsonWriter 23 | { 24 | private readonly StreamWriter writer; 25 | 26 | public Stream Stream { get { return writer.BaseStream; } } 27 | 28 | public JsonStreamWriter(Stream stream, SerializationContext context) : base(context) 29 | { 30 | if (stream == null) throw new ArgumentNullException("stream"); 31 | if (!stream.CanWrite) throw JsonSerializationException.StreamIsNotWriteable(); 32 | 33 | 34 | writer = new StreamWriter(stream, context.Encoding); 35 | } 36 | 37 | public override void Flush() 38 | { 39 | writer.Flush(); 40 | } 41 | 42 | public override void WriteJson(string jsonString) 43 | { 44 | if (jsonString == null) 45 | throw new ArgumentNullException("jsonString"); 46 | 47 | 48 | writer.Write(jsonString); 49 | this.CharactersWritten += jsonString.Length; 50 | } 51 | 52 | public override void WriteJson(char[] jsonString, int index, int charactersToWrite) 53 | { 54 | if (jsonString == null) 55 | throw new ArgumentNullException("jsonString"); 56 | if (index < 0 || index >= jsonString.Length) 57 | throw new ArgumentOutOfRangeException("index"); 58 | if (charactersToWrite < 0 || index + charactersToWrite > jsonString.Length) 59 | throw new ArgumentOutOfRangeException("charactersToWrite"); 60 | 61 | 62 | if (charactersToWrite == 0) 63 | return; 64 | 65 | writer.Write(jsonString, index, charactersToWrite); 66 | this.CharactersWritten += charactersToWrite; 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/JsonTextWriter.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.IO; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public sealed class JsonTextWriter : JsonWriter 23 | { 24 | private readonly TextWriter writer; 25 | 26 | private TextWriter Writer 27 | { 28 | get { return writer; } 29 | } 30 | 31 | public JsonTextWriter(TextWriter writer, SerializationContext context) 32 | : base(context) 33 | { 34 | if (writer == null) 35 | throw new ArgumentNullException("writer"); 36 | 37 | 38 | this.writer = writer; 39 | } 40 | 41 | public override void Flush() 42 | { 43 | writer.Flush(); 44 | } 45 | 46 | public override void WriteJson(string jsonString) 47 | { 48 | if (jsonString == null) 49 | throw new ArgumentNullException("jsonString"); 50 | 51 | 52 | writer.Write(jsonString); 53 | this.CharactersWritten += jsonString.Length; 54 | } 55 | 56 | public override void WriteJson(char[] jsonString, int offset, int charactersToWrite) 57 | { 58 | if (jsonString == null) 59 | throw new ArgumentNullException("jsonString"); 60 | if (offset < 0 || offset >= jsonString.Length) 61 | throw new ArgumentOutOfRangeException("offset"); 62 | if (charactersToWrite < 0 || offset + charactersToWrite > jsonString.Length) 63 | throw new ArgumentOutOfRangeException("charactersToWrite"); 64 | 65 | 66 | if (charactersToWrite == 0) 67 | return; 68 | 69 | writer.Write(jsonString, offset, charactersToWrite); 70 | this.CharactersWritten += charactersToWrite; 71 | } 72 | 73 | public override string ToString() 74 | { 75 | return writer.ToString(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/BoundsSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class BoundsSerializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Bounds); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Bounds(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | if (memberName == "center") 40 | value.center = (Vector3)reader.ReadValue(typeof(Vector3)); 41 | else if (memberName == "extents") 42 | value.extents = (Vector3)reader.ReadValue(typeof(Vector3)); 43 | else 44 | reader.ReadValue(typeof(object)); 45 | } 46 | reader.ReadObjectEnd(nextToken: false); 47 | return value; 48 | } 49 | public override void Serialize(IJsonWriter writer, object value) 50 | { 51 | if (writer == null) throw new ArgumentNullException("writer"); 52 | if (value == null) throw new ArgumentNullException("value"); 53 | 54 | var bounds = (Bounds)value; 55 | writer.WriteObjectBegin(2); 56 | writer.WriteMember("center"); 57 | writer.WriteValue(bounds.center, typeof(Vector3)); 58 | writer.WriteMember("extents"); 59 | writer.WriteValue(bounds.extents, typeof(Vector3)); 60 | writer.WriteObjectEnd(); 61 | } 62 | } 63 | } 64 | #endif 65 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/Vector3Serializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class Vector3Serializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Vector3); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Vector3(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | switch (memberName) 40 | { 41 | case "x": value.x = reader.ReadSingle(); break; 42 | case "y": value.y = reader.ReadSingle(); break; 43 | case "z": value.z = reader.ReadSingle(); break; 44 | default: reader.ReadValue(typeof(object)); break; 45 | } 46 | } 47 | reader.ReadObjectEnd(nextToken: false); 48 | return value; 49 | } 50 | public override void Serialize(IJsonWriter writer, object value) 51 | { 52 | if (writer == null) throw new ArgumentNullException("writer"); 53 | if (value == null) throw new ArgumentNullException("value"); 54 | 55 | var vector3 = (Vector3)value; 56 | writer.WriteObjectBegin(3); 57 | writer.WriteMember("x"); 58 | writer.Write(vector3.x); 59 | writer.WriteMember("y"); 60 | writer.Write(vector3.y); 61 | writer.WriteMember("z"); 62 | writer.Write(vector3.z); 63 | writer.WriteObjectEnd(); 64 | } 65 | } 66 | } 67 | #endif 68 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/BinarySerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using GameDevWare.Serialization.MessagePack; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.Serializers 21 | { 22 | public sealed class BinarySerializer : TypeSerializer 23 | { 24 | public static readonly BinarySerializer Instance = new BinarySerializer(); 25 | 26 | public override Type SerializedType { get { return typeof(byte[]); } } 27 | 28 | public override object Deserialize(IJsonReader reader) 29 | { 30 | if (reader == null) throw new ArgumentNullException("reader"); 31 | 32 | if (reader.Token == JsonToken.Null) 33 | return null; 34 | 35 | if (reader.RawValue is byte[]) 36 | { 37 | return reader.RawValue; 38 | } 39 | else 40 | { 41 | var value = reader.RawValue as string; 42 | if (value == null) 43 | return null; 44 | 45 | var buffer = Convert.FromBase64String(value); 46 | return buffer; 47 | } 48 | } 49 | 50 | public override void Serialize(IJsonWriter writer, object value) 51 | { 52 | if (writer == null) throw new ArgumentNullException("writer"); 53 | 54 | if (value == null) 55 | { 56 | writer.WriteNull(); 57 | return; 58 | } 59 | if (value != null && value is byte[] == false) throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be array of bytes"); 60 | 61 | var bytes = (byte[])value; 62 | if (writer is MsgPackWriter) 63 | { 64 | ((MsgPackWriter)writer).Write(bytes); 65 | } 66 | else 67 | { 68 | var base64String = Convert.ToBase64String(bytes); 69 | writer.WriteString(base64String); 70 | } 71 | } 72 | 73 | public override string ToString() 74 | { 75 | return "byte[] as Base64"; 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/JsonStringBuilderWriter.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Text; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public sealed class JsonStringBuilderWriter : JsonWriter 23 | { 24 | private readonly StringBuilder stringBuilder; 25 | 26 | public StringBuilder Builder 27 | { 28 | get { return stringBuilder; } 29 | } 30 | 31 | public JsonStringBuilderWriter(StringBuilder stringBuilder, SerializationContext context) 32 | : base(context) 33 | { 34 | if (stringBuilder == null) 35 | throw new ArgumentNullException("builder"); 36 | 37 | 38 | this.stringBuilder = stringBuilder; 39 | } 40 | 41 | 42 | public override void Flush() 43 | { 44 | } 45 | 46 | public override void WriteJson(string jsonString) 47 | { 48 | if (jsonString == null) 49 | throw new ArgumentNullException("jsonString"); 50 | 51 | 52 | stringBuilder.Append(jsonString); 53 | this.CharactersWritten += jsonString.Length; 54 | } 55 | 56 | public override void WriteJson(char[] jsonString, int offset, int charactersToWrite) 57 | { 58 | if (jsonString == null) 59 | throw new ArgumentNullException("jsonString"); 60 | if (offset < 0 || offset >= jsonString.Length) 61 | throw new ArgumentOutOfRangeException("offset"); 62 | if (charactersToWrite < 0 || offset + charactersToWrite > jsonString.Length) 63 | throw new ArgumentOutOfRangeException("charactersToWrite"); 64 | 65 | 66 | if (charactersToWrite == 0) 67 | return; 68 | 69 | stringBuilder.Append(jsonString, offset, charactersToWrite); 70 | this.CharactersWritten += charactersToWrite; 71 | } 72 | 73 | public override string ToString() 74 | { 75 | return stringBuilder.ToString(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/DateTimeOffsetSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Globalization; 18 | using System.Linq; 19 | using System.Runtime.Serialization; 20 | 21 | // ReSharper disable once CheckNamespace 22 | namespace GameDevWare.Serialization.Serializers 23 | { 24 | public sealed class DateTimeOffsetSerializer : TypeSerializer 25 | { 26 | public override Type SerializedType { get { return typeof(DateTimeOffset); } } 27 | 28 | public override object Deserialize(IJsonReader reader) 29 | { 30 | if (reader == null) throw new ArgumentNullException("reader"); 31 | 32 | if (reader.Value.Raw is DateTimeOffset) 33 | return reader.Value.Raw; 34 | else if (reader.Token == JsonToken.DateTime || reader.Value.Raw is DateTime) 35 | return new DateTimeOffset(reader.Value.AsDateTime); 36 | 37 | var dateTimeOffsetStr = reader.ReadString(false); 38 | try 39 | { 40 | var value = default(DateTimeOffset); 41 | if (!DateTimeOffset.TryParse(dateTimeOffsetStr, reader.Context.Format, DateTimeStyles.RoundtripKind, out value)) 42 | value = DateTimeOffset.ParseExact(dateTimeOffsetStr, reader.Context.DateTimeFormats, reader.Context.Format, DateTimeStyles.RoundtripKind); 43 | 44 | return value; 45 | } 46 | catch (FormatException fe) 47 | { 48 | throw new SerializationException(string.Format("Failed to parse date '{0}' in with pattern '{1}'.", dateTimeOffsetStr, reader.Context.DateTimeFormats[0]), fe); 49 | } 50 | } 51 | 52 | public override void Serialize(IJsonWriter writer, object value) 53 | { 54 | if (writer == null) throw new ArgumentNullException("writer"); 55 | if (value == null) throw new ArgumentNullException("value"); 56 | 57 | var dateTimeOffset = (DateTimeOffset)value; 58 | writer.Write(dateTimeOffset); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/Vector4Serializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class Vector4Serializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Vector4); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Vector4(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | switch (memberName) 40 | { 41 | case "x": value.x = reader.ReadSingle(); break; 42 | case "y": value.y = reader.ReadSingle(); break; 43 | case "z": value.z = reader.ReadSingle(); break; 44 | case "w": value.w = reader.ReadSingle(); break; 45 | default: reader.ReadValue(typeof(object)); break; 46 | } 47 | } 48 | reader.ReadObjectEnd(nextToken: false); 49 | return value; 50 | } 51 | public override void Serialize(IJsonWriter writer, object value) 52 | { 53 | if (writer == null) throw new ArgumentNullException("writer"); 54 | if (value == null) throw new ArgumentNullException("value"); 55 | 56 | var vector4 = (Vector4)value; 57 | writer.WriteObjectBegin(4); 58 | writer.WriteMember("x"); 59 | writer.Write(vector4.x); 60 | writer.WriteMember("y"); 61 | writer.Write(vector4.y); 62 | writer.WriteMember("z"); 63 | writer.Write(vector4.z); 64 | writer.WriteMember("w"); 65 | writer.Write(vector4.w); 66 | writer.WriteObjectEnd(); 67 | } 68 | } 69 | } 70 | #endif 71 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/RectSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class RectSerializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Rect); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Rect(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | if (memberName == "x") 40 | value.x = reader.ReadSingle(); 41 | else if (memberName == "y") 42 | value.y = reader.ReadSingle(); 43 | else if (memberName == "width") 44 | value.width = reader.ReadSingle(); 45 | else if (memberName == "height") 46 | value.height = reader.ReadSingle(); 47 | else 48 | reader.ReadValue(typeof(object)); 49 | } 50 | reader.ReadObjectEnd(nextToken: false); 51 | return value; 52 | } 53 | public override void Serialize(IJsonWriter writer, object value) 54 | { 55 | if (writer == null) throw new ArgumentNullException("writer"); 56 | if (value == null) throw new ArgumentNullException("value"); 57 | 58 | var vector4 = (Rect)value; 59 | writer.WriteObjectBegin(4); 60 | writer.WriteMember("x"); 61 | writer.Write(vector4.x); 62 | writer.WriteMember("y"); 63 | writer.Write(vector4.y); 64 | writer.WriteMember("width"); 65 | writer.Write(vector4.width); 66 | writer.WriteMember("height"); 67 | writer.Write(vector4.height); 68 | writer.WriteObjectEnd(); 69 | } 70 | } 71 | } 72 | #endif 73 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/QuaternionSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class QuaternionSerializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Quaternion); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Quaternion(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | if (memberName == "x") 40 | value.x = reader.ReadSingle(); 41 | else if (memberName == "y") 42 | value.y = reader.ReadSingle(); 43 | else if (memberName == "z") 44 | value.z = reader.ReadSingle(); 45 | else if (memberName == "w") 46 | value.w = reader.ReadSingle(); 47 | else 48 | reader.ReadValue(typeof(object)); 49 | } 50 | reader.ReadObjectEnd(nextToken: false); 51 | return value; 52 | } 53 | public override void Serialize(IJsonWriter writer, object value) 54 | { 55 | if (writer == null) throw new ArgumentNullException("writer"); 56 | if (value == null) throw new ArgumentNullException("value"); 57 | 58 | var quaternion = (Quaternion)value; 59 | writer.WriteObjectBegin(4); 60 | writer.WriteMember("x"); 61 | writer.Write(quaternion.x); 62 | writer.WriteMember("y"); 63 | writer.Write(quaternion.y); 64 | writer.WriteMember("z"); 65 | writer.Write(quaternion.z); 66 | writer.WriteMember("w"); 67 | writer.Write(quaternion.w); 68 | writer.WriteObjectEnd(); 69 | } 70 | } 71 | } 72 | #endif 73 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Metadata/PropertyDescription.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Reflection; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.Metadata 21 | { 22 | internal sealed class PropertyDescription : DataMemberDescription 23 | { 24 | private readonly PropertyInfo propertyInfo; 25 | private readonly Func getFn; 26 | private readonly Action setFn; 27 | private readonly MethodInfo getMethod; 28 | private readonly MethodInfo setMethod; 29 | 30 | public override bool CanGet { get { return this.getMethod != null; } } 31 | public override bool CanSet { get { return this.setMethod != null; } } 32 | public override Type ValueType { get { return this.propertyInfo.PropertyType; } } 33 | 34 | public PropertyDescription(TypeDescription typeDescription, PropertyInfo propertyInfo) 35 | : base(typeDescription, propertyInfo) 36 | { 37 | if (propertyInfo == null) throw new ArgumentNullException("propertyInfo"); 38 | 39 | this.propertyInfo = propertyInfo; 40 | 41 | this.getMethod = propertyInfo.GetGetMethod(nonPublic: true); 42 | this.setMethod = propertyInfo.GetSetMethod(nonPublic: true); 43 | 44 | GettersAndSetters.TryGetAssessors(this.getMethod, this.setMethod, out this.getFn, out this.setFn); 45 | } 46 | 47 | public override object GetValue(object target) 48 | { 49 | if (!this.CanGet) throw new InvalidOperationException("Property is write-only."); 50 | 51 | if (this.getFn != null) 52 | return this.getFn(target); 53 | else 54 | return this.getMethod.Invoke(target, null); 55 | } 56 | public override void SetValue(object target, object value) 57 | { 58 | if (!this.CanSet) throw new InvalidOperationException("Property is read-only."); 59 | 60 | if (this.setFn != null) 61 | this.setFn(target, value); 62 | else 63 | this.setMethod.Invoke(target, new object[] { value }); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Serializer/Conversion/Endianness.cs: -------------------------------------------------------------------------------- 1 | /* 2 | "Miscellaneous Utility Library" Software Licence 3 | 4 | Version 1.0 5 | 6 | Copyright (c) 2004-2008 Jon Skeet and Marc Gravell. 7 | All rights reserved. 8 | 9 | Redistribution and use in source and binary forms, with or without 10 | modification, are permitted provided that the following conditions 11 | are met: 12 | 13 | 1. Redistributions of source code must retain the above copyright 14 | notice, this list of conditions and the following disclaimer. 15 | 16 | 2. Redistributions in binary form must reproduce the above copyright 17 | notice, this list of conditions and the following disclaimer in the 18 | documentation and/or other materials provided with the distribution. 19 | 20 | 3. The end-user documentation included with the redistribution, if 21 | any, must include the following acknowledgment: 22 | 23 | "This product includes software developed by Jon Skeet 24 | and Marc Gravell. Contact skeet@pobox.com, or see 25 | http://www.pobox.com/~skeet/)." 26 | 27 | Alternately, this acknowledgment may appear in the software itself, 28 | if and wherever such third-party acknowledgments normally appear. 29 | 30 | 4. The name "Miscellaneous Utility Library" must not be used to endorse 31 | or promote products derived from this software without prior written 32 | permission. For written permission, please contact skeet@pobox.com. 33 | 34 | 5. Products derived from this software may not be called 35 | "Miscellaneous Utility Library", nor may "Miscellaneous Utility Library" 36 | appear in their name, without prior written permission of Jon Skeet. 37 | 38 | THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED 39 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 40 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 41 | IN NO EVENT SHALL JON SKEET BE LIABLE FOR ANY DIRECT, INDIRECT, 42 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 43 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 44 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 45 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 46 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 47 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 48 | POSSIBILITY OF SUCH DAMAGE. 49 | */ 50 | 51 | namespace MiscUtil.Conversion 52 | { 53 | /// 54 | /// Endianness of a converter 55 | /// 56 | public enum Endianness 57 | { 58 | /// 59 | /// Little endian - least significant byte first 60 | /// 61 | LittleEndian, 62 | /// 63 | /// Big endian - most significant byte first 64 | /// 65 | BigEndian 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/MessagePack/Endianness.cs: -------------------------------------------------------------------------------- 1 | // 2 | /* 3 | "Miscellaneous Utility Library" Software Licence 4 | 5 | Version 1.0 6 | 7 | Copyright (c) 2004-2008 Jon Skeet and Marc Gravell. 8 | All rights reserved. 9 | 10 | Redistribution and use in source and binary forms, with or without 11 | modification, are permitted provided that the following conditions 12 | are met: 13 | 14 | 1. Redistributions of source code must retain the above copyright 15 | notice, this list of conditions and the following disclaimer. 16 | 17 | 2. Redistributions in binary form must reproduce the above copyright 18 | notice, this list of conditions and the following disclaimer in the 19 | documentation and/or other materials provided with the distribution. 20 | 21 | 3. The end-user documentation included with the redistribution, if 22 | any, must include the following acknowledgment: 23 | 24 | "This product includes software developed by Jon Skeet 25 | and Marc Gravell. Contact skeet@pobox.com, or see 26 | http://www.pobox.com/~skeet/)." 27 | 28 | Alternately, this acknowledgment may appear in the software itself, 29 | if and wherever such third-party acknowledgments normally appear. 30 | 31 | 4. The name "Miscellaneous Utility Library" must not be used to endorse 32 | or promote products derived from this software without prior written 33 | permission. For written permission, please contact skeet@pobox.com. 34 | 35 | 5. Products derived from this software may not be called 36 | "Miscellaneous Utility Library", nor may "Miscellaneous Utility Library" 37 | appear in their name, without prior written permission of Jon Skeet. 38 | 39 | THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED 40 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 41 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 42 | IN NO EVENT SHALL JON SKEET BE LIABLE FOR ANY DIRECT, INDIRECT, 43 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 44 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 45 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 46 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 47 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 48 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 49 | POSSIBILITY OF SUCH DAMAGE. 50 | */ 51 | 52 | // ReSharper disable once CheckNamespace 53 | namespace GameDevWare.Serialization.MessagePack 54 | { 55 | /// 56 | /// Endianness of a converter 57 | /// 58 | public enum Endianness 59 | { 60 | /// 61 | /// Little endian - least significant byte first 62 | /// 63 | LittleEndian, 64 | 65 | /// 66 | /// Big endian - most significant byte first 67 | /// 68 | BigEndian 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Serializer/SchemaSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | 4 | namespace Colyseus 5 | { 6 | public class SchemaSerializer : ISerializer // where T : Colyseus.Schema.Schema 7 | { 8 | protected T state; 9 | 10 | public SchemaSerializer() 11 | { 12 | state = Activator.CreateInstance(); 13 | } 14 | 15 | public void SetState(byte[] data) 16 | { 17 | (state as Schema.Schema).Decode(data); 18 | } 19 | 20 | public T GetState() 21 | { 22 | return state; 23 | } 24 | 25 | public void Patch(byte[] data) 26 | { 27 | (state as Schema.Schema).Decode(data); 28 | } 29 | 30 | public void Teardown () 31 | { 32 | } 33 | 34 | public void Handshake (byte[] bytes, int offset) 35 | { 36 | Type targetType = typeof(T); 37 | 38 | Type[] allTypes = targetType.Assembly.GetTypes(); 39 | Type[] namespaceSchemaTypes = Array.FindAll(allTypes, t => ( 40 | t.Namespace == targetType.Namespace && 41 | typeof(Schema.Schema).IsAssignableFrom(targetType) 42 | )); 43 | 44 | Schema.Reflection reflection = new Schema.Reflection(); 45 | Schema.Iterator it = new Schema.Iterator { Offset = offset }; 46 | 47 | reflection.Decode(bytes, it); 48 | 49 | for (var i=0; i CompareTypes(t, reflection.types[i])); 52 | 53 | if (schemaType == null) 54 | { 55 | throw new Exception("Local schema mismatch from server. Use \"schema-codegen\" to generate up-to-date local definitions."); 56 | } 57 | 58 | Schema.Context.GetInstance().SetTypeId(schemaType, reflection.types[i].id); 59 | } 60 | } 61 | 62 | private bool CompareTypes(System.Type schemaType, Schema.ReflectionType reflectionType) 63 | { 64 | FieldInfo[] fields = schemaType.GetFields(); 65 | int typedFieldCount = 0; 66 | 67 | string fieldNames = ""; 68 | for (var i=0;i< fields.Length;i++) 69 | { 70 | fieldNames += fields[i].Name + ", "; 71 | } 72 | 73 | foreach (FieldInfo field in fields) 74 | { 75 | object[] typeAttributes = field.GetCustomAttributes(typeof(Schema.Type), true); 76 | 77 | if (typeAttributes.Length == 1) 78 | { 79 | Schema.Type typedField = (Schema.Type) typeAttributes[0]; 80 | Schema.ReflectionField reflectionField = reflectionType.fields[typedField.Index]; 81 | 82 | if ( 83 | reflectionField == null || 84 | reflectionField.type.IndexOf(typedField.FieldType) != 0 || 85 | reflectionField.name != field.Name 86 | ) { 87 | return false; 88 | } 89 | 90 | typedFieldCount++; 91 | } 92 | } 93 | 94 | // skip if number of Type'd fields doesn't match 95 | if (typedFieldCount != reflectionType.fields.Count) 96 | { 97 | return false; 98 | } 99 | 100 | return true; 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/StreamSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.IO; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.Serializers 21 | { 22 | public sealed class StreamSerializer : TypeSerializer 23 | { 24 | public static readonly StreamSerializer Instance = new StreamSerializer(); 25 | 26 | public override Type SerializedType { get { return typeof(Stream); } } 27 | 28 | public override object Deserialize(IJsonReader reader) 29 | { 30 | if (reader == null) throw new ArgumentNullException("reader"); 31 | 32 | if (reader.Token == JsonToken.Null) 33 | return null; 34 | 35 | if (reader.RawValue is Stream) 36 | return reader.RawValue; 37 | else if(reader.RawValue is byte[]) 38 | return new MemoryStream((byte[])reader.RawValue); 39 | else 40 | { 41 | var base64Str = Convert.ToString(reader.RawValue, reader.Context.Format); 42 | var bytes = Convert.FromBase64String(base64Str); 43 | return new MemoryStream(bytes); 44 | } 45 | } 46 | 47 | public override void Serialize(IJsonWriter writer, object value) 48 | { 49 | if (writer == null) throw new ArgumentNullException("writer"); 50 | if (value == null) throw new ArgumentNullException("value"); 51 | 52 | var stream = value as Stream; 53 | if (value != null && stream == null) throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be a Stream"); 54 | if (!stream.CanRead) throw new JsonSerializationException("Stream couldn't be readed.", JsonSerializationException.ErrorCode.StreamIsNotReadable); 55 | 56 | if (stream.CanSeek) 57 | { 58 | var position = stream.Position; 59 | var buffer = new byte[stream.Length - stream.Position]; 60 | stream.Read(buffer, 0, buffer.Length); 61 | BinarySerializer.Instance.Serialize(writer, buffer); 62 | stream.Position = position; 63 | } 64 | else 65 | { 66 | var tmpStream = new MemoryStream(); 67 | var buffer = new byte[ushort.MaxValue]; 68 | var readed = 0; 69 | 70 | while ((readed = stream.Read(buffer, 0, buffer.Length)) > 0) 71 | tmpStream.Write(buffer, 0, readed); 72 | 73 | BinarySerializer.Instance.Serialize(writer, tmpStream.ToArray()); 74 | } 75 | } 76 | 77 | public override string ToString() 78 | { 79 | return "stream"; 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Metadata/MemberDescription.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections.Generic; 18 | using System.Collections.ObjectModel; 19 | using System.Linq; 20 | using System.Reflection; 21 | 22 | // ReSharper disable once CheckNamespace 23 | namespace GameDevWare.Serialization.Metadata 24 | { 25 | internal abstract class MemberDescription 26 | { 27 | protected const string DATA_CONTRACT_ATTRIBUTE_NAME = "DataContractAttribute"; 28 | protected const string DATA_MEMBER_ATTRIBUTE_NAME = "DataMemberAttribute"; 29 | protected const string IGNORE_DATA_MEMBER_ATTRIBUTE_NAME = "IgnoreDataMemberAttribute"; 30 | 31 | private readonly string name; 32 | private readonly MemberInfo member; 33 | private readonly ReadOnlyCollection attributes; 34 | private readonly ILookup attributesByType; 35 | 36 | public MemberInfo Member { get { return this.member; } } 37 | public ReadOnlyCollection Attributes { get { return this.attributes; } } 38 | public string Name { get { return this.name; } } 39 | 40 | protected MemberDescription(TypeDescription typeDescription, MemberInfo member) 41 | { 42 | if (member == null) throw new ArgumentNullException("member"); 43 | 44 | this.member = member; 45 | this.name = member.Name; 46 | 47 | var attributesList = new List(); 48 | foreach (Attribute attr in member.GetCustomAttributes(true)) 49 | attributesList.Add(attr); 50 | 51 | if (typeDescription != null && typeDescription.IsDataContract) 52 | { 53 | var dataMemberAttribute = attributesList.FirstOrDefault(a => a.GetType().Name == DATA_MEMBER_ATTRIBUTE_NAME); 54 | if (dataMemberAttribute != null) 55 | this.name = ReflectionExtentions.GetDataMemberName(dataMemberAttribute) ?? this.name; 56 | } 57 | 58 | this.attributes = new ReadOnlyCollection(attributesList); 59 | this.attributesByType = attributesList.ToLookup(a => a.GetType()); 60 | } 61 | 62 | public bool HasAttributes(Type type) 63 | { 64 | if (type == null) throw new ArgumentNullException("type"); 65 | 66 | return this.attributesByType.Contains(type); 67 | } 68 | 69 | public IEnumerable GetAttributesOrEmptyList(Type type) 70 | { 71 | if (type == null) throw new ArgumentNullException("type"); 72 | 73 | return this.attributesByType[type]; 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /Server/DemoRoom.ts: -------------------------------------------------------------------------------- 1 | import { Room, Client, generateId } from "colyseus"; 2 | import { Schema, type, MapSchema, ArraySchema } from "@colyseus/schema"; 3 | import { verifyToken, User, IUser } from "@colyseus/social"; 4 | 5 | class Entity extends Schema { 6 | @type("number") 7 | x: number = 0; 8 | 9 | @type("number") 10 | y: number = 0; 11 | } 12 | 13 | class Player extends Entity { 14 | @type("boolean") 15 | connected: boolean = true; 16 | } 17 | 18 | class Enemy extends Entity { 19 | @type("number") 20 | power: number = Math.random() * 10; 21 | } 22 | 23 | class State extends Schema { 24 | @type({ map: Entity }) 25 | entities = new MapSchema(); 26 | } 27 | 28 | /** 29 | * Demonstrate sending schema data types as messages 30 | */ 31 | class Message extends Schema { 32 | @type("number") num; 33 | @type("string") str; 34 | } 35 | 36 | export class DemoRoom extends Room { 37 | 38 | onCreate (options: any) { 39 | console.log("DemoRoom created!", options); 40 | 41 | this.setState(new State()); 42 | this.populateEnemies(); 43 | 44 | this.setMetadata({ 45 | str: "hello", 46 | number: 10 47 | }); 48 | 49 | this.setPatchRate(1000 / 20); 50 | this.setSimulationInterval((dt) => this.update(dt)); 51 | } 52 | 53 | async onAuth (client, options) { 54 | console.log("onAuth(), options!", options); 55 | return await User.findById(verifyToken(options.token)._id); 56 | } 57 | 58 | populateEnemies () { 59 | for (let i=0; i<=3; i++) { 60 | const enemy = new Enemy(); 61 | enemy.x = Math.random() * 2; 62 | enemy.y = Math.random() * 2; 63 | this.state.entities[generateId()] = enemy; 64 | } 65 | } 66 | 67 | onJoin (client: Client, options: any, user: IUser) { 68 | console.log("client joined!", client.sessionId); 69 | this.state.entities[client.sessionId] = new Player(); 70 | } 71 | 72 | async onLeave (client: Client, consented: boolean) { 73 | this.state.entities[client.sessionId].connected = false; 74 | 75 | try { 76 | if (consented) { 77 | throw new Error("consented leave!"); 78 | } 79 | 80 | console.log("let's wait for reconnection!") 81 | const newClient = await this.allowReconnection(client, 10); 82 | console.log("reconnected!", newClient.sessionId); 83 | 84 | } catch (e) { 85 | console.log("disconnected!", client.sessionId); 86 | delete this.state.entities[client.sessionId]; 87 | } 88 | } 89 | 90 | onMessage (client: Client, data: any) { 91 | console.log(data, "received from", client.sessionId); 92 | 93 | if (data === "move_right") { 94 | this.state.entities[client.sessionId].x += 0.01; 95 | 96 | const message = new Message(); 97 | message.num = Math.floor(Math.random() * 100); 98 | message.str = "sending to a single client"; 99 | this.send(client, message); 100 | } 101 | console.log(this.state.entities[client.sessionId].x); 102 | 103 | this.broadcast({ hello: "hello world" }); 104 | } 105 | 106 | update (dt?: number) { 107 | // console.log("num clients:", Object.keys(this.clients).length); 108 | } 109 | 110 | onDispose () { 111 | console.log("disposing DemoRoom..."); 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/DictionaryEntrySerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections; 18 | using System.Runtime.Serialization; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class DictionaryEntrySerializer : TypeSerializer 24 | { 25 | public const string KEY_MEMBER_NAME = "Key"; 26 | public const string VALUE_MEMBER_NAME = "Value"; 27 | 28 | public override Type SerializedType { get { return typeof(DictionaryEntry); } } 29 | 30 | public override object Deserialize(IJsonReader reader) 31 | { 32 | if (reader == null) throw new ArgumentNullException("reader"); 33 | 34 | if (reader.Token == JsonToken.BeginArray) 35 | { 36 | var entry = new DictionaryEntry(); 37 | reader.ReadArrayBegin(); 38 | entry.Key = reader.ReadValue(typeof(object)); 39 | entry.Value = reader.ReadValue(typeof(object)); 40 | reader.ReadArrayEnd(nextToken: false); 41 | return entry; 42 | } 43 | else if (reader.Token == JsonToken.BeginObject) 44 | { 45 | var entry = new DictionaryEntry(); 46 | reader.ReadObjectBegin(); 47 | while (reader.Token != JsonToken.EndOfObject) 48 | { 49 | var memberName = reader.ReadMember(); 50 | switch (memberName) 51 | { 52 | case KEY_MEMBER_NAME: 53 | entry.Key = reader.ReadValue(typeof(object)); 54 | break; 55 | case VALUE_MEMBER_NAME: 56 | entry.Value = reader.ReadValue(typeof(object)); 57 | break; 58 | case ObjectSerializer.TYPE_MEMBER_NAME: 59 | reader.ReadValue(typeof(object)); 60 | break; 61 | default: 62 | throw new SerializationException(string.Format("Unknown member found '{0}' while '{1}' or '{2}' are expected.", memberName, KEY_MEMBER_NAME, VALUE_MEMBER_NAME)); 63 | } 64 | } 65 | reader.ReadObjectEnd(nextToken: false); 66 | return entry; 67 | } 68 | else 69 | { 70 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.BeginObject, JsonToken.BeginArray); 71 | } 72 | } 73 | public override void Serialize(IJsonWriter writer, object value) 74 | { 75 | if (writer == null) throw new ArgumentNullException("writer"); 76 | if (value == null) throw new ArgumentNullException("value"); 77 | 78 | var entry = (DictionaryEntry)value; 79 | writer.WriteObjectBegin(2); 80 | writer.WriteMember(KEY_MEMBER_NAME); 81 | writer.WriteValue(entry.Key, typeof(object)); 82 | writer.WriteMember(VALUE_MEMBER_NAME); 83 | writer.WriteValue(entry.Value, typeof(object)); 84 | writer.WriteObjectEnd(); 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/JsonMember.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Linq; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization 21 | { 22 | public struct JsonMember : IEquatable, IEquatable 23 | { 24 | internal string NameString; 25 | internal char[] NameChars; 26 | internal bool IsEscapedAndQuoted; 27 | 28 | public int Length 29 | { 30 | get { return this.NameString != null ? this.NameString.Length : this.NameChars.Length; } 31 | } 32 | 33 | public JsonMember(string name) 34 | : this(name, false) 35 | { 36 | } 37 | 38 | public JsonMember(string name, bool escapedAndQuoted) 39 | { 40 | if (name == null) 41 | throw new ArgumentNullException("name"); 42 | 43 | this.NameString = name; 44 | this.IsEscapedAndQuoted = escapedAndQuoted; 45 | this.NameChars = null; 46 | } 47 | 48 | public JsonMember(char[] name) 49 | : this(name, false) 50 | { 51 | } 52 | 53 | public JsonMember(char[] name, bool escapedAndQuoted) 54 | { 55 | if (name == null) 56 | throw new ArgumentNullException("name"); 57 | 58 | this.NameChars = name; 59 | this.IsEscapedAndQuoted = escapedAndQuoted; 60 | this.NameString = null; 61 | } 62 | 63 | public override int GetHashCode() 64 | { 65 | return this.NameString != null ? this.NameString.GetHashCode() : this.NameChars.Aggregate(0, (a, c) => a ^ (int) c); 66 | } 67 | 68 | public override bool Equals(object obj) 69 | { 70 | if (obj is JsonMember) 71 | return this.Equals((JsonMember) obj); 72 | else if (obj is string) 73 | return this.Equals((string) obj); 74 | else 75 | return false; 76 | } 77 | 78 | public bool Equals(JsonMember other) 79 | { 80 | return this.ToString().Equals(other.ToString(), StringComparison.Ordinal); 81 | } 82 | 83 | public bool Equals(string other) 84 | { 85 | return this.ToString().Equals(other, StringComparison.Ordinal); 86 | } 87 | 88 | public static explicit operator string(JsonMember member) 89 | { 90 | return member.ToString(); 91 | } 92 | 93 | public static explicit operator JsonMember(string memberName) 94 | { 95 | return new JsonMember(memberName); 96 | } 97 | 98 | public override string ToString() 99 | { 100 | var name = NameString; 101 | if (this.NameChars != null) 102 | name = new string(NameChars, 0, NameChars.Length); 103 | 104 | // this is used in tests, so perf is not primary 105 | if (this.IsEscapedAndQuoted) 106 | { 107 | if (name.EndsWith(":")) 108 | name = name.Substring(0, name.Length - 1); 109 | 110 | name = JsonUtils.UnescapeAndUnquote(name); 111 | } 112 | 113 | return name; 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 |
6 |
7 | 8 | 9 | 10 | 11 | Patreon donate button 12 | 13 | 14 | Discussion forum 15 | 16 | 17 | 18 | 19 |

20 | Multiplayer Game Client for Unity.
View documentation 21 |

22 |
23 | 24 | 25 | | Description | Status | 26 | | ------| -------| 27 | | Master Branch Build Status | [![Build Status](https://dev.azure.com/colyseus/colyseus-unity3d/_apis/build/status/colyseus.colyseus-unity3d?branchName=master)](https://dev.azure.com/colyseus/colyseus-unity3d/_build/latest?definitionId=2&branchName=master) | 28 | 29 | 30 | ## Releasing a new version 31 | 32 | How to create a release: 33 | 34 | ### 1. Create release branch (release/RELEASE_VERSION) 35 | 36 | Example branch name: `release/0.11.0` 37 | 38 | RELEASE_VERSION will be used for multiple things: 39 | - It will tag the commit with this string 40 | - It will name the release with this string 41 | - It will add this string as a suffix to attachments of the release (example: plugins-0.11.0.zip 42 | 43 | ### 2. Check Github releases for new draft (can take a while) 44 | 45 | - Check the build status here: https://dev.azure.com/colyseus/colyseus-unity3d/_build 46 | - Check the deploy status here: https://dev.azure.com/colyseus/colyseus-unity3d/_release 47 | - Change the release notes if necessary 48 | 49 | ### 3. Publish Release 50 | 51 | ## License 52 | 53 | MIT 54 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/MsgPackExtensionTypeSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Globalization; 18 | using GameDevWare.Serialization.MessagePack; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class MsgPackExtensionTypeSerializer : TypeSerializer 24 | { 25 | private const string DATA_MEMBER_NAME = "$data"; 26 | private const string TYPE_MEMBER_NAME = "$type"; 27 | 28 | /// 29 | public override Type SerializedType { get { return typeof(MessagePackExtensionType); } } 30 | 31 | public override object Deserialize(IJsonReader reader) 32 | { 33 | if (reader.Token == JsonToken.Null) 34 | { 35 | return null; 36 | } 37 | else if (reader.RawValue is MessagePackExtensionType) 38 | { 39 | return (MessagePackExtensionType)reader.RawValue; 40 | } 41 | else if (reader.RawValue is byte[]) 42 | { 43 | return new MessagePackExtensionType((byte[])reader.RawValue); 44 | } 45 | else if (reader.RawValue is string) 46 | { 47 | return new MessagePackExtensionType(Convert.FromBase64String(reader.Value.AsString)); 48 | } 49 | 50 | // { "$binary" : "", "$type" : "" } 51 | // http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON 52 | 53 | reader.ReadObjectBegin(); 54 | var base64Binary = default(string); 55 | var subtypeHex = default(string); 56 | while (reader.Token != JsonToken.EndOfObject) 57 | { 58 | var member = reader.ReadMember(); 59 | switch (member) 60 | { 61 | case DATA_MEMBER_NAME: 62 | base64Binary = reader.ReadString(); 63 | break; 64 | case TYPE_MEMBER_NAME: 65 | subtypeHex = reader.ReadString(); 66 | break; 67 | default: 68 | reader.ReadValue(typeof(object)); // skip value 69 | break; 70 | } 71 | } 72 | reader.ReadObjectEnd(nextToken: false); 73 | 74 | if (subtypeHex == null) subtypeHex = "0"; 75 | if (base64Binary == null) base64Binary = ""; 76 | 77 | var binaryType = unchecked((sbyte)byte.Parse(subtypeHex, NumberStyles.HexNumber)); 78 | var binary = Convert.FromBase64String(base64Binary); 79 | 80 | var value = new MessagePackExtensionType(binaryType, binary); 81 | return value; 82 | } 83 | public override void Serialize(IJsonWriter writer, object value) 84 | { 85 | if (value == null) 86 | { 87 | writer.WriteNull(); 88 | return; 89 | } 90 | 91 | var extensionType = (MessagePackExtensionType)value; 92 | 93 | var msgPackWriter = writer as MsgPackWriter; 94 | if (msgPackWriter != null) 95 | { 96 | msgPackWriter.Write(extensionType.Type, extensionType.ToArraySegment()); 97 | return; 98 | } 99 | 100 | writer.WriteObjectBegin(2); 101 | writer.WriteMember(DATA_MEMBER_NAME); 102 | writer.WriteString(extensionType.ToBase64()); 103 | writer.WriteMember(TYPE_MEMBER_NAME); 104 | writer.Write(unchecked((byte)extensionType.Type).ToString("X2")); 105 | writer.WriteObjectEnd(); 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/MessagePack/MsgPackTimestamp.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using GameDevWare.Serialization.Serializers; 18 | 19 | // ReSharper disable once CheckNamespace 20 | namespace GameDevWare.Serialization.MessagePack 21 | { 22 | [TypeSerializer(typeof(MsgPackTimestampSerializer))] 23 | public struct MessagePackTimestamp : IEquatable, IComparable 24 | { 25 | public const int MAX_NANO_SECONDS = 999999999; 26 | 27 | public readonly long Seconds; 28 | public readonly uint NanoSeconds; 29 | 30 | public MessagePackTimestamp(long seconds, uint nanoSeconds) 31 | { 32 | if (nanoSeconds > MAX_NANO_SECONDS) 33 | nanoSeconds = MAX_NANO_SECONDS; 34 | 35 | this.Seconds = seconds; 36 | this.NanoSeconds = nanoSeconds; 37 | } 38 | 39 | public static explicit operator DateTime(MessagePackTimestamp timestamp) 40 | { 41 | return new DateTime(JsonUtils.UnixEpochTicks + ((TimeSpan)timestamp).Ticks, DateTimeKind.Unspecified); 42 | } 43 | public static explicit operator TimeSpan(MessagePackTimestamp timestamp) 44 | { 45 | return TimeSpan.FromSeconds(timestamp.Seconds) + TimeSpan.FromTicks(timestamp.NanoSeconds / 100); 46 | } 47 | 48 | /// 49 | public override int GetHashCode() 50 | { 51 | return unchecked(this.Seconds.GetHashCode() * 17 + this.NanoSeconds.GetHashCode()); 52 | } 53 | /// 54 | public override bool Equals(object obj) 55 | { 56 | if (obj is MessagePackTimestamp) 57 | return this.Equals((MessagePackTimestamp)obj); 58 | else 59 | return false; 60 | } 61 | /// 62 | public bool Equals(MessagePackTimestamp other) 63 | { 64 | return this.Seconds.Equals(other.Seconds) && this.NanoSeconds.Equals(other.NanoSeconds); 65 | } 66 | /// 67 | public int CompareTo(MessagePackTimestamp other) 68 | { 69 | var cmp = this.Seconds.CompareTo(other.Seconds); 70 | if (cmp != 0) 71 | return cmp; 72 | return this.NanoSeconds.CompareTo(other.NanoSeconds); 73 | } 74 | 75 | public static bool operator >(MessagePackTimestamp a, MessagePackTimestamp b) 76 | { 77 | return a.CompareTo(b) == 1; 78 | } 79 | public static bool operator <(MessagePackTimestamp a, MessagePackTimestamp b) 80 | { 81 | return a.CompareTo(b) == -1; 82 | } 83 | public static bool operator >=(MessagePackTimestamp a, MessagePackTimestamp b) 84 | { 85 | return a.CompareTo(b) != -1; 86 | } 87 | public static bool operator <=(MessagePackTimestamp a, MessagePackTimestamp b) 88 | { 89 | return a.CompareTo(b) != 1; 90 | } 91 | public static bool operator ==(MessagePackTimestamp a, MessagePackTimestamp b) 92 | { 93 | return a.Equals(b); 94 | } 95 | public static bool operator !=(MessagePackTimestamp a, MessagePackTimestamp b) 96 | { 97 | return !a.Equals(b); 98 | } 99 | 100 | /// 101 | public override string ToString() 102 | { 103 | return string.Format("seconds: {0}, nanoseconds: {1}", this.Seconds, this.NanoSeconds); 104 | } 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/Matrix4x4Serializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | #if UNITY_5 || UNITY_4 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 17 | using System; 18 | using UnityEngine; 19 | 20 | // ReSharper disable once CheckNamespace 21 | namespace GameDevWare.Serialization.Serializers 22 | { 23 | public sealed class Matrix4x4Serializer : TypeSerializer 24 | { 25 | public override Type SerializedType { get { return typeof(Matrix4x4); } } 26 | 27 | public override object Deserialize(IJsonReader reader) 28 | { 29 | if (reader == null) throw new ArgumentNullException("reader"); 30 | 31 | if (reader.Token == JsonToken.Null) 32 | return null; 33 | 34 | var value = new Matrix4x4(); 35 | reader.ReadObjectBegin(); 36 | while (reader.Token != JsonToken.EndOfObject) 37 | { 38 | var memberName = reader.ReadMember(); 39 | switch (memberName) 40 | { 41 | case "m00": value.m00 = reader.ReadSingle(); break; 42 | case "m10": value.m10 = reader.ReadSingle(); break; 43 | case "m20": value.m20 = reader.ReadSingle(); break; 44 | case "m30": value.m30 = reader.ReadSingle(); break; 45 | case "m01": value.m01 = reader.ReadSingle(); break; 46 | case "m11": value.m11 = reader.ReadSingle(); break; 47 | case "m21": value.m21 = reader.ReadSingle(); break; 48 | case "m31": value.m31 = reader.ReadSingle(); break; 49 | case "m02": value.m02 = reader.ReadSingle(); break; 50 | case "m12": value.m12 = reader.ReadSingle(); break; 51 | case "m22": value.m22 = reader.ReadSingle(); break; 52 | case "m32": value.m32 = reader.ReadSingle(); break; 53 | case "m03": value.m03 = reader.ReadSingle(); break; 54 | case "m13": value.m13 = reader.ReadSingle(); break; 55 | case "m23": value.m23 = reader.ReadSingle(); break; 56 | case "m33": value.m33 = reader.ReadSingle(); break; 57 | default: 58 | reader.ReadValue(typeof(object)); 59 | break; 60 | } 61 | } 62 | reader.ReadObjectEnd(nextToken: false); 63 | return value; 64 | } 65 | public override void Serialize(IJsonWriter writer, object value) 66 | { 67 | if (writer == null) throw new ArgumentNullException("writer"); 68 | if (value == null) throw new ArgumentNullException("value"); 69 | 70 | var matrix = (Matrix4x4)value; 71 | writer.WriteObjectBegin(16); 72 | writer.WriteMember("m00"); 73 | writer.Write(matrix.m00); 74 | writer.WriteMember("m10"); 75 | writer.Write(matrix.m10); 76 | writer.WriteMember("m20"); 77 | writer.Write(matrix.m20); 78 | writer.WriteMember("m30"); 79 | writer.Write(matrix.m30); 80 | writer.WriteMember("m01"); 81 | writer.Write(matrix.m01); 82 | writer.WriteMember("m11"); 83 | writer.Write(matrix.m11); 84 | writer.WriteMember("m21"); 85 | writer.Write(matrix.m21); 86 | writer.WriteMember("m31"); 87 | writer.Write(matrix.m31); 88 | writer.WriteMember("m02"); 89 | writer.Write(matrix.m02); 90 | writer.WriteMember("m12"); 91 | writer.Write(matrix.m12); 92 | writer.WriteMember("m22"); 93 | writer.Write(matrix.m22); 94 | writer.WriteMember("m32"); 95 | writer.Write(matrix.m32); 96 | writer.WriteMember("m03"); 97 | writer.Write(matrix.m03); 98 | writer.WriteMember("m13"); 99 | writer.Write(matrix.m13); 100 | writer.WriteMember("m23"); 101 | writer.Write(matrix.m23); 102 | writer.WriteMember("m33"); 103 | writer.Write(matrix.m33); 104 | writer.WriteObjectEnd(); 105 | } 106 | } 107 | } 108 | #endif 109 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/MsgPack.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections.Generic; 18 | using System.IO; 19 | using System.Text; 20 | using GameDevWare.Serialization.MessagePack; 21 | using GameDevWare.Serialization.Serializers; 22 | 23 | // ReSharper disable once CheckNamespace 24 | namespace GameDevWare.Serialization 25 | { 26 | public static class MsgPack 27 | { 28 | public static string[] DefaultDateTimeFormats { get { return Json.DefaultDateTimeFormats; } set { Json.DefaultDateTimeFormats = value; } } 29 | public static IFormatProvider DefaultFormat { get { return Json.DefaultFormat; } set { Json.DefaultFormat = value; } } 30 | public static Encoding DefaultEncoding { get { return Json.DefaultEncoding; } set { Json.DefaultEncoding = value; } } 31 | public static List DefaultSerializers { get { return Json.DefaultSerializers; } } 32 | public static MessagePackExtensionTypeHandler ExtensionTypeHandler { get; private set; } 33 | 34 | static MsgPack() 35 | { 36 | ExtensionTypeHandler = new DefaultMessagePackExtensionTypeHandler(EndianBitConverter.Big); 37 | } 38 | 39 | public static void Serialize(T objectToSerialize, Stream msgPackOutput) 40 | { 41 | Serialize(objectToSerialize, msgPackOutput, CreateDefaultContext(SerializationOptions.None)); 42 | } 43 | public static void Serialize(T objectToSerialize, Stream msgPackOutput, SerializationOptions options) 44 | { 45 | Serialize(objectToSerialize, msgPackOutput, CreateDefaultContext(options)); 46 | } 47 | public static void Serialize(T objectToSerialize, Stream msgPackOutput, SerializationContext context) 48 | { 49 | if (msgPackOutput == null) throw new ArgumentNullException("msgPackOutput"); 50 | if (context == null) throw new ArgumentNullException("context"); 51 | 52 | var writer = new MsgPackWriter(msgPackOutput, context); 53 | if (objectToSerialize == null) 54 | { 55 | writer.WriteNull(); 56 | writer.Flush(); 57 | return; 58 | } 59 | writer.WriteValue(objectToSerialize, typeof(T)); 60 | writer.Flush(); 61 | } 62 | 63 | public static object Deserialize(Type objectType, Stream msgPackInput) 64 | { 65 | return Deserialize(objectType, msgPackInput, CreateDefaultContext(SerializationOptions.None)); 66 | } 67 | public static object Deserialize(Type objectType, Stream msgPackInput, SerializationOptions options) 68 | { 69 | return Deserialize(objectType, msgPackInput, CreateDefaultContext(options)); 70 | } 71 | public static object Deserialize(Type objectType, Stream msgPackInput, SerializationContext context) 72 | { 73 | if (objectType == null) throw new ArgumentNullException("objectType"); 74 | if (context == null) throw new ArgumentNullException("context"); 75 | if (msgPackInput == null) throw new ArgumentNullException("msgPackInput"); 76 | if (!msgPackInput.CanRead) throw JsonSerializationException.StreamIsNotReadable(); 77 | 78 | var reader = new MsgPackReader(msgPackInput, context); 79 | return reader.ReadValue(objectType, false); 80 | } 81 | 82 | public static T Deserialize(Stream msgPackInput) 83 | { 84 | return Deserialize(msgPackInput, CreateDefaultContext(SerializationOptions.None)); 85 | } 86 | public static T Deserialize(Stream msgPackInput, SerializationOptions options) 87 | { 88 | return Deserialize(msgPackInput, CreateDefaultContext(options)); 89 | } 90 | public static T Deserialize(Stream msgPackInput, SerializationContext context) 91 | { 92 | if (context == null) throw new ArgumentNullException("context"); 93 | if (msgPackInput == null) throw new ArgumentNullException("msgPackInput"); 94 | if (!msgPackInput.CanRead) throw JsonSerializationException.StreamIsNotReadable(); 95 | 96 | return (T)Deserialize(typeof(T), msgPackInput, context); 97 | } 98 | 99 | private static SerializationContext CreateDefaultContext(SerializationOptions options) 100 | { 101 | return new SerializationContext 102 | { 103 | Options = options, 104 | EnumSerializerFactory = (enumType) => new EnumNumberSerializer(enumType) 105 | }; 106 | } 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Serializer/Conversion/LittleEndianBitConverter.cs: -------------------------------------------------------------------------------- 1 | /* 2 | "Miscellaneous Utility Library" Software Licence 3 | 4 | Version 1.0 5 | 6 | Copyright (c) 2004-2008 Jon Skeet and Marc Gravell. 7 | All rights reserved. 8 | 9 | Redistribution and use in source and binary forms, with or without 10 | modification, are permitted provided that the following conditions 11 | are met: 12 | 13 | 1. Redistributions of source code must retain the above copyright 14 | notice, this list of conditions and the following disclaimer. 15 | 16 | 2. Redistributions in binary form must reproduce the above copyright 17 | notice, this list of conditions and the following disclaimer in the 18 | documentation and/or other materials provided with the distribution. 19 | 20 | 3. The end-user documentation included with the redistribution, if 21 | any, must include the following acknowledgment: 22 | 23 | "This product includes software developed by Jon Skeet 24 | and Marc Gravell. Contact skeet@pobox.com, or see 25 | http://www.pobox.com/~skeet/)." 26 | 27 | Alternately, this acknowledgment may appear in the software itself, 28 | if and wherever such third-party acknowledgments normally appear. 29 | 30 | 4. The name "Miscellaneous Utility Library" must not be used to endorse 31 | or promote products derived from this software without prior written 32 | permission. For written permission, please contact skeet@pobox.com. 33 | 34 | 5. Products derived from this software may not be called 35 | "Miscellaneous Utility Library", nor may "Miscellaneous Utility Library" 36 | appear in their name, without prior written permission of Jon Skeet. 37 | 38 | THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED 39 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 40 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 41 | IN NO EVENT SHALL JON SKEET BE LIABLE FOR ANY DIRECT, INDIRECT, 42 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 43 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 44 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 45 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 46 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 47 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 48 | POSSIBILITY OF SUCH DAMAGE. 49 | */ 50 | 51 | namespace MiscUtil.Conversion 52 | { 53 | /// 54 | /// Implementation of EndianBitConverter which converts to/from little-endian 55 | /// byte arrays. 56 | /// 57 | public sealed class LittleEndianBitConverter : EndianBitConverter 58 | { 59 | /// 60 | /// Indicates the byte order ("endianess") in which data is converted using this class. 61 | /// 62 | /// 63 | /// Different computer architectures store data using different byte orders. "Big-endian" 64 | /// means the most significant byte is on the left end of a word. "Little-endian" means the 65 | /// most significant byte is on the right end of a word. 66 | /// 67 | /// true if this converter is little-endian, false otherwise. 68 | public sealed override bool IsLittleEndian() 69 | { 70 | return true; 71 | } 72 | 73 | /// 74 | /// Indicates the byte order ("endianess") in which data is converted using this class. 75 | /// 76 | public sealed override Endianness Endianness 77 | { 78 | get { return Endianness.LittleEndian; } 79 | } 80 | 81 | /// 82 | /// Copies the specified number of bytes from value to buffer, starting at index. 83 | /// 84 | /// The value to copy 85 | /// The number of bytes to copy 86 | /// The buffer to copy the bytes into 87 | /// The index to start at 88 | protected override void CopyBytesImpl(long value, int bytes, byte[] buffer, int index) 89 | { 90 | for (int i=0; i < bytes; i++) 91 | { 92 | buffer[i+index] = unchecked((byte)(value&0xff)); 93 | value = value >> 8; 94 | } 95 | } 96 | 97 | /// 98 | /// Returns a value built from the specified number of bytes from the given buffer, 99 | /// starting at index. 100 | /// 101 | /// The data in byte array format 102 | /// The first index to use 103 | /// The number of bytes to use 104 | /// The value built from the given bytes 105 | protected override long FromBytes(byte[] buffer, int startIndex, int bytesToConvert) 106 | { 107 | long ret = 0; 108 | for (int i=0; i < bytesToConvert; i++) 109 | { 110 | ret = unchecked((ret << 8) | buffer[startIndex+bytesToConvert-1-i]); 111 | } 112 | return ret; 113 | } 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/MessagePack/LittleEndianBitConverter.cs: -------------------------------------------------------------------------------- 1 | // 2 | /* 3 | "Miscellaneous Utility Library" Software Licence 4 | 5 | Version 1.0 6 | 7 | Copyright (c) 2004-2008 Jon Skeet and Marc Gravell. 8 | All rights reserved. 9 | 10 | Redistribution and use in source and binary forms, with or without 11 | modification, are permitted provided that the following conditions 12 | are met: 13 | 14 | 1. Redistributions of source code must retain the above copyright 15 | notice, this list of conditions and the following disclaimer. 16 | 17 | 2. Redistributions in binary form must reproduce the above copyright 18 | notice, this list of conditions and the following disclaimer in the 19 | documentation and/or other materials provided with the distribution. 20 | 21 | 3. The end-user documentation included with the redistribution, if 22 | any, must include the following acknowledgment: 23 | 24 | "This product includes software developed by Jon Skeet 25 | and Marc Gravell. Contact skeet@pobox.com, or see 26 | http://www.pobox.com/~skeet/)." 27 | 28 | Alternately, this acknowledgment may appear in the software itself, 29 | if and wherever such third-party acknowledgments normally appear. 30 | 31 | 4. The name "Miscellaneous Utility Library" must not be used to endorse 32 | or promote products derived from this software without prior written 33 | permission. For written permission, please contact skeet@pobox.com. 34 | 35 | 5. Products derived from this software may not be called 36 | "Miscellaneous Utility Library", nor may "Miscellaneous Utility Library" 37 | appear in their name, without prior written permission of Jon Skeet. 38 | 39 | THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED 40 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 41 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 42 | IN NO EVENT SHALL JON SKEET BE LIABLE FOR ANY DIRECT, INDIRECT, 43 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 44 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 45 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 46 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 47 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 48 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 49 | POSSIBILITY OF SUCH DAMAGE. 50 | */ 51 | 52 | // ReSharper disable once CheckNamespace 53 | namespace GameDevWare.Serialization.MessagePack 54 | { 55 | /// 56 | /// Implementation of EndianBitConverter which converts to/from little-endian 57 | /// byte arrays. 58 | /// 59 | internal sealed class LittleEndianBitConverter : EndianBitConverter 60 | { 61 | /// 62 | /// Indicates the byte order ("endianess") in which data is converted using this class. 63 | /// 64 | /// 65 | /// Different computer architectures store data using different byte orders. "Big-endian" 66 | /// means the most significant byte is on the left end of a word. "Little-endian" means the 67 | /// most significant byte is on the right end of a word. 68 | /// 69 | /// true if this converter is little-endian, false otherwise. 70 | public override sealed bool IsLittleEndian() 71 | { 72 | return true; 73 | } 74 | 75 | /// 76 | /// Indicates the byte order ("endianess") in which data is converted using this class. 77 | /// 78 | public override sealed Endianness Endianness 79 | { 80 | get { return Endianness.LittleEndian; } 81 | } 82 | 83 | /// 84 | /// Copies the specified number of bytes from value to buffer, starting at index. 85 | /// 86 | /// The value to copy 87 | /// The number of bytes to copy 88 | /// The buffer to copy the bytes into 89 | /// The index to start at 90 | protected override void CopyBytesImpl(long value, int bytes, byte[] buffer, int index) 91 | { 92 | for (var i = 0; i < bytes; i++) 93 | { 94 | buffer[i + index] = unchecked((byte) (value & 0xff)); 95 | value = value >> 8; 96 | } 97 | } 98 | 99 | /// 100 | /// Returns a value built from the specified number of bytes from the given buffer, 101 | /// starting at index. 102 | /// 103 | /// The data in byte array format 104 | /// The first index to use 105 | /// The number of bytes to use 106 | /// The value built from the given bytes 107 | protected override long FromBytes(byte[] buffer, int startIndex, int bytesToConvert) 108 | { 109 | long ret = 0; 110 | for (var i = 0; i < bytesToConvert; i++) 111 | { 112 | ret = unchecked((ret << 8) | buffer[startIndex + bytesToConvert - 1 - i]); 113 | } 114 | return ret; 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/Serializer/Conversion/BigEndianBitConverter.cs: -------------------------------------------------------------------------------- 1 | /* 2 | "Miscellaneous Utility Library" Software Licence 3 | 4 | Version 1.0 5 | 6 | Copyright (c) 2004-2008 Jon Skeet and Marc Gravell. 7 | All rights reserved. 8 | 9 | Redistribution and use in source and binary forms, with or without 10 | modification, are permitted provided that the following conditions 11 | are met: 12 | 13 | 1. Redistributions of source code must retain the above copyright 14 | notice, this list of conditions and the following disclaimer. 15 | 16 | 2. Redistributions in binary form must reproduce the above copyright 17 | notice, this list of conditions and the following disclaimer in the 18 | documentation and/or other materials provided with the distribution. 19 | 20 | 3. The end-user documentation included with the redistribution, if 21 | any, must include the following acknowledgment: 22 | 23 | "This product includes software developed by Jon Skeet 24 | and Marc Gravell. Contact skeet@pobox.com, or see 25 | http://www.pobox.com/~skeet/)." 26 | 27 | Alternately, this acknowledgment may appear in the software itself, 28 | if and wherever such third-party acknowledgments normally appear. 29 | 30 | 4. The name "Miscellaneous Utility Library" must not be used to endorse 31 | or promote products derived from this software without prior written 32 | permission. For written permission, please contact skeet@pobox.com. 33 | 34 | 5. Products derived from this software may not be called 35 | "Miscellaneous Utility Library", nor may "Miscellaneous Utility Library" 36 | appear in their name, without prior written permission of Jon Skeet. 37 | 38 | THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED 39 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 40 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 41 | IN NO EVENT SHALL JON SKEET BE LIABLE FOR ANY DIRECT, INDIRECT, 42 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 43 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 44 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 45 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 46 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 47 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 48 | POSSIBILITY OF SUCH DAMAGE. 49 | */ 50 | 51 | namespace MiscUtil.Conversion 52 | { 53 | /// 54 | /// Implementation of EndianBitConverter which converts to/from big-endian 55 | /// byte arrays. 56 | /// 57 | public sealed class BigEndianBitConverter : EndianBitConverter 58 | { 59 | /// 60 | /// Indicates the byte order ("endianess") in which data is converted using this class. 61 | /// 62 | /// 63 | /// Different computer architectures store data using different byte orders. "Big-endian" 64 | /// means the most significant byte is on the left end of a word. "Little-endian" means the 65 | /// most significant byte is on the right end of a word. 66 | /// 67 | /// true if this converter is little-endian, false otherwise. 68 | public sealed override bool IsLittleEndian() 69 | { 70 | return false; 71 | } 72 | 73 | /// 74 | /// Indicates the byte order ("endianess") in which data is converted using this class. 75 | /// 76 | public sealed override Endianness Endianness 77 | { 78 | get { return Endianness.BigEndian; } 79 | } 80 | 81 | /// 82 | /// Copies the specified number of bytes from value to buffer, starting at index. 83 | /// 84 | /// The value to copy 85 | /// The number of bytes to copy 86 | /// The buffer to copy the bytes into 87 | /// The index to start at 88 | protected override void CopyBytesImpl(long value, int bytes, byte[] buffer, int index) 89 | { 90 | int endOffset = index+bytes-1; 91 | for (int i=0; i < bytes; i++) 92 | { 93 | buffer[endOffset-i] = unchecked((byte)(value&0xff)); 94 | value = value >> 8; 95 | } 96 | } 97 | 98 | /// 99 | /// Returns a value built from the specified number of bytes from the given buffer, 100 | /// starting at index. 101 | /// 102 | /// The data in byte array format 103 | /// The first index to use 104 | /// The number of bytes to use 105 | /// The value built from the given bytes 106 | protected override long FromBytes(byte[] buffer, int startIndex, int bytesToConvert) 107 | { 108 | long ret = 0; 109 | for (int i=0; i < bytesToConvert; i++) 110 | { 111 | ret = unchecked((ret << 8) | buffer[startIndex+i]); 112 | } 113 | return ret; 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/MessagePack/BigEndianBitConverter.cs: -------------------------------------------------------------------------------- 1 | // 2 | /* 3 | "Miscellaneous Utility Library" Software Licence 4 | 5 | Version 1.0 6 | 7 | Copyright (c) 2004-2008 Jon Skeet and Marc Gravell. 8 | All rights reserved. 9 | 10 | Redistribution and use in source and binary forms, with or without 11 | modification, are permitted provided that the following conditions 12 | are met: 13 | 14 | 1. Redistributions of source code must retain the above copyright 15 | notice, this list of conditions and the following disclaimer. 16 | 17 | 2. Redistributions in binary form must reproduce the above copyright 18 | notice, this list of conditions and the following disclaimer in the 19 | documentation and/or other materials provided with the distribution. 20 | 21 | 3. The end-user documentation included with the redistribution, if 22 | any, must include the following acknowledgment: 23 | 24 | "This product includes software developed by Jon Skeet 25 | and Marc Gravell. Contact skeet@pobox.com, or see 26 | http://www.pobox.com/~skeet/)." 27 | 28 | Alternately, this acknowledgment may appear in the software itself, 29 | if and wherever such third-party acknowledgments normally appear. 30 | 31 | 4. The name "Miscellaneous Utility Library" must not be used to endorse 32 | or promote products derived from this software without prior written 33 | permission. For written permission, please contact skeet@pobox.com. 34 | 35 | 5. Products derived from this software may not be called 36 | "Miscellaneous Utility Library", nor may "Miscellaneous Utility Library" 37 | appear in their name, without prior written permission of Jon Skeet. 38 | 39 | THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED 40 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 41 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 42 | IN NO EVENT SHALL JON SKEET BE LIABLE FOR ANY DIRECT, INDIRECT, 43 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 44 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 45 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 46 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 47 | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 48 | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 49 | POSSIBILITY OF SUCH DAMAGE. 50 | */ 51 | 52 | // ReSharper disable once CheckNamespace 53 | namespace GameDevWare.Serialization.MessagePack 54 | { 55 | /// 56 | /// Implementation of EndianBitConverter which converts to/from big-endian 57 | /// byte arrays. 58 | /// 59 | internal sealed class BigEndianBitConverter : EndianBitConverter 60 | { 61 | /// 62 | /// Indicates the byte order ("endianess") in which data is converted using this class. 63 | /// 64 | /// 65 | /// Different computer architectures store data using different byte orders. "Big-endian" 66 | /// means the most significant byte is on the left end of a word. "Little-endian" means the 67 | /// most significant byte is on the right end of a word. 68 | /// 69 | /// true if this converter is little-endian, false otherwise. 70 | public override sealed bool IsLittleEndian() 71 | { 72 | return false; 73 | } 74 | 75 | /// 76 | /// Indicates the byte order ("endianess") in which data is converted using this class. 77 | /// 78 | public override sealed Endianness Endianness 79 | { 80 | get { return Endianness.BigEndian; } 81 | } 82 | 83 | /// 84 | /// Copies the specified number of bytes from value to buffer, starting at index. 85 | /// 86 | /// The value to copy 87 | /// The number of bytes to copy 88 | /// The buffer to copy the bytes into 89 | /// The index to start at 90 | protected override void CopyBytesImpl(long value, int bytes, byte[] buffer, int index) 91 | { 92 | var endOffset = index + bytes - 1; 93 | for (var i = 0; i < bytes; i++) 94 | { 95 | buffer[endOffset - i] = unchecked((byte) (value & 0xff)); 96 | value = value >> 8; 97 | } 98 | } 99 | 100 | /// 101 | /// Returns a value built from the specified number of bytes from the given buffer, 102 | /// starting at index. 103 | /// 104 | /// The data in byte array format 105 | /// The first index to use 106 | /// The number of bytes to use 107 | /// The value built from the given bytes 108 | protected override long FromBytes(byte[] buffer, int startIndex, int bytesToConvert) 109 | { 110 | long ret = 0; 111 | for (var i = 0; i < bytesToConvert; i++) 112 | { 113 | ret = unchecked((ret << 8) | buffer[startIndex + i]); 114 | } 115 | return ret; 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/ArraySerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections; 18 | using System.Collections.Generic; 19 | using System.Linq; 20 | using System.Runtime.CompilerServices; 21 | 22 | // ReSharper disable once CheckNamespace 23 | namespace GameDevWare.Serialization.Serializers 24 | { 25 | public sealed class ArraySerializer : TypeSerializer 26 | { 27 | private readonly Type arrayType; 28 | private readonly Type instantiatedArrayType; 29 | private readonly Type elementType; 30 | 31 | public override Type SerializedType { get { return this.arrayType; } } 32 | 33 | public ArraySerializer(Type enumerableType) 34 | { 35 | if (enumerableType == null) throw new ArgumentNullException("enumerableType"); 36 | 37 | this.arrayType = 38 | this.instantiatedArrayType = enumerableType; 39 | this.elementType = this.GetElementType(arrayType); 40 | 41 | if (this.elementType == null) JsonSerializationException.TypeIsNotValid(this.GetType(), "be enumerable"); 42 | 43 | if (this.arrayType == typeof(IList) || this.arrayType == typeof(ICollection) || this.arrayType == typeof(IEnumerable)) 44 | this.instantiatedArrayType = typeof(ArrayList); 45 | else if (arrayType.IsInterface && arrayType.IsGenericType && (arrayType.GetGenericTypeDefinition() == typeof(IList<>) || arrayType.GetGenericTypeDefinition() == typeof(ICollection<>) || arrayType.GetGenericTypeDefinition() == typeof(IEnumerable<>))) 46 | this.instantiatedArrayType = typeof(List<>).MakeGenericType(this.elementType); 47 | } 48 | 49 | public override object Deserialize(IJsonReader reader) 50 | { 51 | if (reader == null) throw new ArgumentNullException("reader"); 52 | 53 | if (reader.Token == JsonToken.Null) 54 | return null; 55 | 56 | var container = new ArrayList(); 57 | if (reader.Token != JsonToken.BeginArray) 58 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.BeginArray); 59 | 60 | reader.Context.Hierarchy.Push(container); 61 | while (reader.NextToken() && reader.Token != JsonToken.EndOfArray) 62 | { 63 | var value = reader.ReadValue(this.elementType, false); 64 | container.Add(value); 65 | } 66 | reader.Context.Hierarchy.Pop(); 67 | 68 | if (reader.IsEndOfStream()) 69 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.EndOfArray); 70 | 71 | if (this.instantiatedArrayType == typeof(ArrayList)) 72 | return container; 73 | else if (this.instantiatedArrayType.IsArray) 74 | return container.ToArray(this.elementType); 75 | else 76 | return Activator.CreateInstance(this.instantiatedArrayType, container.ToArray(this.elementType)); 77 | } 78 | 79 | public override void Serialize(IJsonWriter writer, object value) 80 | { 81 | if (writer == null) throw new ArgumentNullException("writer"); 82 | if (value == null) throw new ArgumentNullException("value"); 83 | 84 | var size = 0; 85 | if (value is ICollection) 86 | size = ((ICollection)value).Count; 87 | else 88 | size = ((IEnumerable)value).Cast().Count(); 89 | 90 | writer.WriteArrayBegin(size); 91 | foreach (var item in (IEnumerable)value) 92 | writer.WriteValue(item, this.elementType); 93 | writer.WriteArrayEnd(); 94 | } 95 | 96 | private Type GetElementType(Type arrayType) 97 | { 98 | if (arrayType == null) throw new ArgumentNullException("arrayType"); 99 | 100 | 101 | var elementType = (Type)null; 102 | if (arrayType.IsArray) 103 | { 104 | elementType = arrayType.GetElementType(); 105 | return elementType; 106 | } 107 | 108 | if (arrayType.IsInstantiationOf(typeof(IEnumerable<>))) 109 | { 110 | if (arrayType.HasMultipleInstantiations(typeof(IEnumerable<>))) 111 | throw JsonSerializationException.TypeIsNotValid(this.GetType(), "have only one generic IEnumerable interface"); 112 | 113 | elementType = arrayType.GetInstantiationArguments(typeof(IEnumerable<>))[0]; 114 | } 115 | 116 | if (elementType == null && typeof(IEnumerable).IsAssignableFrom(arrayType)) 117 | elementType = typeof(object); 118 | else if (elementType == null) 119 | throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be enumerable"); 120 | 121 | return elementType; 122 | } 123 | 124 | public override string ToString() 125 | { 126 | return string.Format("array of {1}, {0}", this.arrayType, this.elementType); 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/StateListener/Compare.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections; 4 | using System.Collections.Generic; 5 | 6 | using GameDevWare.Serialization; 7 | using GameDevWare.Serialization.MessagePack; 8 | 9 | namespace Colyseus 10 | { 11 | public struct PatchObject 12 | { 13 | public string[] path; 14 | public string operation; // : "add" | "remove" | "replace"; 15 | public object value; 16 | } 17 | 18 | public class Compare 19 | { 20 | 21 | public static PatchObject[] GetPatchList(IndexedDictionary tree1, IndexedDictionary tree2) 22 | { 23 | List patches = new List(); 24 | List path = new List(); 25 | 26 | Generate(tree1, tree2, patches, path); 27 | 28 | return patches.ToArray(); 29 | } 30 | 31 | protected static void Generate(List mirror, List obj, List patches, List path) 32 | { 33 | var mirrorDict = new IndexedDictionary (); 34 | for (int i = 0; i < mirror.Count; i++) { 35 | mirrorDict.Add (i.ToString(), mirror.ElementAt (i)); 36 | } 37 | 38 | var objDict = new IndexedDictionary (); 39 | for (int i = 0; i < obj.Count; i++) { 40 | objDict.Add (i.ToString(), obj.ElementAt (i)); 41 | } 42 | 43 | Generate (mirrorDict, objDict, patches, path); 44 | } 45 | 46 | // Dirty check if obj is different from mirror, generate patches and update mirror 47 | protected static void Generate(IndexedDictionary mirror, IndexedDictionary obj, List patches, List path) 48 | { 49 | var newKeys = obj.Keys; 50 | var oldKeys = mirror.Keys; 51 | var deleted = false; 52 | 53 | for (int i = 0; i < oldKeys.Count; i++) 54 | { 55 | var key = oldKeys [i]; 56 | if ( 57 | obj.ContainsKey(key) && 58 | obj[key] != null && 59 | !(!obj.ContainsKey(key) && mirror.ContainsKey(key)) 60 | ) 61 | { 62 | var oldVal = mirror[key]; 63 | var newVal = obj[key]; 64 | 65 | if ( 66 | oldVal != null && newVal != null && 67 | !oldVal.GetType ().IsPrimitive && oldVal.GetType () != typeof(string) && 68 | !newVal.GetType ().IsPrimitive && newVal.GetType () != typeof(string) && 69 | Object.ReferenceEquals(oldVal.GetType (), newVal.GetType ()) 70 | ) 71 | { 72 | List deeperPath = new List(path); 73 | deeperPath.Add((string) key); 74 | 75 | if (oldVal is IndexedDictionary) { 76 | Generate( 77 | (IndexedDictionary) oldVal, 78 | (IndexedDictionary) newVal, 79 | patches, 80 | deeperPath 81 | ); 82 | 83 | } else if (oldVal is List) { 84 | Generate( 85 | ((List) oldVal), 86 | ((List) newVal), 87 | patches, 88 | deeperPath 89 | ); 90 | } 91 | 92 | } else { 93 | if ( 94 | (oldVal == null && newVal != null) || 95 | !oldVal.Equals(newVal) 96 | ) 97 | { 98 | List replacePath = new List(path); 99 | replacePath.Add((string) key); 100 | 101 | patches.Add(new PatchObject 102 | { 103 | operation = "replace", 104 | path = replacePath.ToArray(), 105 | value = newVal 106 | }); 107 | } 108 | } 109 | } 110 | else { 111 | List removePath = new List(path); 112 | removePath.Add((string) key); 113 | 114 | patches.Add(new PatchObject 115 | { 116 | operation = "remove", 117 | path = removePath.ToArray() 118 | }); 119 | 120 | deleted = true; // property has been deleted 121 | } 122 | } 123 | 124 | if (!deleted && newKeys.Count == oldKeys.Count) { 125 | return; 126 | } 127 | 128 | foreach (var key in newKeys) 129 | { 130 | 131 | if (!mirror.ContainsKey(key) && obj.ContainsKey(key)) 132 | { 133 | List addPath = new List(path); 134 | addPath.Add((string) key); 135 | 136 | var newVal = obj [key]; 137 | if (newVal != null) { 138 | var newValType = newVal.GetType (); 139 | 140 | // compare deeper additions 141 | if ( 142 | !newValType.IsPrimitive && 143 | newValType != typeof(string) 144 | ) { 145 | if (newVal is IDictionary) { 146 | Generate(new IndexedDictionary(), newVal as IndexedDictionary, patches, addPath); 147 | 148 | } else if (newVal is IList) { 149 | Generate(new List(), newVal as List, patches, addPath); 150 | } 151 | } 152 | } 153 | 154 | patches.Add(new PatchObject 155 | { 156 | operation = "add", 157 | path = addPath.ToArray(), 158 | value = newVal 159 | }); 160 | } 161 | } 162 | 163 | } 164 | 165 | // protected static List GetObjectKeys (object data) 166 | // { 167 | // if (data is IndexedDictionary) { 168 | // var d = (IndexedDictionary)data; 169 | // return d.Keys; 170 | // 171 | // } else if (data is List) { 172 | // var d = (IndexedDictionary)data; 173 | //// d.Keys 174 | // return d.Keys; 175 | // } 176 | // 177 | // } 178 | 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Serializers/PrimitiveTypeSerializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | 18 | // ReSharper disable once CheckNamespace 19 | namespace GameDevWare.Serialization.Serializers 20 | { 21 | public sealed class PrimitiveSerializer : TypeSerializer 22 | { 23 | private readonly Type primitiveType; 24 | private readonly TypeCode primitiveTypeCode; 25 | 26 | public override Type SerializedType { get { return this.primitiveType; } } 27 | 28 | public PrimitiveSerializer(Type primitiveType) 29 | { 30 | if (primitiveType == null) throw new ArgumentNullException("primitiveType"); 31 | 32 | if (primitiveType.IsGenericType && primitiveType.GetGenericTypeDefinition() == typeof(Nullable<>)) 33 | throw JsonSerializationException.TypeIsNotValid(typeof(PrimitiveSerializer), "can't be nullable type"); 34 | 35 | this.primitiveType = primitiveType; 36 | this.primitiveTypeCode = Type.GetTypeCode(primitiveType); 37 | 38 | if (this.primitiveTypeCode == TypeCode.Object || this.primitiveTypeCode == TypeCode.Empty || 39 | this.primitiveTypeCode == TypeCode.DBNull) 40 | throw JsonSerializationException.TypeIsNotValid(this.GetType(), "be a primitive type"); 41 | } 42 | 43 | public override object Deserialize(IJsonReader reader) 44 | { 45 | if (reader == null) throw new ArgumentNullException("reader"); 46 | 47 | if (reader.Token == JsonToken.Null) 48 | { 49 | if (this.primitiveTypeCode == TypeCode.String) 50 | return null; 51 | 52 | throw JsonSerializationException.UnexpectedToken(reader, JsonToken.Boolean, JsonToken.DateTime, JsonToken.Null, JsonToken.Number, JsonToken.StringLiteral); 53 | } 54 | 55 | var value = default(object); 56 | switch (primitiveTypeCode) 57 | { 58 | case TypeCode.Boolean: 59 | value = reader.ReadBoolean(false); 60 | break; 61 | case TypeCode.Byte: 62 | value = reader.ReadByte(false); 63 | break; 64 | case TypeCode.DateTime: 65 | value = reader.ReadDateTime(false); 66 | break; 67 | case TypeCode.Decimal: 68 | value = reader.ReadDecimal(false); 69 | break; 70 | case TypeCode.Double: 71 | value = reader.ReadDouble(false); 72 | break; 73 | case TypeCode.Int16: 74 | value = reader.ReadInt16(false); 75 | break; 76 | case TypeCode.Int32: 77 | value = reader.ReadInt32(false); 78 | break; 79 | case TypeCode.Int64: 80 | value = reader.ReadInt64(false); 81 | break; 82 | case TypeCode.SByte: 83 | value = reader.ReadSByte(false); 84 | break; 85 | case TypeCode.Single: 86 | value = reader.ReadSingle(false); 87 | break; 88 | case TypeCode.UInt16: 89 | value = reader.ReadUInt16(false); 90 | break; 91 | case TypeCode.UInt32: 92 | value = reader.ReadUInt32(false); 93 | break; 94 | case TypeCode.UInt64: 95 | value = reader.ReadUInt64(false); 96 | break; 97 | default: 98 | var valueStr = reader.ReadString(false); 99 | value = Convert.ChangeType(valueStr, this.primitiveType, reader.Context.Format); 100 | break; 101 | } 102 | return value; 103 | } 104 | 105 | public override void Serialize(IJsonWriter writer, object value) 106 | { 107 | if (writer == null) throw new ArgumentNullException("writer"); 108 | if (value == null) throw new ArgumentNullException("value"); 109 | 110 | switch (primitiveTypeCode) 111 | { 112 | case TypeCode.Boolean: 113 | writer.WriteBoolean((bool)value); 114 | break; 115 | case TypeCode.Byte: 116 | writer.WriteNumber((byte)value); 117 | break; 118 | case TypeCode.DateTime: 119 | writer.WriteDateTime((DateTime)value); 120 | break; 121 | case TypeCode.Decimal: 122 | writer.WriteNumber((decimal)value); 123 | break; 124 | case TypeCode.Double: 125 | writer.WriteNumber((double)value); 126 | break; 127 | case TypeCode.Int16: 128 | writer.WriteNumber((short)value); 129 | break; 130 | case TypeCode.Int32: 131 | writer.WriteNumber((int)value); 132 | break; 133 | case TypeCode.Int64: 134 | writer.WriteNumber((long)value); 135 | break; 136 | case TypeCode.SByte: 137 | writer.WriteNumber((sbyte)value); 138 | break; 139 | case TypeCode.Single: 140 | writer.WriteNumber((float)value); 141 | break; 142 | case TypeCode.UInt16: 143 | writer.WriteNumber((ushort)value); 144 | break; 145 | case TypeCode.UInt32: 146 | writer.WriteNumber((uint)value); 147 | break; 148 | case TypeCode.UInt64: 149 | writer.WriteNumber((ulong)value); 150 | break; 151 | default: 152 | var valueStr = default(string); 153 | 154 | if (value is IFormattable) 155 | valueStr = (string)Convert.ChangeType(value, typeof(string), writer.Context.Format); 156 | else 157 | valueStr = value.ToString(); 158 | 159 | writer.WriteString(valueStr); 160 | break; 161 | } 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /Assets/Plugins/Colyseus/StateListener/StateContainer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.RegularExpressions; 3 | using System.Collections.Generic; 4 | 5 | using GameDevWare.Serialization; 6 | 7 | namespace Colyseus 8 | { 9 | using PatchListener = Listener>; 10 | using FallbackPatchListener = Listener>; 11 | 12 | public struct DataChange 13 | { 14 | public Dictionary path; 15 | public string operation; // : "add" | "remove" | "replace"; 16 | public object value; 17 | } 18 | 19 | public struct Listener 20 | { 21 | public T callback; 22 | public Regex[] rules; 23 | public string[] rawRules; 24 | } 25 | 26 | public class StateContainer 27 | { 28 | public IndexedDictionary state; 29 | private List listeners; 30 | private FallbackPatchListener defaultListener; 31 | 32 | private Dictionary matcherPlaceholders = new Dictionary() 33 | { 34 | { ":id", new Regex(@"^([a-zA-Z0-9\-_]+)$") }, 35 | { ":number", new Regex(@"^([0-9]+)$") }, 36 | { ":string", new Regex(@"^(\w+)$") }, 37 | { ":axis", new Regex(@"^([xyz])$") }, 38 | { ":*", new Regex(@"(.*)") }, 39 | }; 40 | 41 | public StateContainer (IndexedDictionary state) 42 | { 43 | this.state = state; 44 | this.Reset(); 45 | } 46 | 47 | public PatchObject[] Set(IndexedDictionary newData) { 48 | var patches = Compare.GetPatchList(this.state, newData); 49 | 50 | this.CheckPatches(patches); 51 | this.state = newData; 52 | 53 | return patches; 54 | } 55 | 56 | public void RegisterPlaceholder(string placeholder, Regex matcher) 57 | { 58 | this.matcherPlaceholders[placeholder] = matcher; 59 | } 60 | 61 | public FallbackPatchListener Listen(Action callback) 62 | { 63 | FallbackPatchListener listener = new FallbackPatchListener { 64 | callback = callback, 65 | rules = new Regex[]{} 66 | }; 67 | 68 | this.defaultListener = listener; 69 | 70 | return listener; 71 | } 72 | 73 | public PatchListener Listen(string segments, Action callback, bool immediate = false) { 74 | var rawRules = segments.Split ('/'); 75 | var regexpRules = this.ParseRegexRules (rawRules); 76 | 77 | PatchListener listener = new PatchListener { 78 | callback = callback, 79 | rules = regexpRules, 80 | rawRules = rawRules 81 | }; 82 | 83 | this.listeners.Add(listener); 84 | 85 | if (immediate) { 86 | List onlyListener = new List(); 87 | onlyListener.Add(listener); 88 | this.CheckPatches(Compare.GetPatchList(new IndexedDictionary(), this.state), onlyListener); 89 | } 90 | 91 | return listener; 92 | } 93 | 94 | public void RemoveListener(PatchListener listener) 95 | { 96 | for (var i = this.listeners.Count - 1; i >= 0; i--) 97 | { 98 | if (this.listeners[i].Equals(listener)) 99 | { 100 | this.listeners.RemoveAt(i); 101 | } 102 | } 103 | } 104 | 105 | public void RemoveAllListeners() 106 | { 107 | this.Reset(); 108 | } 109 | 110 | protected Regex[] ParseRegexRules (string[] rules) 111 | { 112 | Regex[] regexpRules = new Regex[rules.Length]; 113 | 114 | for (int i = 0; i < rules.Length; i++) 115 | { 116 | var segment = rules[i]; 117 | if (segment.IndexOf(':') == 0) 118 | { 119 | if (this.matcherPlaceholders.ContainsKey(segment)) 120 | { 121 | regexpRules[i] = this.matcherPlaceholders[segment]; 122 | } 123 | else { 124 | regexpRules[i] = this.matcherPlaceholders[":*"]; 125 | } 126 | 127 | } else { 128 | regexpRules[i] = new Regex("^" + segment + "$"); 129 | } 130 | } 131 | 132 | return regexpRules; 133 | } 134 | 135 | private void CheckPatches(PatchObject[] patches, List _listeners = null) 136 | { 137 | if (_listeners == null) 138 | { 139 | _listeners = this.listeners; 140 | } 141 | 142 | for (var i = patches.Length - 1; i >= 0; i--) 143 | { 144 | var matched = false; 145 | 146 | for (var j = 0; j < _listeners.Count; j++) 147 | { 148 | var listener = _listeners[j]; 149 | var pathVariables = this.GetPathVariables(patches[i], listener); 150 | if (pathVariables != null) 151 | { 152 | DataChange dataChange = new DataChange 153 | { 154 | path = pathVariables, 155 | operation = patches[i].operation, 156 | value = patches[i].value 157 | }; 158 | 159 | listener.callback.Invoke (dataChange); 160 | matched = true; 161 | } 162 | } 163 | 164 | // check for fallback listener 165 | if (!matched && !object.Equals(this.defaultListener, default(FallbackPatchListener))) 166 | { 167 | this.defaultListener.callback.Invoke (patches [i]); 168 | } 169 | 170 | } 171 | 172 | } 173 | 174 | private Dictionary GetPathVariables(PatchObject patch, PatchListener listener) { 175 | var result = new Dictionary (); 176 | 177 | // skip if rules count differ from patch 178 | if (patch.path.Length != listener.rules.Length) { 179 | return null; 180 | } 181 | 182 | for (var i = 0; i < listener.rules.Length; i++) { 183 | var matches = listener.rules[i].Matches(patch.path[i]); 184 | if (matches.Count == 0 || matches.Count > 2) { 185 | return null; 186 | 187 | } else if (listener.rawRules[i][0] == ':') { 188 | result.Add ( listener.rawRules[i].Substring(1), matches[0].ToString() ); 189 | } 190 | } 191 | 192 | return result; 193 | } 194 | 195 | private void Reset() 196 | { 197 | this.listeners = new List (); 198 | 199 | this.defaultListener = default(FallbackPatchListener); 200 | } 201 | 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /Assets/Plugins/GameDevWare.Serialization/Metadata/TypeDescription.cs: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Denis Zykov, GameDevWare.com 3 | 4 | This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918 5 | 6 | THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND 7 | REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE 8 | IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, 9 | FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE 10 | AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. 11 | 12 | This source code is distributed via Unity Asset Store, 13 | to use it in your project you should accept Terms of Service and EULA 14 | https://unity3d.com/ru/legal/as_terms 15 | */ 16 | using System; 17 | using System.Collections; 18 | using System.Collections.Generic; 19 | using System.Collections.ObjectModel; 20 | using System.Linq; 21 | using System.Reflection; 22 | using System.Runtime.CompilerServices; 23 | 24 | // ReSharper disable once CheckNamespace 25 | namespace GameDevWare.Serialization.Metadata 26 | { 27 | internal class TypeDescription : MemberDescription 28 | { 29 | private static readonly Dictionary TypeDescriptions = new Dictionary(); 30 | 31 | private readonly Type objectType; 32 | private readonly Func constructorFn; 33 | private readonly ReadOnlyCollection members; 34 | private readonly Dictionary membersByName; 35 | 36 | public Type ObjectType { get { return this.objectType; } } 37 | public bool IsAnonymousType { get; private set; } 38 | public bool IsEnumerable { get; private set; } 39 | public bool IsDictionary { get; private set; } 40 | public bool IsDataContract { get; private set; } 41 | public bool IsSerializable { get; private set; } 42 | public ReadOnlyCollection Members { get { return this.members; } } 43 | 44 | public TypeDescription(Type objectType) 45 | : base(null, objectType) 46 | { 47 | if (objectType == null) throw new ArgumentNullException("objectType"); 48 | 49 | this.objectType = objectType; 50 | this.IsDataContract = this.Attributes.Any(attribute => attribute.GetType().Name == DATA_CONTRACT_ATTRIBUTE_NAME); 51 | this.IsSerializable = objectType.IsSerializable; 52 | this.IsEnumerable = objectType.IsInstantiationOf(typeof(Enumerable)) && objectType != typeof(string); 53 | this.IsDictionary = typeof(IDictionary).IsAssignableFrom(objectType); 54 | this.IsAnonymousType = objectType.IsSealed && objectType.IsNotPublic && objectType.GetCustomAttributes(typeof(CompilerGeneratedAttribute), true).Length > 0; ; 55 | 56 | var allMembers = this.FindMembers(objectType); 57 | 58 | this.members = allMembers.AsReadOnly(); 59 | this.membersByName = allMembers.ToDictionary(m => m.Name, StringComparer.Ordinal); 60 | 61 | GettersAndSetters.TryGetConstructor(objectType, out this.constructorFn); 62 | } 63 | 64 | private List FindMembers(Type objectType) 65 | { 66 | if (objectType == null) throw new ArgumentNullException("objectType"); 67 | 68 | var members = new List(); 69 | var memberNames = new HashSet(StringComparer.Ordinal); 70 | 71 | var isOptIn = objectType.GetCustomAttributes(false).Any(a => a.GetType().Name == DATA_CONTRACT_ATTRIBUTE_NAME); 72 | var searchFlags = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | (isOptIn ? BindingFlags.NonPublic : 0); 73 | var properties = objectType.GetProperties(searchFlags); 74 | var fields = objectType.GetFields(searchFlags); 75 | 76 | foreach (var member in properties.Cast().Concat(fields.Cast())) 77 | { 78 | if (member is PropertyInfo && (member as PropertyInfo).GetIndexParameters().Length != 0) 79 | continue; 80 | 81 | var dataMemberAttribute = member.GetCustomAttributes(false).FirstOrDefault(a => a.GetType().Name == DATA_MEMBER_ATTRIBUTE_NAME); 82 | var ignoreMemberAttribute = member.GetCustomAttributes(false).FirstOrDefault(a => a.GetType().Name == IGNORE_DATA_MEMBER_ATTRIBUTE_NAME); 83 | 84 | if (isOptIn && dataMemberAttribute == null) 85 | continue; 86 | else if (!isOptIn && ignoreMemberAttribute != null) 87 | continue; 88 | 89 | var dataMember = default(DataMemberDescription); 90 | if (member is PropertyInfo) dataMember = new PropertyDescription(this, member as PropertyInfo); 91 | else if (member is FieldInfo) dataMember = new FieldDescription(this, member as FieldInfo); 92 | else throw new InvalidOperationException("Unknown member type. Should be PropertyInfo or FieldInfo."); 93 | 94 | if (string.IsNullOrEmpty(dataMember.Name)) 95 | throw JsonSerializationException.TypeIsNotValid(objectType, "has no members with empty name"); 96 | 97 | if (memberNames.Contains(dataMember.Name)) 98 | { 99 | var conflictingMember = members.First(m => m.Name == dataMember.Name); 100 | throw JsonSerializationException.TypeIsNotValid(objectType, string.Format("has no duplicate member's name '{0}' ('{1}.{2}' and '{3}.{4}')", dataMember.Name, conflictingMember.Member.DeclaringType.Name, conflictingMember.Member.Name, dataMember.Member.DeclaringType.Name, dataMember.Member.Name)); 101 | } 102 | 103 | members.Add(dataMember); 104 | memberNames.Add(dataMember.Name); 105 | } 106 | 107 | return members; 108 | } 109 | 110 | public bool TryGetMember(string name, out DataMemberDescription member) 111 | { 112 | return this.membersByName.TryGetValue(name, out member); 113 | } 114 | 115 | public object CreateInstance() 116 | { 117 | if (this.constructorFn != null) 118 | return this.constructorFn(); 119 | else 120 | return Activator.CreateInstance(this.objectType); 121 | } 122 | 123 | public static TypeDescription Get(Type type) 124 | { 125 | if (type == null) throw new ArgumentNullException("type"); 126 | 127 | lock (TypeDescriptions) 128 | { 129 | TypeDescription objectTypeDescription; 130 | if (!TypeDescriptions.TryGetValue(type, out objectTypeDescription)) 131 | TypeDescriptions.Add(type, objectTypeDescription = new TypeDescription(type)); 132 | return objectTypeDescription; 133 | } 134 | } 135 | 136 | public override string ToString() 137 | { 138 | return this.objectType.ToString(); 139 | } 140 | } 141 | } 142 | --------------------------------------------------------------------------------