コード例 #1
0
 /// <inheritdoc/>
 public override void Serialize(ref SiliconStudio.Core.Collections.SortedList <TKey, TValue> obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Deserialize)
     {
         // Should be null if it was
         int count = stream.ReadInt32();
         for (int i = 0; i < count; ++i)
         {
             TKey   key   = default(TKey);
             TValue value = default(TValue);
             keySerializer.Serialize(ref key, mode, stream);
             valueSerializer.Serialize(ref value, mode, stream);
             obj.Add(key, value);
         }
     }
     else if (mode == ArchiveMode.Serialize)
     {
         stream.Write(obj.Count);
         foreach (var item in obj)
         {
             keySerializer.Serialize(item.Key, stream);
             valueSerializer.Serialize(item.Value, stream);
         }
     }
 }
コード例 #2
0
 /// <inheritdoc/>
 public override void Serialize(ref IDictionary <TKey, TValue> obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Deserialize)
     {
         // Should be null if it was
         var count = stream.ReadInt32();
         for (var i = 0; i < count; ++i)
         {
             var key   = default(TKey);
             var value = default(TValue);
             keySerializer.Serialize(ref key, mode, stream);
             valueSerializer.Serialize(ref value, mode, stream);
             obj.Add(key, value);
         }
     }
     else if (mode == ArchiveMode.Serialize)
     {
         stream.Write(obj.Count);
         foreach (var item in obj)
         {
             keySerializer.Serialize(item.Key, stream);
             valueSerializer.Serialize(item.Value, stream);
         }
     }
 }
コード例 #3
0
        public void Serialize(SerializationStream stream, ArchiveMode mode)
        {
            // Check version number (should be 0 for now, for future use)
            if (mode == ArchiveMode.Serialize)
            {
                stream.Write(0);
            }
            else if (mode == ArchiveMode.Deserialize)
            {
                if (stream.ReadInt32() != 0)
                {
                    throw new InvalidOperationException("Unexpected version number.");
                }
            }

            // Serialize content
            stream.Serialize(ref IsBinary);
            if (IsBinary)
            {
                stream.Serialize(ref BinaryFormat);
                stream.Serialize(ref Binary, mode);
            }
            else
            {
                stream.Serialize(ref Profile);
                stream.Serialize(ref EntryPoint);
                stream.Serialize(ref Source);
            }
        }
コード例 #4
0
        public override void Serialize(ref ContentReference <T> reference, ArchiveMode mode, SerializationStream stream)
        {
            var contentSerializerContext = stream.Context.Get(ContentSerializerContext.ContentSerializerContextProperty);

            if (contentSerializerContext != null)
            {
                if (mode == ArchiveMode.Serialize)
                {
                    int index = contentSerializerContext.AddContentReference(reference);
                    stream.Write(index);
                }
                else
                {
                    int index = stream.ReadInt32();
                    reference = contentSerializerContext.GetContentReference <T>(index);
                }
            }
            else
            {
                // This case will happen when serializing build engine command hashes: we still want Location to still be written
                if (mode == ArchiveMode.Serialize)
                {
                    {
                        // This case will happen when serializing build engine command hashes: we still want Location to still be written
                        stream.Write(reference.Location);
                    }
                }
                else
                {
                    // No real case yet
                    throw new NotSupportedException();
                }
            }
        }
コード例 #5
0
 public override void Serialize(ref VertexDeclaration obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Deserialize)
     {
         var elements      = stream.Read <VertexElement[]>();
         var instanceCount = stream.ReadInt32();
         var vertexStride  = stream.ReadInt32();
         obj = new VertexDeclaration(elements, instanceCount, vertexStride);
     }
     else
     {
         stream.Write(obj.VertexElements);
         stream.Write(obj.InstanceCount);
         stream.Write(obj.VertexStride);
     }
 }
