/// <summary>
        /// Clones the current value of this cloner with the specified new shadow registry (optional)
        /// </summary>
        /// <param name="idRemapping">A dictionary containing the remapping of <see cref="IIdentifiable.Id"/> if <see cref="AssetClonerFlags.GenerateNewIdsForIdentifiableObjects"/> has been passed to the cloner.</param>
        /// <returns>A clone of the value associated with this cloner.</returns>
        private object Clone(out Dictionary <Guid, Guid> idRemapping)
        {
            var stream = streamOrValueType as Stream;

            if (stream != null)
            {
                stream.Position = 0;
                var reader = new BinarySerializationReader(stream);
                reader.Context.SerializerSelector = ClonerSelector;
                var refFlag = (flags & AssetClonerFlags.ReferenceAsNull) != 0
                    ? ContentSerializerContext.AttachedReferenceSerialization.AsNull
                    : ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion;
                reader.Context.Set(InvariantObjectListProperty, invariantObjects);
                reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, refFlag);
                reader.Context.Set(MemberSerializer.ObjectDeserializeCallback, OnObjectDeserialized);
                object newObject = null;
                reader.SerializeExtended(ref newObject, ArchiveMode.Deserialize);

                if ((flags & AssetClonerFlags.RemoveUnloadableObjects) != 0)
                {
                    UnloadableObjectRemover.Run(newObject);
                }

                idRemapping = cloningIdRemapping;
                return(newObject);
            }
            // Else this is a value type, so it is cloned automatically
            idRemapping = null;
            return(streamOrValueType);
        }
Exemple #2
0
        private void HandleEffectCompilerRequestedPacket(RemoteEffectCompilerEffectRequested packet, PackageViewModel package)
        {
            // Received a shader requested notification, add it to list of "pending shaders", and update count in UI

            dispatcher.InvokeAsync(() =>
            {
                CheckEffectLogAsset(package);

                // Try to decode request
                try
                {
                    // Deserialize as an object
                    var binaryReader = new BinarySerializationReader(new MemoryStream(packet.Request));
                    EffectCompileRequest effectCompileRequest = null;
                    binaryReader.Context.SerializerSelector   = SerializerSelector.AssetWithReuse;
                    binaryReader.SerializeExtended(ref effectCompileRequest, ArchiveMode.Deserialize, null);

                    // Record in list of pending effects and check if it would result in a new shader
                    // (it is still recorded in list of pending effect, in case EffectLog asset is deleted in the meantime)
                    if (pendingEffects.Add(effectCompileRequest) && !effectLogStore.Contains(effectCompileRequest))
                    {
                        UpdateImportEffectLogPendingCount(session.ImportEffectLogPendingCount + 1);
                    }
                }
                catch
                {
                    // TODO Log error
                    //Log.Warning("Received an effect compilation request which could not be decoded. Make sure Windows project compiled successfully and is up to date.");
                }
            });
        }
Exemple #3
0
        private static object DecodeObject(byte[] serializedObject)
        {
            var    reader  = new BinarySerializationReader(new MemoryStream(serializedObject));
            object command = null;

            reader.SerializeExtended(ref command, ArchiveMode.Deserialize, null);
            return(command);
        }
Exemple #4
0
        private static object DecodeObject(byte[] serializedObject)
        {
            var reader = new BinarySerializationReader(new MemoryStream(serializedObject));

            reader.Context.SerializerSelector = SerializerSelector.AssetWithReuse;
            reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion);
            object command = null;

            reader.SerializeExtended(ref command, ArchiveMode.Deserialize, null);
            return(command);
        }
