public void SetValue(object target, object value, GameObject go = null) #endif { #if !UNITY_EDITOR try #endif { if (field != null) { value = Serialization.ConvertObject(value, field.FieldType, go); field.SetValue(target, value); } else if (property != null && property.CanWrite) { value = Serialization.ConvertObject(value, property.PropertyType, go); property.SetValue(target, value, null); } #if UNITY_EDITOR else { Debug.LogError("No property or field to set"); } #endif } #if !UNITY_EDITOR catch (Exception ex) { Tools.LogError(ex.GetType() + ": " + ex.Message); } #endif }
/// <summary> /// Transfer the specified object to another channel, changing its Object ID in the process. /// </summary> public CreatedObject TransferObject(uint objectID, Channel other) { if (objectID < 32768) { Tools.LogError("Transferring objects only works with objects that were instantiated at run-time."); } else if (mCreatedObjectDictionary.Remove(objectID)) { for (int i = 0; i < created.size; ++i) { CreatedObject obj = created[i]; if (obj.objectID == objectID) { // Move the created object over to the other channel obj.objectID = other.GetUniqueID(); // If the other channel doesn't contain the object's owner, assign a new owner bool changeOwner = true; for (int b = 0; b < other.players.size; ++b) { if (other.players[b].id == obj.playerID) { changeOwner = false; break; } } if (changeOwner) { obj.playerID = (other.host != null) ? other.host.id : 0; } created.RemoveAt(i); other.created.Add(obj); other.mCreatedObjectDictionary[obj.objectID] = true; // Move RFCs over to the other channel for (int b = rfcs.size; b > 0;) { RFC r = rfcs[--b]; if (r.objectID == objectID) { r.objectID = obj.objectID; rfcs.RemoveAt(b); other.rfcs.Add(r); } } return(obj); } } } return(null); }
/// <summary> /// Create a new instance of the specified object. /// </summary> static public object Create(this Type type) { try { return(Activator.CreateInstance(type)); } catch (Exception ex) { Tools.LogError(ex.Message); return(null); } }
/// <summary> /// Send the specified datagram. /// </summary> public void Send(Buffer buffer, IPEndPoint ip) { #if !MODDING if (ip.Address.Equals(IPAddress.Broadcast)) { Broadcast(buffer, ip.Port); } else if (mSocket != null) { if (mSocket.AddressFamily != ip.AddressFamily) { #if UNITY_EDITOR UnityEngine.Debug.LogError("UDP socket " + name + " (" + mSocket.AddressFamily + ") and the desired address " + ip.Address + " (" + ip.AddressFamily + ") were started with different address families"); #else Tools.LogError("UDP socket " + name + " (" + mSocket.AddressFamily + ") and the desired address " + ip.Address + " (" + ip.AddressFamily + ") were started with different address families"); #endif return; } buffer.MarkAsUsed(); buffer.BeginReading(); lock (mOut) { Datagram dg = new Datagram(); dg.buffer = buffer; dg.ip = ip; mOut.Enqueue(dg); if (mOut.Count == 1) { try { // If it's the first datagram, begin the sending process mSocket.BeginSendTo(buffer.buffer, buffer.position, buffer.size, SocketFlags.None, ip, OnSend, null); } catch (Exception ex) { Tools.LogError(ex.Message + "\n" + ex.StackTrace); buffer.Recycle(); } } } } else { Tools.LogError("The socket is null. Did you forget to call UdpProtocol.Start()?"); } #endif }
/// <summary> /// Start listening for incoming connections. /// </summary> public override bool Start(int listenPort) { Stop(); try { mListener = new TcpListener(IPAddress.Any, listenPort); mListener.Start(50); mPort = listenPort; } #if STANDALONE catch (System.Exception ex) { Tools.LogError(ex.Message, ex.StackTrace); return(false); } Tools.Print("TCP Lobby Server started on port " + listenPort);
public void SetValue(object target, object value, GameObject go = null) #endif { try { if (field != null) { value = Serialization.ConvertObject(value, field.FieldType, go); field.SetValue(target, value); } else if (property != null && property.CanWrite) { value = Serialization.ConvertObject(value, property.PropertyType, go); property.SetValue(target, value, null); } } catch (Exception ex) { Tools.LogError(ex.GetType() + ": " + ex.Message); } }
/// <summary> /// Log an error message. /// </summary> public void LogError(string error, string stack = null, bool logInFile = true) { StringBuilder sb = new StringBuilder(); sb.Append(name); sb.Append(" ("); sb.Append(address); if (aliases != null) { for (int i = 0; i < aliases.size; ++i) { sb.Append(", " + aliases.buffer[i]); } } sb.Append("): "); sb.Append(error); Tools.LogError(sb.ToString(), stack, logInFile); }
/// <summary> /// Send the specified datagram. /// </summary> public void Send(Buffer buffer, IPEndPoint ip) { if (ip.Address.Equals(IPAddress.Broadcast)) { Broadcast(buffer, ip.Port); } else if (mSocket != null) { buffer.MarkAsUsed(); buffer.BeginReading(); lock (mOut) { Datagram dg = new Datagram(); dg.buffer = buffer; dg.ip = ip; mOut.Enqueue(dg); if (mOut.Count == 1) { try { // If it's the first datagram, begin the sending process mSocket.BeginSendTo(buffer.buffer, buffer.position, buffer.size, SocketFlags.None, ip, OnSend, null); } catch (Exception ex) { Tools.LogError(ex.Message + "\n" + ex.StackTrace); buffer.Recycle(); } } } } else { Tools.LogError("The socket is null. Did you forget to call UdpProtocol.Start()?"); } }
/// <summary> /// Create a new instance of the specified object. /// </summary> static public object Create(this Type type) { if (type != null) { try { return(Activator.CreateInstance(type)); } catch (Exception ex) { var p = GameServer.currentPlayer; if (p != null) { p.LogError(ex.Message, ex.StackTrace, true); } else { Tools.LogError(ex.Message); } } } return(default(Type)); }
/// <summary> /// Start listening for incoming connections. /// </summary> public override bool Start(int listenPort) { Stop(); Tools.LoadList(banFilePath, mBan); #if FORCE_EN_US Tools.SetCurrentCultureToEnUS(); #endif try { mListener = new TcpListener(TNet.TcpProtocol.defaultListenerInterface, listenPort); mListener.Start(50); mPort = listenPort; } #if STANDALONE catch (System.Exception ex) { Tools.LogError(ex.Message, ex.StackTrace); return(false); } Tools.Print("Bans: " + mBan.Count); Tools.Print("TCP Lobby Server started on port " + listenPort);
/// <summary> /// See if the received packet can be processed and split it up into different ones. /// </summary> bool ProcessBuffer(int bytes) { if (mReceiveBuffer == null) { // Create a new packet buffer mReceiveBuffer = Buffer.Create(); mReceiveBuffer.BeginWriting(false).Write(mTemp, 0, bytes); mExpected = 0; mOffset = 0; } else { // Append this data to the end of the last used buffer mReceiveBuffer.BeginWriting(true).Write(mTemp, 0, bytes); } for (int available = mReceiveBuffer.size - mOffset; available >= 4;) { // Figure out the expected size of the packet if (mExpected == 0) { mExpected = mReceiveBuffer.PeekInt(mOffset); // "GET " -- HTTP GET request sent by a web browser if (mExpected == 542393671) { if (httpGetSupport) { if (stage == Stage.Verifying || stage == Stage.WebBrowser) { stage = Stage.WebBrowser; string request = Encoding.ASCII.GetString(mReceiveBuffer.buffer, mOffset, available); mReceiveBuffer.BeginPacket(Packet.RequestHTTPGet).Write(request); mReceiveBuffer.EndPacket(); mReceiveBuffer.BeginReading(4); lock (mIn) mIn.Enqueue(mReceiveBuffer); mReceiveBuffer = null; mExpected = 0; mOffset = 0; } return(true); } mReceiveBuffer.Recycle(); mReceiveBuffer = null; mExpected = 0; mOffset = 0; Disconnect(); return(false); } else if (mExpected < 0 || mExpected > 16777216) { #if UNITY_EDITOR UnityEngine.Debug.LogError("Malformed data packet: " + mOffset + ", " + available + " / " + mExpected); #else Tools.LogError("Malformed data packet: " + mOffset + ", " + available + " / " + mExpected); #endif mReceiveBuffer.Recycle(); mReceiveBuffer = null; mExpected = 0; mOffset = 0; Disconnect(); return(false); } } // The first 4 bytes of any packet always contain the number of bytes in that packet available -= 4; // If the entire packet is present if (available == mExpected) { // Reset the position to the beginning of the packet mReceiveBuffer.BeginReading(mOffset + 4); // This packet is now ready to be processed lock (mIn) mIn.Enqueue(mReceiveBuffer); mReceiveBuffer = null; mExpected = 0; mOffset = 0; break; } else if (available > mExpected) { // There is more than one packet. Extract this packet fully. int realSize = mExpected + 4; Buffer temp = Buffer.Create(); // Extract the packet and move past its size component BinaryWriter bw = temp.BeginWriting(false); bw.Write(mReceiveBuffer.buffer, mOffset, realSize); temp.BeginReading(4); // This packet is now ready to be processed lock (mIn) mIn.Enqueue(temp); // Skip this packet available -= mExpected; mOffset += realSize; mExpected = 0; } else { break; } } return(true); }
/// <summary> /// Process the string values, converting them to proper objects. /// Returns whether child nodes should be processed in turn. /// </summary> public bool ResolveValue(Type type = null) { if (mValue is string) { mResolved = true; string line = mValue as string; // Trim strings wrapped in quotes if (type == typeof(string)) { if (line == "\"\"") { mValue = ""; } else { int len = line.Length; if (len > 2 && line[0] == '"' && line[len - 1] == '"') { mValue = line.Substring(1, len - 2); } } return(true); } // Try to resolve this type as a simple type if (Serialization.ReadObject(line, out mValue, type)) { return(true); } // This type is either a class or an array if (type == null) { type = Serialization.NameToType(line); } if (type == null || type == typeof(void)) { mValue = null; return(true); } else if (type.Implements(typeof(IDataNodeSerializable))) { IDataNodeSerializable ds = (IDataNodeSerializable)type.Create(); ds.Deserialize(this); mValue = ds; return(false); } #if !STANDALONE else if (type == typeof(AnimationCurve)) { if (children.size != 0) { AnimationCurve cv = new AnimationCurve(); Keyframe[] kfs = new Keyframe[children.size]; for (int i = 0; i < children.size; ++i) { DataNode child = children[i]; if (child.value == null) { child.mValue = child.name; child.mResolved = false; child.ResolveValue(typeof(Vector4)); Vector4 v = (Vector4)child.mValue; kfs[i] = new Keyframe(v.x, v.y, v.z, v.w); } else { Vector4 v = (Vector4)child.mValue; kfs[i] = new Keyframe(v.x, v.y, v.z, v.w); } } cv.keys = kfs; mValue = cv; children.Clear(); } return(false); } else if (type == typeof(LayerMask)) { mValue = (LayerMask)Get <int>(); } #endif else #if !STANDALONE if (!type.IsSubclassOf(typeof(Component))) #endif { bool isIList = type.Implements(typeof(System.Collections.IList)); bool isTList = (!isIList && type.Implements(typeof(TList))); mValue = (isTList || isIList) ? type.Create(children.size) : type.Create(); if (mValue == null) { Tools.LogError("Unable to create a " + type); return(true); } if (isTList) { TList list = mValue as TList; Type elemType = type.GetGenericArgument(); if (elemType != null) { for (int i = 0; i < children.size; ++i) { DataNode child = children[i]; if (child.value == null) { child.mValue = child.name; child.mResolved = false; child.ResolveValue(elemType); list.Add(child.mValue); } else if (child.name == "Add") { child.ResolveValue(elemType); list.Add(child.mValue); } else { Tools.LogError("Unexpected node in an array: " + child.name); } } return(false); } else { Tools.LogError("Unable to determine the element type of " + type); } } else if (isIList) { // This is for both List<Type> and Type[] arrays. System.Collections.IList list = mValue as System.Collections.IList; Type elemType = type.GetGenericArgument(); if (elemType == null) { elemType = type.GetElementType(); } bool fixedSize = (list.Count == children.size); if (elemType != null) { for (int i = 0; i < children.size; ++i) { DataNode child = children[i]; if (child.value == null) { child.mValue = child.name; child.mResolved = false; child.ResolveValue(elemType); if (fixedSize) { list[i] = child.mValue; } else { list.Add(child.mValue); } } else if (child.name == "Add") { child.ResolveValue(elemType); if (fixedSize) { list[i] = child.mValue; } else { list.Add(child.mValue); } } else { Tools.LogError("Unexpected node in an array: " + child.name); } } return(false); } else { Tools.LogError("Unable to determine the element type of " + type); } } else if (type.IsClass) { for (int i = 0; i < children.size; ++i) { DataNode child = children[i]; mValue.SetFieldOrPropertyValue(child.name, child.value); } return(false); } #if UNITY_EDITOR else { Debug.LogError("Unhandled type: " + type); } #else else { Tools.LogError("Unhandled type: " + type); } #endif } return(true); }
/// <summary> /// Process the string values, converting them to proper objects. /// Returns whether child nodes should be processed in turn. /// </summary> public bool ResolveValue(Type type = null) { if (mValue is string) { mResolved = true; string line = mValue as string; // Trim strings wrapped in quotes if (type == typeof(string)) { if (line == "\"\"") { mValue = ""; } else { int len = line.Length; if (len > 2 && line[0] == '"' && line[len - 1] == '"') { mValue = line.Substring(1, len - 2); } } return(true); } // Try to resolve this type as a simple type if (Serialization.ReadObject(line, out mValue, type)) { return(true); } // This type is either a class or an array if (type == null) { type = Serialization.NameToType(line); } if (type == null || type == typeof(void)) { mValue = null; return(true); } else if (type == typeof(DataNode)) { mValue = children[0]; children.Clear(); return(false); } else if (type.Implements(typeof(IDataNodeSerializable))) { var ds = (IDataNodeSerializable)type.Create(); ds.Deserialize(this); mValue = ds; return(false); } #if SERIALIZATION_WITHOUT_INTERFACE else if (type.HasDataNodeSerialization()) { mValue = type.Create(); mValue.Invoke("Deserialize", this); mValue = TypeExtensions.invokedObject; // Failing to do this will break structs. See note in the Invoke() function. return(false); } #endif #if !STANDALONE else if (type == typeof(AnimationCurve)) // NOTE: This is no longer used since AnimationCurves get serialized out as Vector4 arrays. { #if UNITY_EDITOR Debug.Log("Still used"); #endif if (children.size != 0) { var cv = new AnimationCurve(); var kfs = new Keyframe[children.size]; for (int i = 0; i < children.size; ++i) { var child = children[i]; if (child.value == null) { child.mValue = child.name; child.mResolved = false; child.ResolveValue(typeof(Vector4)); var v = (Vector4)child.mValue; kfs[i] = new Keyframe(v.x, v.y, v.z, v.w); } else { var v = (Vector4)child.mValue; kfs[i] = new Keyframe(v.x, v.y, v.z, v.w); } } cv.keys = kfs; mValue = cv; children.Clear(); } return(false); } else if (type == typeof(LayerMask)) { mValue = (LayerMask)Get <int>(); } #endif else #if !STANDALONE if (!type.IsSubclassOf(typeof(Component))) #endif { bool isIList = type.Implements(typeof(System.Collections.IList)); bool isTList = (!isIList && type.Implements(typeof(TList))); mValue = (isTList || isIList) ? type.Create(children.size) : type.Create(); if (mValue == null) { Tools.LogError("Unable to create a " + type); return(true); } if (isTList) { TList list = mValue as TList; Type elemType = type.GetGenericArgument(); if (elemType != null) { for (int i = 0; i < children.size; ++i) { var child = children[i]; if (child.value == null) { child.mValue = child.name; child.mResolved = false; child.ResolveValue(elemType); list.Add(child.mValue); } else if (child.name == "Add") { child.ResolveValue(elemType); list.Add(child.mValue); } else { Tools.LogError("Unexpected node in an array: " + child.name); } } return(false); } else { Tools.LogError("Unable to determine the element type of " + type); } } else if (isIList) { // This is for both List<Type> and Type[] arrays. System.Collections.IList list = mValue as System.Collections.IList; Type elemType = type.GetGenericArgument(); if (elemType == null) { elemType = type.GetElementType(); } bool fixedSize = (list.Count == children.size); if (elemType != null) { for (int i = 0; i < children.size; ++i) { var child = children[i]; if (child.value == null) { child.mValue = child.name; child.mResolved = false; child.ResolveValue(elemType); if (fixedSize) { list[i] = child.mValue; } else { list.Add(child.mValue); } } else if (child.name == "Add") { child.ResolveValue(elemType); if (fixedSize) { list[i] = child.mValue; } else { list.Add(child.mValue); } } else { Tools.LogError("Unexpected node in an array: " + child.name); } } return(false); } else { Tools.LogError("Unable to determine the element type of " + type); } } else { for (int i = 0; i < children.size; ++i) { var child = children[i]; mValue.SetFieldOrPropertyValue(child.name, child.value); } return(false); } } return(true); } return(true); }