コード例 #6
0
        public override void Serialize(ref Sound obj, ArchiveMode mode, SerializationStream stream)
        {
            if (mode == ArchiveMode.Deserialize)
            {
                var services    = stream.Context.Tags.Get(ServiceRegistry.ServiceRegistryKey);
                var audioEngine = services.GetServiceAs <IAudioEngineProvider>()?.AudioEngine;

                obj.CompressedDataUrl = stream.ReadString();
                obj.SampleRate        = stream.ReadInt32();
                obj.Channels          = stream.ReadByte();
                obj.StreamFromDisk    = stream.ReadBoolean();
                obj.Spatialized       = stream.ReadBoolean();
                obj.NumberOfPackets   = stream.ReadInt16();
                obj.MaxPacketLength   = stream.ReadInt16();

                if (!obj.StreamFromDisk && audioEngine != null && audioEngine.State != AudioEngineState.Invalidated && audioEngine.State != AudioEngineState.Disposed) //immediatelly preload all the data and decode
                {
                    using (var soundStream = ContentManager.FileProvider.OpenStream(obj.CompressedDataUrl, VirtualFileMode.Open, VirtualFileAccess.Read, VirtualFileShare.Read, StreamFlags.Seekable))
                        using (var decoder = new Celt(obj.SampleRate, CompressedSoundSource.SamplesPerFrame, obj.Channels, true))
                        {
                            var reader           = new BinarySerializationReader(soundStream);
                            var samplesPerPacket = CompressedSoundSource.SamplesPerFrame * obj.Channels;

                            obj.PreloadedBuffer = AudioLayer.BufferCreate(samplesPerPacket * obj.NumberOfPackets * sizeof(short));

                            var memory = new UnmanagedArray <short>(samplesPerPacket * obj.NumberOfPackets);

                            var offset       = 0;
                            var outputBuffer = new short[samplesPerPacket];
                            for (var i = 0; i < obj.NumberOfPackets; i++)
                            {
                                var len = reader.ReadInt16();
                                var compressedBuffer = reader.ReadBytes(len);
                                var samplesDecoded   = decoder.Decode(compressedBuffer, len, outputBuffer);
                                memory.Write(outputBuffer, offset, 0, samplesDecoded * obj.Channels);
                                offset += samplesDecoded * obj.Channels * sizeof(short);
                            }

                            AudioLayer.BufferFill(obj.PreloadedBuffer, memory.Pointer, memory.Length * sizeof(short), obj.SampleRate, obj.Channels == 1);
                            memory.Dispose();
                        }
                }

                if (audioEngine != null)
                {
                    obj.Attach(audioEngine);
                }
            }
            else
            {
                stream.Write(obj.CompressedDataUrl);
                stream.Write(obj.SampleRate);
                stream.Write((byte)obj.Channels);
                stream.Write(obj.StreamFromDisk);
                stream.Write(obj.Spatialized);
                stream.Write((short)obj.NumberOfPackets);
                stream.Write((short)obj.MaxPacketLength);
            }
        }
コード例 #7
0
 public override void Serialize(ref VertexElement obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Deserialize)
     {
         obj.semanticName      = stream.ReadString();
         obj.semanticIndex     = stream.ReadInt32();
         obj.format            = stream.Read <PixelFormat>();
         obj.alignedByteOffset = stream.ReadInt32();
         obj.ComputeHashCode();
     }
     else
     {
         stream.Write(obj.semanticName);
         stream.Write(obj.semanticIndex);
         stream.Write(obj.format);
         stream.Write(obj.alignedByteOffset);
     }
 }