Exemple #5
0
        /// <summary>
        /// Clones the specified object, taking special care of <see cref="Entity"/>, <see cref="EntityComponent"/> and external assets.
        /// User can optionally provides list of cloned objects (list of data reference objects that should be cloned)
        /// and mapped objects (list of data reference objects that should be ducplicated using the given instance).
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="clonedObjects">The cloned objects.</param>
        /// <param name="mappedObjects">The mapped objects.</param>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        private static T Clone <T>(HashSet <object> clonedObjects, TryGetValueFunction <object, object> mappedObjects, T entity) where T : class
        {
            if (cloneSerializerSelector == null)
            {
                cloneSerializerSelector = new SerializerSelector();
                cloneSerializerSelector.ReuseReferences = true;

                cloneSerializerSelector
                .RegisterProfile("Default")
                .RegisterProfile("Clone")
                .RegisterSerializer(new EntitySerializer())
                .RegisterSerializer(new CloneSerializer <string>())
                .RegisterSerializer(new CloneSerializer <Effect>())
                .RegisterSerializer(new CloneSerializer <Mesh>())
                .RegisterSerializer(new CloneSerializer <Model>())
                .RegisterSerializer(new CloneSerializer <AnimationClip>());
            }

            // Initialize CloneContext
            lock (cloneContext)
            {
                try
                {
                    cloneContext.EntitySerializerSelector = cloneSerializerSelector;

                    cloneContext.ClonedObjects = clonedObjects;
                    cloneContext.MappedObjects = mappedObjects;

                    // Serialize
                    var memoryStream = cloneContext.MemoryStream;
                    var writer       = new BinarySerializationWriter(memoryStream);
                    writer.Context.SerializerSelector = cloneSerializerSelector;
                    writer.Context.Set(CloneContextProperty, cloneContext);
                    writer.SerializeExtended(entity, ArchiveMode.Serialize, null);

                    // Deserialization reuses this list and expect it to be empty at the beginning.
                    cloneContext.SerializedObjects.Clear();

                    // Deserialize
                    T result = null;
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    var reader = new BinarySerializationReader(memoryStream);
                    reader.Context.SerializerSelector = cloneSerializerSelector;
                    reader.Context.Set(CloneContextProperty, cloneContext);
                    reader.SerializeExtended(ref result, ArchiveMode.Deserialize, null);

                    return(result);
                }
                finally
                {
                    cloneContext.Cleanup();
                }
            }
        }
Exemple #6
0
        public async Task MessageLoop()
        {
            try
            {
                while (true)
                {
                    // Get next packet size
                    var bufferSize = await context.ReadStream.ReadInt32Async();

                    // Get next packet data (until complete)
                    var buffer = new byte[bufferSize];
                    await context.ReadStream.ReadAllAsync(buffer, 0, bufferSize);

                    // Deserialize as an object
                    var    binaryReader = new BinarySerializationReader(new MemoryStream(buffer));
                    object obj          = null;
                    binaryReader.Context.SerializerSelector = SerializerSelector.AssetWithReuse;
                    binaryReader.SerializeExtended <object>(ref obj, ArchiveMode.Deserialize, null);

                    // If it's a message, process it separately (StreamId)
                    if (obj is SocketMessage)
                    {
                        var socketMessage = (SocketMessage)obj;
                        ProcessMessage(socketMessage);
                    }

                    // Check if there is a specific handler for this packet type
                    bool handlerFound;
                    Tuple <Action <object>, bool> handler;
                    lock (packetHandlers)
                    {
                        handlerFound = packetHandlers.TryGetValue(obj.GetType(), out handler);

                        // one-time handler
                        if (handlerFound && handler.Item2)
                        {
                            packetHandlers.Remove(obj.GetType());
                        }
                    }

                    if (handlerFound)
                    {
                        handler.Item1(obj);
                    }
                }
            }
            catch (Exception)
            {
                context.Dispose();
                throw;
            }
        }
Exemple #7
0
        private static object Decode(byte[] data, Serializer serializer = null)
        {
            object result = null;
            var    stream = new BinarySerializationReader(new MemoryStream(data));

            if (serializer != null)
            {
                stream.Context.Serializer = serializer;
            }
            stream.SerializeExtended(null, ref result, ArchiveMode.Deserialize);

            return(result);
        }
Exemple #8
0
        public T Deserialize <T>(byte[] bytes)
        {
            if (null == bytes || bytes.Length == 0)
            {
                return(default(T));
            }
            var reader = new BinarySerializationReader(new MemoryStream(bytes));

            reader.Context.SerializerSelector = SerializerSelector.AssetWithReuse;
            reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion);
            T command = default(T);

            reader.SerializeExtended(ref command, ArchiveMode.Deserialize, null);
            return(command);
        }
Exemple #9
0
        internal T DeepClone <T>(T obj)
        {
            // Serialize
            writer.SerializeExtended(obj, ArchiveMode.Serialize);

            // Deserialize
            obj = default(T);
            memoryStream.Seek(0, SeekOrigin.Begin);
            reader.SerializeExtended(ref obj, ArchiveMode.Deserialize);

            // Reset stream and references
            memoryStream.Seek(0, SeekOrigin.Begin);
            memoryStream.SetLength(0);

            return(obj);
        }