コード例 #8
0
            public override void Serialize(ref ParameterCollectionData obj, ArchiveMode mode, SerializationStream stream)
            {
                if (mode == ArchiveMode.Deserialize)
                {
                    // Should be null if it was
                    int count = stream.ReadInt32();
                    for (int i = 0; i < count; ++i)
                    {
                        ParameterKey key          = null;
                        object       value        = null;
                        bool         matchingType = false;

                        stream.SerializeExtended(ref key, mode);
                        stream.Serialize(ref matchingType);

                        var valueType = matchingType ? key.PropertyType : typeof(object);
                        if (reuseReferences)
                        {
                            MemberReuseSerializer.SerializeExtended(stream, valueType, ref value, mode);
                        }
                        else
                        {
                            MemberNonSealedSerializer.SerializeExtended(stream, valueType, ref value, mode);
                        }

                        obj.Add(key, value);
                    }
                }
                else if (mode == ArchiveMode.Serialize)
                {
                    stream.Write(obj.Count);
                    foreach (var item in obj)
                    {
                        var key = item.Key;

                        // When serializing convert the value type to the expecting type
                        // This should probably better done at the source (when creating/filling the ParameterCollectionData)
                        var value = item.Key.ConvertValue(item.Value);

                        stream.SerializeExtended(ref key, mode);
                        bool matchingType = value.GetType().GetTypeInfo().IsAssignableFrom(key.PropertyType.GetTypeInfo());
                        stream.Serialize(ref matchingType);

                        var valueType = matchingType ? key.PropertyType : typeof(object);

                        if (reuseReferences)
                        {
                            MemberReuseSerializer.SerializeExtended(stream, valueType, ref value, mode);
                        }
                        else
                        {
                            MemberNonSealedSerializer.SerializeExtended(stream, valueType, ref value, mode);
                        }
                    }
                }
            }
コード例 #9
0
            public override void Serialize(ref IndexBufferBinding indexBufferBinding, ArchiveMode mode, SerializationStream stream)
            {
                if (mode == ArchiveMode.Deserialize)
                {
                    var buffer  = stream.Read <Buffer>();
                    var is32Bit = stream.ReadBoolean();
                    var count   = stream.ReadInt32();
                    var offset  = stream.ReadInt32();

                    indexBufferBinding = new IndexBufferBinding(buffer, is32Bit, count, offset);
                }
                else
                {
                    stream.Write(indexBufferBinding.Buffer);
                    stream.Write(indexBufferBinding.Is32Bit);
                    stream.Write(indexBufferBinding.Count);
                    stream.Write(indexBufferBinding.Offset);
                }
            }
コード例 #10
0
 public override void Serialize(ref ServiceSyncInfo info, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Serialize)
     {
         stream.Write(info.CompressionThreshold);
         stream.Write(info.ServiceKeyIndex);
         stream.Write(info.UseCompression);
         stream.Write(info.MethodInfos.Length);
         foreach (var method in info.MethodInfos)
         {
             stream.Write(method.MethodIdent);
             stream.Write(method.MethodName);
             stream.Write(method.MethodReturnType);
             stream.Write(method.ParameterTypes.Length);
             foreach (var paramType in method.ParameterTypes)
             {
                 stream.Write(paramType);
             }
         }
     }
     else if (mode == ArchiveMode.Deserialize)
     {
         info.CompressionThreshold = stream.ReadInt32();
         info.ServiceKeyIndex      = stream.ReadInt32();
         info.UseCompression       = stream.ReadBoolean();
         var length = stream.ReadInt32();
         info.MethodInfos = new MethodSyncInfo[length];
         for (int i = 0; i < length; i++)
         {
             info.MethodInfos[i]                  = new MethodSyncInfo();
             info.MethodInfos[i].MethodIdent      = stream.ReadInt32();
             info.MethodInfos[i].MethodName       = stream.ReadString();
             info.MethodInfos[i].MethodReturnType = stream.ReadString();
             var paramLength = stream.ReadInt32();
             info.MethodInfos[i].ParameterTypes = new string[paramLength];
             for (int j = 0; j < paramLength; j++)
             {
                 info.MethodInfos[i].ParameterTypes[j] = stream.ReadString();
             }
         }
     }
 }
コード例 #11
0
 public override void Serialize(ref CompressedTimeSpan timeSpan, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Serialize)
     {
         stream.Write(timeSpan.Ticks);
     }
     else if (mode == ArchiveMode.Deserialize)
     {
         timeSpan = new CompressedTimeSpan(stream.ReadInt32());
     }
 }
コード例 #12
0
ファイル: ChunkHeader.cs プロジェクト: h78hy78yhoi8j/xenko
        public static ChunkHeader Read(SerializationStream stream)
        {
            int magic = stream.ReadInt32();
            if (magic != Magic)
            {
                // Rewind
                stream.NativeStream.Seek(-4, SeekOrigin.Current);
                return null;
            }

            int version = stream.ReadInt32();
            var header = new ChunkHeader(version);
            if (version == 1)
            {
                header.Type = stream.ReadString();
                header.OffsetToObject = stream.ReadInt32();
                header.OffsetToReferences = stream.ReadInt32();
            }
            return header;
        }
コード例 #13
0
 /// <inheritdoc/>
 public override void PreSerialize(ref T[] obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Serialize)
     {
         stream.Write(obj.Length);
     }
     else if (mode == ArchiveMode.Deserialize)
     {
         var length = stream.ReadInt32();
         obj = new T[length];
     }
 }
コード例 #14
0
            public override void Serialize(ref VertexBufferBinding vertexBufferBinding, ArchiveMode mode, SerializationStream stream)
            {
                if (mode == ArchiveMode.Deserialize)
                {
                    var buffer      = stream.Read <Buffer>();
                    var declaration = stream.Read <VertexDeclaration>();
                    var count       = stream.ReadInt32();
                    var stride      = stream.ReadInt32();
                    var offset      = stream.ReadInt32();

                    vertexBufferBinding = new VertexBufferBinding(buffer, declaration, count, stride, offset);
                }
                else
                {
                    stream.Write(vertexBufferBinding.Buffer);
                    stream.Write(vertexBufferBinding.Declaration);
                    stream.Write(vertexBufferBinding.Count);
                    stream.Write(vertexBufferBinding.Stride);
                    stream.Write(vertexBufferBinding.Offset);
                }
            }
コード例 #15
0
 public override void PreSerialize(ref AnimationKeyValuePair <T>[] obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Serialize)
     {
         stream.Write(obj.Length);
     }
     else if (mode == ArchiveMode.Deserialize)
     {
         int length = stream.ReadInt32();
         obj = new AnimationKeyValuePair <T> [length];
     }
 }
コード例 #16
0
ファイル: CloneSerializer.cs プロジェクト: yongweisun/paradox
        public override void PreSerialize(ref T obj, ArchiveMode mode, SerializationStream stream)
        {
            var cloneContext = stream.Context.Get(EntityCloner.CloneContextProperty);

            if (mode == ArchiveMode.Serialize)
            {
                // Check against list of items that should be included in the stream (Entity and EntityComponent whose parent is the cloned Entity).
                // First try MappedObjects, then ClonedObjects.
                object mappedObject   = null;
                bool   isSharedObject = cloneContext.MappedObjects != null && cloneContext.MappedObjects(obj, out mappedObject);

                if (!isSharedObject && cloneContext.ClonedObjects != null && !cloneContext.ClonedObjects.Contains(obj))
                {
                    isSharedObject = true;
                    mappedObject   = obj;
                }

                stream.Write(isSharedObject);

                if (isSharedObject)
                {
                    stream.Write(cloneContext.SharedObjects.Count);
                    cloneContext.SharedObjects.Add(mappedObject);
                }
                else
                {
                    cloneContext.SerializedObjects.Add(obj);
                }
            }
            else
            {
                bool isSharedObject = stream.ReadBoolean();

                if (isSharedObject)
                {
                    var sharedObjectIndex = stream.ReadInt32();
                    obj = (T)cloneContext.SharedObjects[sharedObjectIndex];

                    // TODO: Hardcoded
                    // Model need to be cloned
                    if (obj is Model)
                    {
                        obj = (T)(object)((Model)(object)obj).Instantiate();
                    }
                }
                else
                {
                    base.PreSerialize(ref obj, mode, stream);
                    cloneContext.SerializedObjects.Add(obj);
                }
            }
        }