Exemple #10
0
        void MessageLoop()
        {
            while (true)
            {
                //var obj = formatter.Deserialize(socketStream);
                var remaining = socketBinaryReader.ReadInt32();
                var buffer    = new byte[remaining];
                int offset    = 0;
                while (remaining > 0)
                {
                    int read = socketStream.Read(buffer, offset, remaining);
                    remaining -= read;
                    offset    += read;
                }
                var    binaryReader = new BinarySerializationReader(new MemoryStream(buffer));
                object obj          = null;
                binaryReader.Context.SerializerSelector = SerializerSelector.AssetWithReuse;
                binaryReader.SerializeExtended <object>(ref obj, ArchiveMode.Deserialize, null);
                if (obj is SocketMessage)
                {
                    var socketMessage = (SocketMessage)obj;
                    ProcessMessage(socketMessage);
                }
                bool handlerFound;
                Tuple <Action <object>, bool> handler;
                lock (packetHandlers)
                {
                    handlerFound = packetHandlers.TryGetValue(obj.GetType(), out handler);

                    // one-time handler
                    if (handlerFound && handler.Item2)
                    {
                        packetHandlers.Remove(obj.GetType());
                    }
                }

                if (handlerFound)
                {
                    handler.Item1(obj);
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Clones the current value of this cloner with the specified new shadow registry (optional)
        /// </summary>
        /// <returns>A clone of the value associated with this cloner.</returns>
        private object Clone()
        {
            var stream = streamOrValueType as Stream;

            if (stream != null)
            {
                stream.Position = 0;
                var reader = new BinarySerializationReader(stream);
                reader.Context.SerializerSelector = ClonerSelector;
                var refFlag = (flags & AssetClonerFlags.ReferenceAsNull) != 0
                    ? ContentSerializerContext.AttachedReferenceSerialization.AsNull
                    : ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion;
                reader.Context.Set(InvariantObjectListProperty, invariantObjects);
                reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, refFlag);
                object newObject = null;
                reader.SerializeExtended(ref newObject, ArchiveMode.Deserialize);

                // If there are any references, we would like to copy all dynamic properties from ShadowObject to the new instances
                if (objectReferences != null)
                {
                    var newObjectReferences = reader.Context.Get(MemberSerializer.ObjectDeserializeReferences);
                    foreach (var objRef in objectReferences)
                    {
                        var innerObject    = objRef.Key;
                        var newInnerObject = newObjectReferences[objRef.Value];
                        // Copy only when objects are non-null
                        if (innerObject != null && newInnerObject != null)
                        {
                            ShadowObject.CopyDynamicProperties(innerObject, newInnerObject);
                            if ((flags & AssetClonerFlags.RemoveOverrides) != 0)
                            {
                                Override.RemoveFrom(newInnerObject);
                            }
                        }
                    }
                }

                return(newObject);
            }
            // Else this is a value type, so it is cloned automatically
            return(streamOrValueType);
        }
Exemple #12
0
        /// <summary>
        /// Clones the current value of this cloner with the specified new shadow registry (optional)
        /// </summary>
        /// <returns>A clone of the value associated with this cloner.</returns>
        public object Clone()
        {
            var stream = streamOrValueType as Stream;

            if (stream != null)
            {
                stream.Position = 0;
                var reader = new BinarySerializationReader(stream);
                reader.Context.SerializerSelector = ClonerSelector;
                var refFlag = referencesAsNull ? ContentSerializerContext.AttachedReferenceSerialization.AsNull
                                           : ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion;
                reader.Context.Set(InvariantObjectListProperty, invariantObjects);
                reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, refFlag);
                object newObject = null;
                reader.SerializeExtended(ref newObject, ArchiveMode.Deserialize);
                return(newObject);
            }
            // Else this is a value type, so it is cloned automatically
            return(streamOrValueType);
        }
Exemple #13
0
        public object Deserialize(byte[] bytes, string typeConfigName)
        {
            if (null == typeConfigName)
            {
                throw new ArgumentNullException(nameof(typeConfigName));
            }
            var type = typeConfigName.ToType();

            if (null == typeConfigName || null == bytes || bytes.Length == 0)
            {
                return(type.GetDefault());
            }
            var reader = new BinarySerializationReader(new MemoryStream(bytes));

            reader.Context.SerializerSelector = SerializerSelector.AssetWithReuse;
            reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion);
            object command = null;

            reader.SerializeExtended(ref command, ArchiveMode.Deserialize, null);
            return(command);
        }