コード例 #17
0
ファイル: ChunkHeader.cs プロジェクト: Ethereal77/stride
        public static ChunkHeader Read(SerializationStream stream)
        {
            int magic = stream.ReadInt32();

            if (magic != Magic)
            {
                // Rewind
                stream.NativeStream.Seek(-4, SeekOrigin.Current);
                return(null);
            }

            int version = stream.ReadInt32();
            var header  = new ChunkHeader(version);

            if (version == 1)
            {
                header.Type               = stream.ReadString();
                header.OffsetToObject     = stream.ReadInt32();
                header.OffsetToReferences = stream.ReadInt32();
            }
            return(header);
        }
コード例 #18
0
        public override void Serialize(ref Sound obj, ArchiveMode mode, SerializationStream stream)
        {
            if (mode == ArchiveMode.Deserialize)
            {
                var services    = stream.Context.Tags.Get(ServiceRegistry.ServiceRegistryKey);
                var audioEngine = services.GetService <IAudioEngineProvider>()?.AudioEngine;

                obj.FileProvider      = services.GetService <IDatabaseFileProviderService>()?.FileProvider;
                obj.CompressedDataUrl = stream.ReadString();
                obj.SampleRate        = stream.ReadInt32();
                obj.Channels          = stream.ReadByte();
                obj.StreamFromDisk    = stream.ReadBoolean();
                obj.Spatialized       = stream.ReadBoolean();
                obj.NumberOfPackets   = stream.ReadInt32();
                obj.MaxPacketLength   = stream.ReadInt16();
                obj.Samples           = stream.ReadInt32();

                if (!obj.StreamFromDisk && audioEngine != null && audioEngine.State != AudioEngineState.Invalidated && audioEngine.State != AudioEngineState.Disposed) //immediatelly preload all the data and decode
                {
                    obj.LoadSoundInMemory();
                }

                if (audioEngine != null)
                {
                    obj.Attach(audioEngine);
                }
            }
            else
            {
                stream.Write(obj.CompressedDataUrl);
                stream.Write(obj.SampleRate);
                stream.Write((byte)obj.Channels);
                stream.Write(obj.StreamFromDisk);
                stream.Write(obj.Spatialized);
                stream.Write(obj.NumberOfPackets);
                stream.Write((short)obj.MaxPacketLength);
                stream.Write(obj.Samples);
            }
        }
コード例 #19
0
        /// <summary>
        /// Reads header instance from a stream.
        /// </summary>
        /// <param name="stream">The source stream.</param>
        /// <param name="result">Result data</param>
        public static void Read(SerializationStream stream, out ContentStorageHeader result)
        {
            result = new ContentStorageHeader();
            var version = stream.ReadInt32();

            if (version == 1)
            {
                result.DataUrl     = stream.ReadString();
                result.PackageTime = new DateTime(stream.ReadInt64());
                int chunksCount = stream.ReadInt32();
                result.Chunks = new ChunkEntry[chunksCount];
                for (int i = 0; i < chunksCount; i++)
                {
                    result.Chunks[i].Location = stream.ReadInt32();
                    result.Chunks[i].Size     = stream.ReadInt32();
                }
                result.HashCode = stream.ReadInt32();

                return;
            }

            throw new SerializationException($"Invald {nameof(ContentStorageHeader)} version.");
        }
コード例 #20
0
        public override void Serialize(ref ContentReference <T> contentReference, ArchiveMode mode, SerializationStream stream)
        {
            var cloneContext = stream.Context.Get(EntityCloner.CloneContextProperty);

            if (mode == ArchiveMode.Serialize)
            {
                stream.Write(cloneContext.ContentReferences.Count);
                cloneContext.ContentReferences.Add(contentReference);
            }
            else
            {
                int index = stream.ReadInt32();
                contentReference = (ContentReference <T>)cloneContext.ContentReferences[index];
            }
        }
コード例 #21
0
 /// <inheritdoc/>
 public override void Serialize(ref Enum obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Serialize)
     {
         stream.Write(obj != null ? obj.GetType().AssemblyQualifiedName : string.Empty);
         stream.Write(Convert.ToInt32(obj));
     }
     else if (mode == ArchiveMode.Deserialize)
     {
         var type  = AssemblyRegistry.GetType(stream.ReadString());
         var value = stream.ReadInt32();
         if (type != null)
         {
             obj = (Enum)Enum.ToObject(type, value);
         }
     }
 }
コード例 #22
0
ファイル: HashSetSerializer.cs プロジェクト: yinovation/xenko
 /// <inheritdoc/>
 public override void Serialize(ref HashSet <T> obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Deserialize)
     {
         int count = stream.ReadInt32();
         for (int i = 0; i < count; ++i)
         {
             T value = default(T);
             itemDataSerializer.Serialize(ref value, mode, stream);
             obj.Add(value);
         }
     }
     else if (mode == ArchiveMode.Serialize)
     {
         stream.Write(obj.Count);
         foreach (T item in obj)
         {
             itemDataSerializer.Serialize(item, stream);
         }
     }
 }
コード例 #23
0
 /// <inheritdoc/>
 public override void Serialize(ref TKeyedList obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Deserialize)
     {
         // TODO: We could probably avoid using TrackingKeyedList.Add, and directly fill the items list (since items are supposed to be sorted already).
         var count = stream.ReadInt32();
         for (var i = 0; i < count; ++i)
         {
             var value = default(T);
             itemDataSerializer.Serialize(ref value, mode, stream);
             obj.Add(value);
         }
     }
     else if (mode == ArchiveMode.Serialize)
     {
         stream.Write(obj.Count);
         foreach (var item in obj)
         {
             itemDataSerializer.Serialize(item, stream);
         }
     }
 }
コード例 #24
0
 /// <inheritdoc/>
 public override void Serialize(ref ComputeColorParameters obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Deserialize)
     {
         // Should be null if it was
         int count = stream.ReadInt32();
         for (int i = 0; i < count; ++i)
         {
             var value = new KeyValuePair <string, IComputeColorParameter>();
             itemDataSerializer.Serialize(ref value, mode, stream);
             obj.Add(value.Key, value.Value);
         }
     }
     else if (mode == ArchiveMode.Serialize)
     {
         stream.Write(obj.Count);
         foreach (var item in obj.internalDictionary)
         {
             itemDataSerializer.Serialize(item, stream);
         }
     }
 }
コード例 #25
0
        public override void Serialize(ref ParameterKey <T> obj, ArchiveMode mode, SerializationStream stream)
        {
            if (mode == ArchiveMode.Serialize)
            {
                stream.Write(obj.Name);
                stream.Write(obj.Length);
            }
            else
            {
                var parameterName   = stream.ReadString();
                var parameterLength = stream.ReadInt32();
                obj = (ParameterKey <T>)ParameterKeys.FindByName(parameterName);

                // If parameter could not be found, create one matching this type.
                if (obj == null)
                {
                    var metadata = new ParameterKeyValueMetadata <T>();
                    obj = new ParameterKey <T>(parameterName, parameterLength, metadata);
                    ParameterKeys.Merge(obj, null, parameterName);
                }
            }
        }