Exemple #14
0
        private static T Clone <T>(HashSet <object> clonedObjects, T entity) where T : class
        {
            if (cloneSerializerSelector == null)
            {
                cloneSerializerSelector = new SerializerSelector(true, "Default", "Clone");
            }
            // Initialize CloneContext
            lock (CloneContext)
            {
                try
                {
                    CloneContext.EntitySerializerSelector = cloneSerializerSelector;
                    CloneContext.ClonedObjects            = clonedObjects;

                    // Serialize
                    var memoryStream = CloneContext.MemoryStream;
                    var writer       = new BinarySerializationWriter(memoryStream);
                    writer.Context.SerializerSelector = cloneSerializerSelector;
                    writer.Context.Set(EntityCloner.CloneContextProperty, CloneContext);
                    writer.SerializeExtended(entity, ArchiveMode.Serialize);

                    // Deserialization reuses this list and expect it to be empty at the beginning.
                    CloneContext.SerializedObjects.Clear();

                    // Deserialize
                    T result = null;
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    var reader = new BinarySerializationReader(memoryStream);
                    reader.Context.SerializerSelector = cloneSerializerSelector;
                    reader.Context.Set(EntityCloner.CloneContextProperty, CloneContext);
                    reader.SerializeExtended(ref result, ArchiveMode.Deserialize);

                    return(result);
                }
                finally
                {
                    CloneContext.Cleanup();
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Clones the current value of this cloner with the specified new shadow registry (optional)
        /// </summary>
        /// <param name="idRemapping">A dictionary containing the remapping of <see cref="IIdentifiable.Id"/> if <see cref="AssetClonerFlags.GenerateNewIdsForIdentifiableObjects"/> has been passed to the cloner.</param>
        /// <returns>A clone of the value associated with this cloner.</returns>
        private object Clone([NotNull] out Dictionary <Guid, Guid> idRemapping)
        {
            if (streamOrValueType is Stream stream)
            {
                stream.Position = 0;
                var reader = new BinarySerializationReader(stream);
                reader.Context.SerializerSelector = ClonerSelector;
                reader.Context.Set(InvariantObjectListProperty, invariantObjects);
                reader.Context.Set(ContentSerializerContext.SerializeAttachedReferenceProperty, GenerateContentSerializerFlags(flags));
                if (externalIdentifiables != null)
                {
                    if ((flags & AssetClonerFlags.ClearExternalReferences) != 0)
                    {
                        externalIdentifiables.Clear();
                    }

                    reader.Context.Set(MemberSerializer.ExternalIdentifiables, externalIdentifiables);
                }
                if ((flags & AssetClonerFlags.KeepReferences) != 0)
                {
                    reader.Context.Set(ReferenceSerializer.CloneReferences, cloneReferences);
                }
                reader.Context.Set(MemberSerializer.ObjectDeserializeCallback, OnObjectDeserialized);
                object newObject = null;
                reader.SerializeExtended(ref newObject, ArchiveMode.Deserialize);

                if ((flags & AssetClonerFlags.RemoveUnloadableObjects) != 0)
                {
                    UnloadableObjectRemover.Run(newObject);
                }

                idRemapping = cloningIdRemapping;
                return(newObject);
            }
            // Else this is a value type, so it is cloned automatically
            idRemapping = new Dictionary <Guid, Guid>();
            return(streamOrValueType);
        }
Exemple #16
0
        private static object Decode(byte[] data, Serializer serializer = null)
        {
            object result = null;
            var stream = new BinarySerializationReader(new MemoryStream(data));
            if (serializer != null)
                stream.Context.Serializer = serializer;
            stream.SerializeExtended(null, ref result, ArchiveMode.Deserialize);

            return result;
        }
Exemple #17
0
        public void Test()
        {
            var prefab = new PrefabAsset();

            var modelComponent = new ModelComponent();
            var entity         = new Entity()
            {
                modelComponent
            };

            prefab.Hierarchy.Parts.Add(new EntityDesign(entity));
            prefab.Hierarchy.RootPartIds.Add(entity.Id);

            var material1 = new MaterialNull();

            IdentifiableHelper.SetId(material1, new Guid("39E2B226-8752-4678-8E93-76FFBFBA337B"));
            var material2 = new MaterialNull();

            IdentifiableHelper.SetId(material2, new Guid("CC4F1B31-FBB7-4360-A3E7-060BDFDA0695"));
            modelComponent.Materials.Add(material1);
            modelComponent.Materials.Add(material2);

            Action <PrefabAsset> checkPrefab = (newPrefab) =>
            {
                var previousEntityDesign = newPrefab.Hierarchy.Parts.FirstOrDefault();

                Assert.NotNull(previousEntityDesign);

                var previousEntity = previousEntityDesign.Entity;


                var component = previousEntity.Get <ModelComponent>();
                Assert.NotNull(component);

                Assert.AreEqual(2, component.Materials.Count);

                var newMaterial1 = component.Materials[0];
                Assert.AreEqual(IdentifiableHelper.GetId(material1), IdentifiableHelper.GetId(newMaterial1));
                var newMaterial2 = component.Materials[1];
                Assert.AreEqual(IdentifiableHelper.GetId(material2), IdentifiableHelper.GetId(newMaterial2));
            };

            // Test yaml serialization
            {
                using (var stream = new MemoryStream())
                {
                    AssetSerializer.Save(stream, prefab);

                    stream.Position = 0;
                    var serializedVersion = Encoding.UTF8.GetString(stream.ToArray());
                    Console.WriteLine(serializedVersion);

                    stream.Position = 0;
                    var newPrefab = (PrefabAsset)AssetSerializer.Load(stream, "myentity");
                    checkPrefab(newPrefab);
                }
            }

            // Test cloning
            var newPrefabClone = (PrefabAsset)AssetCloner.Clone(prefab);

            checkPrefab(newPrefabClone);

            // Test runtime serialization (runtime serialization is removing MaterialNull and replacing it by a null)
            {
                var stream = new MemoryStream();
                var writer = new BinarySerializationWriter(stream)
                {
                    Context = { SerializerSelector = SerializerSelector.AssetWithReuse }
                };
                writer.SerializeExtended(entity, ArchiveMode.Serialize);
                writer.Flush();
                stream.Position = 0;

                var reader = new BinarySerializationReader(stream)
                {
                    Context = { SerializerSelector = SerializerSelector.AssetWithReuse }
                };

                Entity newEntity = null;
                reader.SerializeExtended(ref newEntity, ArchiveMode.Deserialize);

                Assert.NotNull(newEntity);

                var component = newEntity.Get <ModelComponent>();
                Assert.NotNull(component);

                Assert.AreEqual(2, component.Materials.Count);

                Assert.Null(component.Materials[0]);
                Assert.Null(component.Materials[1]);
            }
        }
Exemple #18
0
        public async Task MessageLoop()
        {
            try
            {
                while (true)
                {
                    // Get next packet size
                    var bufferSize = await context.ReadStream.ReadInt32Async();

                    // Get next packet data (until complete)
                    var buffer = new byte[bufferSize];
                    await context.ReadStream.ReadAllAsync(buffer, 0, bufferSize);

                    // Deserialize as an object
                    var    binaryReader = new BinarySerializationReader(new MemoryStream(buffer));
                    object obj          = null;
                    binaryReader.Context.SerializerSelector = SerializerSelector.AssetWithReuse;
                    binaryReader.SerializeExtended <object>(ref obj, ArchiveMode.Deserialize, null);

                    // If it's a message, process it separately (StreamId)
                    var message = obj as SocketMessage;
                    if (message != null)
                    {
                        var socketMessage = message;
                        ProcessMessage(socketMessage);
                    }

                    // Check if there is a specific handler for this packet type
                    bool handlerFound;
                    Tuple <Func <object, Task>, bool> handler;
                    lock (packetHandlers)
                    {
                        handlerFound = packetHandlers.TryGetValue(obj.GetType(), out handler);

                        // one-time handler
                        if (handlerFound && handler.Item2)
                        {
                            packetHandlers.Remove(obj.GetType());
                        }
                    }

                    if (handlerFound)
                    {
                        try
                        {
                            await handler.Item1(obj);
                        }
                        catch (Exception ex)
                        {
                            if (message != null && message.StreamId != 0)
                            {
                                var exceptionMessage = new ExceptionMessage
                                {
                                    ExceptionInfo = new ExceptionInfo(ex),
                                    StreamId      = message.StreamId,
                                };

                                await Send(exceptionMessage);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                context.Dispose();

                lock (packetCompletionTasks)
                {
                    // Cancel all pending packets
                    foreach (var packetCompletionTask in packetCompletionTasks)
                    {
                        packetCompletionTask.Value.TrySetException(e);
                    }
                    packetCompletionTasks.Clear();
                }

                throw;
            }
        }