コード例 #26
0
 /// <inheritdoc/>
 public override void Serialize(ref AssetPartCollection <TAssetPartDesign, TAssetPart> obj, ArchiveMode mode, SerializationStream stream)
 {
     if (mode == ArchiveMode.Deserialize)
     {
         // Should be null if it was
         var count = stream.ReadInt32();
         for (var i = 0; i < count; ++i)
         {
             var value = default(TAssetPartDesign);
             valueSerializer.Serialize(ref value, mode, stream);
             var key = value.Part.Id;
             obj.Add(key, value);
         }
     }
     else if (mode == ArchiveMode.Serialize)
     {
         stream.Write(obj.Count);
         foreach (var item in obj)
         {
             valueSerializer.Serialize(item.Value, stream);
         }
     }
 }
コード例 #27
0
        public override void Serialize(ref SongLibrary obj, ArchiveMode mode, [NotNull] SerializationStream stream)
        {
            if (mode == ArchiveMode.Deserialize)
            {
                var services      = stream.Context.Tags.Get(ServiceRegistry.ServiceRegistryKey);
                var contentManger = services.GetService <IContentManager>();

                // load songs
                {
                    int idCount = stream.ReadInt32();
                    obj.songs = new Dictionary <Guid, Song>(idCount);

                    for (int i = 0; i < idCount; i++)
                    {
                        Guid id = new Guid();
                        guidSerializer.Serialize(ref id, mode, stream);

                        var songUrl = FormattableString.Invariant($"Songs/{id}");
                        var song    = contentManger.Get <Song>(songUrl) ?? contentManger.Load <Song>(songUrl);

                        if (song == null)
                        {
                            this.LogWarning("Song with id '{songId}' has not been found. Skipping.", id);
                            continue;
                        }

                        obj.songs.Add(id, song);
                    }
                }

                // load attempts
                {
                    int attemptCount = stream.ReadInt32();
                    obj.Attempts = new List <SongAttempt>(attemptCount);

                    for (int i = 0; i < attemptCount; i++)
                    {
                        var attempt = new SongAttempt();

                        Guid songId = new Guid();
                        guidSerializer.Serialize(ref songId, mode, stream);

                        if (!obj.songs.TryGetValue(songId, out Song song))
                        {
                            this.LogWarning("Song with id '{songId}' hasn't been loaded in the library. Removing entry from history.", songId);
                            song = null;
                        }

                        attempt.Song = song;

                        dateSerializer.Serialize(ref attempt.AttemptTime, mode, stream);
                        timeSerializer.Serialize(ref attempt.AttemptLength, mode, stream);
                        attempt.Score         = stream.ReadInt64();
                        attempt.ZombiesKilled = stream.ReadInt32();
                        attempt.Failed        = stream.ReadBoolean();

                        if (attempt.Song != null)
                        {
                            obj.Attempts.Add(attempt);
                        }
                    }
                }
            }
            else // serialize
            {
                var ids = obj.songs.Keys;
                // serialize the collection of songs - we just store their ids here, as each song has a URL
                {
                    stream.Write(ids.Count);
                    foreach (Guid id in ids)
                    {
                        guidSerializer.Serialize(id, stream);
                    }
                }

                // serialize attempts
                {
                    stream.Write(obj.Attempts.Count);
                    foreach (var attempt in obj.Attempts)
                    {
                        guidSerializer.Serialize(obj.songs.First(kvp => kvp.Value == attempt.Song).Key, stream);
                        dateSerializer.Serialize(attempt.AttemptTime, stream);
                        timeSerializer.Serialize(attempt.AttemptLength, stream);
                        stream.Write(attempt.Score);
                        stream.Write(attempt.ZombiesKilled);
                        stream.Write(attempt.Failed);
                    }
                }
            }
        }
コード例 #28
0
        public override void Serialize(ref T obj, ArchiveMode mode, SerializationStream stream)
        {
            var referenceSerialization   = stream.Context.Get(ContentSerializerContext.SerializeAttachedReferenceProperty);
            var contentSerializerContext = stream.Context.Get(ContentSerializerContext.ContentSerializerContextProperty);

            if (contentSerializerContext != null)
            {
                if (mode == ArchiveMode.Serialize)
                {
                    var contentReference = new ContentReference <T>(obj);
                    int index            = contentSerializerContext.AddContentReference(contentReference);
                    stream.Write(index);
                }
                else
                {
                    int index            = stream.ReadInt32();
                    var contentReference = contentSerializerContext.GetContentReference <T>(index);
                    obj = contentReference.Value;
                    if (obj == null)
                    {
                        // Check if already deserialized
                        var assetReference = contentSerializerContext.ContentManager.FindDeserializedObject(contentReference.Location, typeof(T));
                        if (assetReference != null)
                        {
                            obj = (T)assetReference.Object;
                            if (obj != null)
                            {
                                contentReference.Value = obj;
                            }
                        }
                    }

                    if (obj == null && contentSerializerContext.LoadContentReferences)
                    {
                        var contentSerializer = cachedContentSerializer ?? (cachedContentSerializer = contentSerializerContext.ContentManager.Serializer.GetSerializer(null, typeof(T)));
                        if (contentSerializer == null)
                        {
                            // Need to read chunk header to know actual type (note that we can't cache it in cachedContentSerializer as it depends on content)
                            var chunkHeader = contentSerializerContext.ContentManager.ReadChunkHeader(contentReference.Location);
                            if (chunkHeader == null || (contentSerializer = contentSerializerContext.ContentManager.Serializer.GetSerializer(AssemblyRegistry.GetType(chunkHeader.Type), typeof(T))) == null)
                            {
                                throw new InvalidOperationException($"Could not find a valid content serializer for {typeof(T)} when loading {contentReference.Location}");
                            }
                        }

                        // First time, let's create it
                        if (contentSerializerContext.ContentManager.Exists(contentReference.Location))
                        {
                            obj = (T)contentSerializer.Construct(contentSerializerContext);
                            contentSerializerContext.ContentManager.RegisterDeserializedObject(contentReference.Location, obj);
                            contentReference.Value = obj;
                        }
                    }
                }
            }
            else if (referenceSerialization == ContentSerializerContext.AttachedReferenceSerialization.AsNull)
            {
                if (mode == ArchiveMode.Deserialize)
                {
                    obj = default(T);
                }
            }
            else if (referenceSerialization == ContentSerializerContext.AttachedReferenceSerialization.AsSerializableVersion)
            {
                if (mode == ArchiveMode.Serialize)
                {
                    // This case will happen when serializing build engine command hashes: we still want Location to still be written
                    var attachedReference = AttachedReferenceManager.GetAttachedReference(obj);
                    if (attachedReference?.Url == null)
                    {
                        throw new InvalidOperationException("Error when serializing reference.");
                    }

                    // TODO: Do not use string
                    stream.Write(obj.GetType().AssemblyQualifiedName);
                    stream.Write(attachedReference.Id);
                    stream.Write(attachedReference.Url);
                }
                else
                {
                    var type = AssemblyRegistry.GetType(stream.ReadString());
                    var id   = stream.Read <AssetId>();
                    var url  = stream.ReadString();

                    obj = (T)AttachedReferenceManager.CreateProxyObject(type, id, url);
                }
            }
            else
            {
                // This case will happen when serializing build engine command hashes: we still want Location to still be written
                if (mode == ArchiveMode.Serialize)
                {
                    // This case will happen when serializing build engine command hashes: we still want Location to still be written
                    var attachedReference = AttachedReferenceManager.GetAttachedReference(obj);
                    if (attachedReference?.Url == null)
                    {
                        throw new InvalidOperationException("Error when serializing reference.");
                    }

                    stream.Write(attachedReference.Url);
                }
                else
                {
                    // No real case yet
                    throw new NotSupportedException();
                }
            }
        }