Ejemplo n.º 1
0
 internal void InitializeTypeReaders()
 {
     typeReaderManager    = new ContentTypeReaderManager();
     typeReaders          = typeReaderManager.LoadAssetReaders(this);
     sharedResourceCount  = Read7BitEncodedInt();
     sharedResourceFixups = new List <KeyValuePair <int, Action <object> > >();
 }
Ejemplo n.º 2
0
 protected internal override void Initialize(ContentTypeReaderManager manager)
 {
     keyType     = typeof(TKey);
     valueType   = typeof(TValue);
     keyReader   = manager.GetTypeReader(keyType);
     valueReader = manager.GetTypeReader(valueType);
 }
Ejemplo n.º 3
0
        internal object ReadAsset <T>()
        {
            object result = null;

            typeReaderManager = new ContentTypeReaderManager(this);
            typeReaders       = typeReaderManager.LoadAssetReaders();
            foreach (ContentTypeReader r in typeReaders)
            {
                r.Initialize(typeReaderManager);
            }

            int sharedResourceCount = Read7BitEncodedInt();

            sharedResourceFixups = new List <KeyValuePair <int, Action <object> > >();

            // Read primary object
            int index = Read7BitEncodedInt();

            if (index > 0)
            {
                ContentTypeReader contentReader = typeReaders[index - 1];
                result = ReadObject <T>(contentReader);
            }

            // Read shared resources
            if (sharedResourceCount > 0)
            {
                ReadSharedResources(sharedResourceCount);
            }

            return(result);
        }
Ejemplo n.º 4
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
#if WEB
            elementReader = manager.GetTypeReader(typeof(T));
#else
            Type readerType = Enum.GetUnderlyingType(typeof(T));
            elementReader = manager.GetTypeReader(readerType);
#endif
        }
Ejemplo n.º 5
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);

            Type baseType = TargetType.BaseType;

            if (baseType != null && baseType != typeof(object))
            {
                baseTypeReader = manager.GetTypeReader(baseType);
            }

            constructor = TargetType.GetDefaultConstructor();

            const BindingFlags attrs = (
                BindingFlags.NonPublic |
                BindingFlags.Public |
                BindingFlags.Instance |
                BindingFlags.DeclaredOnly
                );

            /* Sometimes, overridden properties of abstract classes can show up even with
             * BindingFlags.DeclaredOnly is passed to GetProperties. Make sure that
             * all properties in this list are defined in this class by comparing
             * its get method with that of its base class. If they're the same
             * Then it's an overridden property.
             */
            PropertyInfo[] properties = TargetType.GetProperties(attrs);
            FieldInfo[]    fields     = TargetType.GetFields(attrs);
            readers = new List <ReadElement>(fields.Length + properties.Length);

            // Gather the properties.
            foreach (PropertyInfo property in properties)
            {
                MethodInfo pm = property.GetGetMethod(true);
                if (pm == null || pm != pm.GetBaseDefinition())
                {
                    continue;
                }

                ReadElement read = GetElementReader(manager, property);
                if (read != null)
                {
                    readers.Add(read);
                }
            }

            // Gather the fields.
            foreach (FieldInfo field in fields)
            {
                ReadElement read = GetElementReader(manager, field);
                if (read != null)
                {
                    readers.Add(read);
                }
            }
        }
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);
            this.manager = manager;
            BindingFlags attrs = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;

            constructor = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[0], null);
            properties  = typeof(T).GetProperties(attrs);
            fields      = typeof(T).GetFields(attrs);
        }
Ejemplo n.º 7
0
 internal void InitializeTypeReaders()
 {
     this.typeReaderManager = new ContentTypeReaderManager(this);
     this.typeReaders       = this.typeReaderManager.LoadAssetReaders();
     foreach (ContentTypeReader contentTypeReader in this.typeReaders)
     {
         contentTypeReader.Initialize(this.typeReaderManager);
     }
     this.sharedResourceCount  = this.Read7BitEncodedInt();
     this.sharedResourceFixups = new List <KeyValuePair <int, Action <object> > >();
 }
Ejemplo n.º 8
0
 internal void InitializeTypeReaders()
 {
     typeReaderManager    = new ContentTypeReaderManager();
     typeReaders          = typeReaderManager.LoadAssetReaders(this);
     sharedResourceCount  = Read7BitEncodedInt();
     sharedResourceFixups = new List <Action <object> > [sharedResourceCount];
     for (int i = 0; i < sharedResourceCount; i += 1)
     {
         sharedResourceFixups[i] = new List <Action <object> >();
     }
 }
Ejemplo n.º 9
0
        private T ReadAsset <T>(string assetName, System.IO.Stream assetStream,
                                Action <IDisposable> recordDisposableObject)
        {
            // GG EDIT removed code for loading raw assets like pngs

            // Load a XNB file
            ContentReader            reader      = new ContentReader(this, assetStream, this.graphicsDeviceService.GraphicsDevice);
            ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);

            reader.TypeReaders = typeManager.LoadAssetReaders(reader);
            foreach (ContentTypeReader r in reader.TypeReaders)
            {
                r.Initialize(typeManager);
            }
            // we need to read a byte here for things to work out, not sure why
            byte dummy = reader.ReadByte();

            System.Diagnostics.Debug.Assert(dummy == 0);

            // Get the 1-based index of the typereader we should use to start decoding with
            int index = reader.ReadByte();
            ContentTypeReader contentReader = reader.TypeReaders[index - 1];
            object            result        = reader.ReadObject <T>(contentReader);

            reader.Close();
            assetStream.Close();

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + assetName + " asset!");
            }

            // GG EDIT added IDisposable recording
            T tresult = (T)result;

            if (tresult is IDisposable)
            {
                if (recordDisposableObject == null)
                {
                    // GG TODO: would call local method here
                }
                else
                {
                    recordDisposableObject((IDisposable)tresult);
                }
            }

            return(tresult);
        }
Ejemplo n.º 10
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);
            this.manager = manager;
            Type type = targetType.BaseType;

            if (type != null && type != typeof(object))
            {
                baseType       = type;
                baseTypeReader = manager.GetTypeReader(baseType);
            }
            constructor = targetType.GetDefaultConstructor();
            properties  = targetType.GetAllProperties();
            fields      = targetType.GetAllFields();
        }
Ejemplo n.º 11
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);
            this.manager = manager;
            Type baseType = this.targetType.BaseType;

            if (baseType != (Type)null && baseType != typeof(object))
            {
                this.baseType       = baseType;
                this.baseTypeReader = manager.GetTypeReader(this.baseType);
            }
            this.constructor = ContentExtensions.GetDefaultConstructor(this.targetType);
            this.properties  = ContentExtensions.GetAllProperties(this.targetType);
            this.fields      = ContentExtensions.GetAllFields(this.targetType);
        }
Ejemplo n.º 12
0
        private int ReadHeader()
        {
            int Count = base.Read7BitEncodedInt();

            this.typeReaders = ContentTypeReaderManager.ReadTypeManifest(Count, this);
            int ResourceCount = base.Read7BitEncodedInt();

            if (ResourceCount > 0)
            {
                this.ResourceFixups = new List <Action <object> > [ResourceCount];
                for (int i = 0; i < ResourceCount; i++)
                {
                    this.ResourceFixups[i] = new List <Action <object> >();
                }
            }
            return(ResourceCount);
        }
Ejemplo n.º 13
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);
            this.manager = manager;

            if (targetType.BaseType != null && targetType.BaseType != typeof(object))
            {
                baseType       = targetType.BaseType;
                baseTypeReader = manager.GetTypeReader(baseType);
            }

            BindingFlags attrs = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;

            constructor = targetType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[0], null);
            properties  = targetType.GetProperties(attrs);
            fields      = targetType.GetFields(attrs);
        }
Ejemplo n.º 14
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);

            var baseType = ReflectionHelpers.GetBaseType(TargetType);

            if (baseType != null && baseType != typeof(object))
            {
                _baseTypeReader = manager.GetTypeReader(baseType);
            }

            _constructor = TargetType.GetDefaultConstructor();

            var properties = TargetType.GetAllProperties();
            var fields     = TargetType.GetAllFields();

            _readers = new List <ReadElement>(fields.Length + properties.Length);

            // Gather the properties.
            foreach (var property in properties)
            {
                var read = GetElementReader(manager, property);
                if (read != null)
                {
                    _readers.Add(read);
                }
            }

            // Gather the fields.
            foreach (var field in fields)
            {
                var read = GetElementReader(manager, field);
                if (read != null)
                {
                    _readers.Add(read);
                }
            }
        }
Ejemplo n.º 15
0
        internal static ContentTypeReader[] ReadTypeManifest(int typeCount, ContentReader contentReader)
        {
            ContentTypeReader[]      readers        = new ContentTypeReader[typeCount];
            List <ContentTypeReader> newTypeReaders = null;

            try
            {
                for (int i = 0; i < typeCount; i++)
                {
                    string typename = contentReader.ReadString();
                    if (typename.Contains("PublicKey"))
                    {
                        typename = typename.Split(new char[] { '[', '[' })[0] + "[" + typename.Split(new char[] { '[', '[' })[2].Split(',')[0] + "]"; //FIXME: Fix for cross-assembly reference problem. Maybe bad solution. Problem: tried to load type from msxna assembly.
                    }
                    ContentTypeReader reader = GetTypeReader(typename, contentReader, ref newTypeReaders);
                    if (contentReader.ReadInt32() != reader.TypeVersion)
                    {
                        throw new ContentLoadException("Bad XNB TypeVersion");
                    }
                    readers[i] = reader;
                }
                if (newTypeReaders != null)
                {
                    ContentTypeReaderManager manager = new ContentTypeReaderManager(contentReader);
                    foreach (ContentTypeReader reader2 in newTypeReaders)
                    {
                        reader2.Initialize(manager);
                    }
                }
                return(readers);
            }
            catch
            {
                RollbackAddReaders(newTypeReaders);
                throw;
            }
            return(readers);
        }
Ejemplo n.º 16
0
        public object ReadAsset <T>()
        {
            if (Version < 6)
            {
                // Transistor: Skip old unused resource loader deets. Used to call ContentReaderManager here.
                int num = Read7BitEncodedInt();
                for (int i = 0; i < num; i++)
                {
                    ReadString();
                    ReadInt32();
                }
                Read7BitEncodedInt();
                Read7BitEncodedInt();

                if (typeof(T) != typeof(Texture))
                {
                    throw new Exception("Only textures are supported for the version 5 format.");
                }
            }

            // Use the content type reader for the requested type directly.
            return(ContentTypeReaderManager.GetTypeReader(typeof(T)).Read(this));
        }
Ejemplo n.º 17
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            base.Initialize(manager);

            Type baseType = TargetType.BaseType;

            if (baseType != null && baseType != typeof(object))
            {
                baseTypeReader = manager.GetTypeReader(baseType);
            }

            constructor = TargetType.GetDefaultConstructor();

            PropertyInfo[] properties = TargetType.GetAllProperties();
            FieldInfo[]    fields     = TargetType.GetAllFields();
            readers = new List <ReadElement>(fields.Length + properties.Length);

            // Gather the properties.
            foreach (PropertyInfo property in properties)
            {
                ReadElement read = GetElementReader(manager, property);
                if (read != null)
                {
                    readers.Add(read);
                }
            }

            // Gather the fields.
            foreach (FieldInfo field in fields)
            {
                ReadElement read = GetElementReader(manager, field);
                if (read != null)
                {
                    readers.Add(read);
                }
            }
        }
Ejemplo n.º 18
0
 protected internal virtual void Initialize(ContentTypeReaderManager manager)
 {
     // Do nothing. Are we supposed to add ourselves to the manager?
 }
Ejemplo n.º 19
0
        protected T ReadAsset <T>(string assetName, Action <IDisposable> recordDisposableObject, int lod = 0)
        {
            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentNullException("assetName");
            }
            if (disposed)
            {
                throw new ObjectDisposedException("ContentManager");
            }

            //GC.GetTotalMemory(true);
            //Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
            //long memstart = currentProcess.WorkingSet64;

            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            // Replace Windows path separators with local path separators
            assetName = GetRealFilename <T>(assetName);

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (!Path.HasExtension(assetName))
            {
                assetName = string.Format("{0}.xnb", assetName);
            }

            if (Path.GetExtension(assetName).ToLower() == ".xnb")
            {
                // Load a XNB file
                using (Stream stream = OpenStream(assetName))
                {
                    using (BinaryReader xnbReader = new BinaryReader(stream))
                    {
                        // The first 4 bytes should be the "XNB" header. i use that to detect an invalid file
                        byte[] headerBuffer = new byte[3];
                        xnbReader.Read(headerBuffer, 0, 3);

                        string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 3);

                        byte platform = xnbReader.ReadByte();

                        if (string.Compare(headerString, "XNB") != 0 ||
                            !(platform == 'w' || platform == 'x' || platform == 'm'))
                        {
                            throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?");
                        }

                        ushort version         = xnbReader.ReadUInt16();
                        int    graphicsProfile = version & 0x7f00;
                        version &= 0x80ff;

                        bool compressed = false;
                        if (version == 0x8005 || version == 0x8004)
                        {
                            compressed = true;
                        }
                        else if (version != 5 && version != 4)
                        {
                            throw new ContentLoadException("Invalid XNB version");
                        }

                        // The next int32 is the length of the XNB file
                        int xnbLength = xnbReader.ReadInt32();

                        ContentReader reader;
                        if (compressed)
                        {
                            //decompress the xnb
                            //thanks to ShinAli (https://bitbucket.org/alisci01/xnbdecompressor)
                            int compressedSize   = xnbLength - 14;
                            int decompressedSize = xnbReader.ReadInt32();
                            int newFileSize      = decompressedSize + 10;

                            MemoryStream decompressedStream = new MemoryStream(decompressedSize);

                            LzxDecoder dec          = new LzxDecoder(16);
                            int        decodedBytes = 0;
                            int        pos          = 0;

                            while (pos < compressedSize)
                            {
                                // let's seek to the correct position
                                stream.Seek(pos + 14, SeekOrigin.Begin);
                                int hi         = stream.ReadByte();
                                int lo         = stream.ReadByte();
                                int block_size = (hi << 8) | lo;
                                int frame_size = 0x8000;
                                if (hi == 0xFF)
                                {
                                    hi         = lo;
                                    lo         = (byte)stream.ReadByte();
                                    frame_size = (hi << 8) | lo;
                                    hi         = (byte)stream.ReadByte();
                                    lo         = (byte)stream.ReadByte();
                                    block_size = (hi << 8) | lo;
                                    pos       += 5;
                                }
                                else
                                {
                                    pos += 2;
                                }

                                if (block_size == 0 || frame_size == 0)
                                {
                                    break;
                                }

                                int lzxRet = dec.Decompress(stream, block_size, decompressedStream, frame_size);
                                pos          += block_size;
                                decodedBytes += frame_size;
                            }

                            if (decompressedStream.Position != decompressedSize)
                            {
                                throw new ContentLoadException("Decompression of " + originalAssetName + "failed. " +
                                                               " Try decompressing with nativeDecompressXnb first.");
                            }

                            decompressedStream.Seek(0, SeekOrigin.Begin);
                            reader = new ContentReader(this, decompressedStream, this.graphicsDeviceService.GraphicsDevice);
                        }
                        else
                        {
                            reader = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice);
                        }

                        using (reader)
                        {
                            ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                            reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                            foreach (ContentTypeReader r in reader.TypeReaders)
                            {
                                r.Initialize(typeManager);
                            }
                            // we need to read a byte here for things to work out, not sure why
                            reader.ReadByte();

                            // Get the 1-based index of the typereader we should use to start decoding with
                            int index = reader.ReadByte();
                            ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                            result = reader.ReadObject <T>(contentReader);
                        }
                    }
                }
            }
            else
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    using (Stream assetStream = OpenStream(assetName))
                    {
                        Texture2D texture = Texture2D.FromFile(graphicsDeviceService.GraphicsDevice, assetStream, lod);
                        texture.Name = originalAssetName;
                        result       = texture;
                    }
                }
                else if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }
                else if ((typeof(T) == typeof(Song)))
                {
                    result = new Song(assetName);
                }
                else if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = new SoundEffect(assetName);
                }
                else if ((typeof(T) == typeof(Video)))
                {
                    result = new Video(assetName);
                }
                else if ((typeof(T) == typeof(Effect)))
                {
                    result = new Effect(graphicsDeviceService.GraphicsDevice, assetName);
                }
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            // Store references to the asset for later use
            T asset = (T)result;

            if (asset is IDisposable)
            {
                if (recordDisposableObject != null)
                {
                    recordDisposableObject(asset as IDisposable);
                }
                else
                {
                    disposableAssets.Add(asset as IDisposable);
                }
            }
            loadedAssets.Add(originalAssetName, asset);

            //GC.GetTotalMemory(true);
            //var memend = currentProcess.WorkingSet64;

            //Console.WriteLine("mem: " + assetName + ", " + (memend -memstart).ToString());

            return((T)result);
        }
Ejemplo n.º 20
0
 protected internal virtual void Initialize(ContentTypeReaderManager manager)
 {
     // Do nothing. Are we supposed to add ourselves to the manager?
 }
Ejemplo n.º 21
0
        public T Load <T>(string assetName)
        {
            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentException("assetname");
            }

            if (!string.IsNullOrEmpty(_rootDirectory))
            {
                assetName = _rootDirectory + Path.DirectorySeparatorChar + assetName;
            }

            // Check for windows-style directory separator character
            assetName = assetName.Replace('\\', Path.DirectorySeparatorChar);

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Song)))
            {
                assetName = SongReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(SoundEffect)))
            {
                assetName = SoundEffectReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Video)))
            {
                assetName = Video.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (!Path.HasExtension(assetName))
            {
                assetName = string.Format("{0}.xnb", assetName);
            }

            if (Path.GetExtension(assetName).ToUpper() == ".XNB")
            {
                // Load a XNB file
                FileStream   stream    = new FileStream(assetName, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryReader xnbReader = new BinaryReader(stream);

                // The first 4 bytes should be the "XNB" header. i use that to detect an invalid file
                byte[] headerBuffer = new byte[3];
                xnbReader.Read(headerBuffer, 0, 3);

                string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 3);

                byte platform = xnbReader.ReadByte();

                if (string.Compare(headerString, "XNB") != 0 ||
                    !(platform == 'w' || platform == 'x' || platform == 'm'))
                {
                    throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?");
                }

                ushort version         = xnbReader.ReadUInt16();
                int    graphicsProfile = version & 0x7f00;
                version &= 0x80ff;

                bool compressed = false;
                if (version == 0x8005 || version == 0x8004)
                {
                    compressed = true;
                }
                else if (version != 5 && version != 4)
                {
                    throw new ContentLoadException("Invalid XNB version");
                }

                // The next int32 is the length of the XNB file
                int xnbLength = xnbReader.ReadInt32();

                ContentReader reader;
                if (compressed)
                {
                    //decompress the xnb
                    //thanks to ShinAli (https://bitbucket.org/alisci01/xnbdecompressor)
                    int compressedSize   = xnbLength - 14;
                    int decompressedSize = xnbReader.ReadInt32();
                    int newFileSize      = decompressedSize + 10;

                    MemoryStream decompressedStream = new MemoryStream(decompressedSize);

                    LzxDecoder dec          = new LzxDecoder(16);
                    int        decodedBytes = 0;
                    int        pos          = 0;

                    while (pos < compressedSize)
                    {
                        // let's seek to the correct position
                        stream.Seek(pos + 14, SeekOrigin.Begin);
                        int hi         = stream.ReadByte();
                        int lo         = stream.ReadByte();
                        int block_size = (hi << 8) | lo;
                        int frame_size = 0x8000;
                        if (hi == 0xFF)
                        {
                            hi         = lo;
                            lo         = (byte)stream.ReadByte();
                            frame_size = (hi << 8) | lo;
                            hi         = (byte)stream.ReadByte();
                            lo         = (byte)stream.ReadByte();
                            block_size = (hi << 8) | lo;
                            pos       += 5;
                        }
                        else
                        {
                            pos += 2;
                        }

                        if (block_size == 0 || frame_size == 0)
                        {
                            break;
                        }

                        int lzxRet = dec.Decompress(stream, block_size, decompressedStream, frame_size);
                        pos          += block_size;
                        decodedBytes += frame_size;
                    }

                    if (decompressedStream.Position != decompressedSize)
                    {
                        throw new ContentLoadException("Decompression of " + originalAssetName + "failed. " +
                                                       " Try decompressing with nativeDecompressXnb first.");
                    }

                    decompressedStream.Seek(0, SeekOrigin.Begin);
                    reader = new ContentReader(this, decompressedStream, this.graphicsDeviceService.GraphicsDevice);
                }
                else
                {
                    reader = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice);
                }

                ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                foreach (ContentTypeReader r in reader.TypeReaders)
                {
                    r.Initialize(typeManager);
                }
                // we need to read a byte here for things to work out, not sure why
                reader.ReadByte();

                // Get the 1-based index of the typereader we should use to start decoding with
                int index = reader.ReadByte();
                ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                result = reader.ReadObject <T>(contentReader);

                reader.Close();
                stream.Close();
            }
            else
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    result = Texture2D.FromFile(graphicsDeviceService.GraphicsDevice, assetName);
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }
                if ((typeof(T) == typeof(Song)))
                {
                    result = new Song(assetName);
                }
                if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = new SoundEffect(assetName);
                }
                if ((typeof(T) == typeof(Video)))
                {
                    result = new Video(assetName);
                }
                if ((typeof(T) == typeof(Effect)))
                {
                    result = new Effect(graphicsDeviceService.GraphicsDevice, assetName);
                }
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            return((T)result);
        }
Ejemplo n.º 22
0
        protected T ReadAsset <T>(string assetName, Action <IDisposable> recordDisposableObject)
        {
            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentNullException();
            }
            if (disposed)
            {
                throw new ObjectDisposedException("ContentManager");
            }

            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            // Replace Windows path separators with local path separators
            assetName = Path.Combine(_rootDirectory, assetName.Replace('\\', Path.DirectorySeparatorChar));

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Song)))
            {
                assetName = SongReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SoundEffect)))
            {
                assetName = SoundEffectReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Video)))
            {
                assetName = Video.Normalize(assetName);
            }
            else
            {
                throw new NotSupportedException("Format not supported");
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (!Path.HasExtension(assetName))
            {
                assetName = string.Format("{0}.xnb", assetName);
            }

            if (Path.GetExtension(assetName).ToUpper() == ".XNB")
            {
                // Load a XNB file
                //Loads from Assets directory + /assetName
                Stream       stream    = OpenStream(assetName);
                BinaryReader xnbReader = new BinaryReader(stream);

                // The first 4 bytes should be the "XNB" header. i use that to detect an invalid file
                byte[] headerBuffer = new byte[3];
                xnbReader.Read(headerBuffer, 0, 3);

                string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 3);

                byte platform = xnbReader.ReadByte();

                if (string.Compare(headerString, "XNB") != 0 ||
                    !(platform == 'w' || platform == 'x' || platform == 'm'))
                {
                    throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?");
                }

                ushort version         = xnbReader.ReadUInt16();
                int    graphicsProfile = version & 0x7f00;
                version &= 0x80ff;

                bool compressed = false;
                if (version == 0x8005 || version == 0x8004)
                {
                    compressed = true;
                }
                else if (version != 5 && version != 4)
                {
                    throw new ContentLoadException("Invalid XNB version");
                }

                // The next int32 is the length of the XNB file
                int xnbLength = xnbReader.ReadInt32();

                ContentReader reader;
                if (compressed)
                {
                    //decompress the xnb
                    //thanks to ShinAli (https://bitbucket.org/alisci01/xnbdecompressor)
                    int compressedSize   = xnbLength - 14;
                    int decompressedSize = xnbReader.ReadInt32();
                    int newFileSize      = decompressedSize + 10;

                    MemoryStream decompressedStream = new MemoryStream(decompressedSize);

                    LzxDecoder dec          = new LzxDecoder(16);
                    int        decodedBytes = 0;
                    int        pos          = 0;

                    while (pos < compressedSize)
                    {
                        // let's seek to the correct position
                        stream.Seek(pos + 14, SeekOrigin.Begin);
                        int hi         = stream.ReadByte();
                        int lo         = stream.ReadByte();
                        int block_size = (hi << 8) | lo;
                        int frame_size = 0x8000;
                        if (hi == 0xFF)
                        {
                            hi         = lo;
                            lo         = (byte)stream.ReadByte();
                            frame_size = (hi << 8) | lo;
                            hi         = (byte)stream.ReadByte();
                            lo         = (byte)stream.ReadByte();
                            block_size = (hi << 8) | lo;
                            pos       += 5;
                        }
                        else
                        {
                            pos += 2;
                        }

                        if (block_size == 0 || frame_size == 0)
                        {
                            break;
                        }

                        int lzxRet = dec.Decompress(stream, block_size, decompressedStream, frame_size);
                        pos          += block_size;
                        decodedBytes += frame_size;
                    }

                    if (decompressedStream.Position != decompressedSize)
                    {
                        throw new ContentLoadException("Decompression of " + originalAssetName + "failed. " +
                                                       " Try decompressing with nativeDecompressXnb first.");
                    }

                    decompressedStream.Seek(0, SeekOrigin.Begin);
                    reader = new ContentReader(this, decompressedStream, this.graphicsDeviceService.GraphicsDevice);
                }
                else
                {
                    reader = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice);
                }

                ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                foreach (ContentTypeReader r in reader.TypeReaders)
                {
                    r.Initialize(typeManager);
                }
                // we need to read a byte here for things to work out, not sure why
                reader.ReadByte();

                // Get the 1-based index of the typereader we should use to start decoding with
                int index = reader.ReadByte();
                ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                result = reader.ReadObject <T>(contentReader);

                reader.Close();
                stream.Close();
            }
            else
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    //Basically the same as Texture2D.FromFile but loading from the assets instead of a filePath
                    Stream  assetStream = OpenStream(assetName);
                    Bitmap  image       = BitmapFactory.DecodeStream(assetStream);
                    ESImage theTexture  = new ESImage(image, graphicsDeviceService.GraphicsDevice.PreferedFilter);
                    result = new Texture2D(theTexture)
                    {
                        Name = Path.GetFileNameWithoutExtension(assetName)
                    };
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }

                if ((typeof(T) == typeof(Song)))
                {
                    result = new Song(assetName);
                }
                if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = new SoundEffect(assetName);
                }
                if ((typeof(T) == typeof(Video)))
                {
                    result = new Video(assetName);
                }
            }

            /*else
             * {
             *      // Load a XNB file
             * //Loads from Assets directory + /assetName
             *  Stream assetStream = OpenStream(assetName);
             *
             * ContentReader reader = new ContentReader(this, assetStream, this.graphicsDeviceService.GraphicsDevice);
             *      ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
             *      reader.TypeReaders = typeManager.LoadAssetReaders(reader);
             * foreach (ContentTypeReader r in reader.TypeReaders)
             * {
             * r.Initialize(typeManager);
             * }
             * // we need to read a byte here for things to work out, not sure why
             * reader.ReadByte();
             *
             *      // Get the 1-based index of the typereader we should use to start decoding with
             * int index = reader.ReadByte();
             *      ContentTypeReader contentReader = reader.TypeReaders[index - 1];
             * result = reader.ReadObject<T>(contentReader);
             *
             *      reader.Close();
             *      assetStream.Close();
             * }*/

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            // Store references to the asset for later use
            T asset = (T)result;

            if (asset is IDisposable && recordDisposableObject != null)
            {
                recordDisposableObject(asset as IDisposable);
            }
            else
            {
                disposableAssets.Add(asset as IDisposable);
            }
            loadedAssets.Add(originalAssetName, asset);

            return((T)result);
        }
Ejemplo n.º 23
0
        public T Load <T>(string assetName)
        {
            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentException("assetname");
            }

            if (!string.IsNullOrEmpty(_rootDirectory))
            {
                assetName = _rootDirectory + Path.DirectorySeparatorChar + assetName;
            }

            // Check for windows-style directory separator character
            assetName = assetName.Replace('\\', Path.DirectorySeparatorChar);

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Song)))
            {
                assetName = SongReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(SoundEffect)))
            {
                assetName = SoundEffectReader.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Video)))
            {
                assetName = Video.Normalize(assetName);
            }
            if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (Path.GetExtension(assetName).ToUpper() != ".XNB")
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    result = Texture2D.FromFile(graphicsDeviceService.GraphicsDevice, assetName);
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }
                if ((typeof(T) == typeof(Song)))
                {
                    result = new Song(assetName);
                }
                if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = new SoundEffect(assetName);
                }
                if ((typeof(T) == typeof(Video)))
                {
                    result = new Video(assetName);
                }
            }
            else
            {
                // Load a XNB file
                FileStream stream = new FileStream(assetName, FileMode.Open, FileAccess.Read, FileShare.Read);

                ContentReader            reader      = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice);
                ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                foreach (ContentTypeReader r in reader.TypeReaders)
                {
                    r.Initialize(typeManager);
                }
                // we need to read a byte here for things to work out, not sure why
                reader.ReadByte();

                // Get the 1-based index of the typereader we should use to start decoding with
                int index = reader.ReadByte();
                ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                result = reader.ReadObject <T>(contentReader);

                reader.Close();
                stream.Close();
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            return((T)result);
        }
Ejemplo n.º 24
0
 protected internal virtual void Initialize(ContentTypeReaderManager manager)
 {
     manager.Readers.Add(TargetType, this);
 }
Ejemplo n.º 25
0
 internal ContentTypeReader[] LoadAssetReaders()
 {
   if (ContentTypeReaderManager.falseflag)
   {
     ByteReader byteReader = new ByteReader();
     SByteReader sbyteReader = new SByteReader();
     DateTimeReader dateTimeReader = new DateTimeReader();
     DecimalReader decimalReader = new DecimalReader();
     BoundingSphereReader boundingSphereReader = new BoundingSphereReader();
     BoundingFrustumReader boundingFrustumReader = new BoundingFrustumReader();
     RayReader rayReader = new RayReader();
     ListReader<char> listReader1 = new ListReader<char>();
     ListReader<Rectangle> listReader2 = new ListReader<Rectangle>();
     ArrayReader<Rectangle> arrayReader1 = new ArrayReader<Rectangle>();
     ListReader<Vector3> listReader3 = new ListReader<Vector3>();
     ListReader<StringReader> listReader4 = new ListReader<StringReader>();
     ListReader<int> listReader5 = new ListReader<int>();
     SpriteFontReader spriteFontReader = new SpriteFontReader();
     Texture2DReader texture2Dreader = new Texture2DReader();
     CharReader charReader = new CharReader();
     RectangleReader rectangleReader = new RectangleReader();
     StringReader stringReader = new StringReader();
     Vector2Reader vector2Reader = new Vector2Reader();
     Vector3Reader vector3Reader = new Vector3Reader();
     Vector4Reader vector4Reader = new Vector4Reader();
     CurveReader curveReader = new CurveReader();
     IndexBufferReader indexBufferReader = new IndexBufferReader();
     BoundingBoxReader boundingBoxReader = new BoundingBoxReader();
     MatrixReader matrixReader = new MatrixReader();
     BasicEffectReader basicEffectReader = new BasicEffectReader();
     VertexBufferReader vertexBufferReader = new VertexBufferReader();
     AlphaTestEffectReader testEffectReader = new AlphaTestEffectReader();
     EnumReader<SpriteEffects> enumReader1 = new EnumReader<SpriteEffects>();
     ArrayReader<float> arrayReader2 = new ArrayReader<float>();
     ArrayReader<Vector2> arrayReader3 = new ArrayReader<Vector2>();
     ListReader<Vector2> listReader6 = new ListReader<Vector2>();
     ArrayReader<Matrix> arrayReader4 = new ArrayReader<Matrix>();
     EnumReader<Blend> enumReader2 = new EnumReader<Blend>();
     NullableReader<Rectangle> nullableReader = new NullableReader<Rectangle>();
     EffectMaterialReader effectMaterialReader = new EffectMaterialReader();
     ExternalReferenceReader externalReferenceReader = new ExternalReferenceReader();
   }
   int length = this._reader.Read7BitEncodedInt();
   this.contentReaders = new ContentTypeReader[length];
   for (int index = 0; index < length; ++index)
   {
     string str = this._reader.ReadString();
     Func<ContentTypeReader> func;
     if (ContentTypeReaderManager.typeCreators.TryGetValue(str, out func))
     {
       this.contentReaders[index] = func();
     }
     else
     {
       string typeName = ContentTypeReaderManager.PrepareType(str);
       Type type = Type.GetType(typeName);
       if (type != (Type) null)
       {
         try
         {
           this.contentReaders[index] = ContentExtensions.GetDefaultConstructor(type).Invoke((object[]) null) as ContentTypeReader;
         }
         catch (TargetInvocationException ex)
         {
           throw new InvalidOperationException("Failed to get default constructor for ContentTypeReader. To work around, add a creation function to ContentTypeReaderManager.AddTypeCreator() with the following failed type string: " + str);
         }
       }
       else
         throw new ContentLoadException("Could not find matching content reader of type " + str + " (" + typeName + ")");
     }
     this._reader.ReadInt32();
   }
   return this.contentReaders;
 }
 protected internal virtual void Initialize(ContentTypeReaderManager manager)
 {
 }
Ejemplo n.º 27
0
 protected internal virtual void Initialize(ContentTypeReaderManager manager)
 {
 }
Ejemplo n.º 28
0
        private static ReadElement GetElementReader(
            ContentTypeReaderManager manager,
            MemberInfo member
            )
        {
            PropertyInfo property = member as PropertyInfo;
            FieldInfo    field    = member as FieldInfo;

            if (property != null)
            {
                // Properties must have at least a getter.
                if (property.CanRead == false)
                {
                    return(null);
                }

                // Skip over indexer properties
                if (property.GetIndexParameters().Length > 0)
                {
                    return(null);
                }
            }

            // Are we explicitly asked to ignore this item?
            Attribute attr = Attribute.GetCustomAttribute(
                member,
                typeof(ContentSerializerIgnoreAttribute)
                );

            if (attr != null)
            {
                return(null);
            }

            ContentSerializerAttribute contentSerializerAttribute = Attribute.GetCustomAttribute(
                member,
                typeof(ContentSerializerAttribute)
                ) as ContentSerializerAttribute;

            if (contentSerializerAttribute == null)
            {
                if (property != null)
                {
                    /* There is no ContentSerializerAttribute, so non-public
                     * properties cannot be deserialized.
                     */
                    MethodInfo getMethod = property.GetGetMethod(true);
                    if (getMethod != null && !getMethod.IsPublic)
                    {
                        return(null);
                    }
                    MethodInfo setMethod = property.GetSetMethod(true);
                    if (setMethod != null && !setMethod.IsPublic)
                    {
                        return(null);
                    }

                    /* If the read-only property has a type reader,
                     * and CanDeserializeIntoExistingObject is true,
                     * then it is safe to deserialize into the existing object.
                     */
                    if (!property.CanWrite)
                    {
                        ContentTypeReader typeReader = manager.GetTypeReader(property.PropertyType);
                        if (typeReader == null || !typeReader.CanDeserializeIntoExistingObject)
                        {
                            return(null);
                        }
                    }
                }
                else
                {
                    /* There is no ContentSerializerAttribute, so non-public
                     * fields cannot be deserialized.
                     */
                    if (!field.IsPublic)
                    {
                        return(null);
                    }

                    // evolutional: Added check to skip initialise only fields
                    if (field.IsInitOnly)
                    {
                        return(null);
                    }
                }
            }

            Action <object, object> setter;
            Type elementType;

            if (property != null)
            {
                elementType = property.PropertyType;
                if (property.CanWrite)
                {
                    setter = (o, v) => property.SetValue(o, v, null);
                }
                else
                {
                    setter = (o, v) => { };
                }
            }
            else
            {
                elementType = field.FieldType;
                setter      = field.SetValue;
            }

            if (contentSerializerAttribute != null &&
                contentSerializerAttribute.SharedResource)
            {
                return((input, parent) =>
                {
                    Action <object> action = value => setter(parent, value);
                    input.ReadSharedResource(action);
                });
            }

            // We need to have a reader at this point.
            ContentTypeReader reader = manager.GetTypeReader(elementType);

            if (reader == null)
            {
                throw new ContentLoadException(string.Format(
                                                   "Content reader could not be found for {0} type.",
                                                   elementType.FullName
                                                   ));
            }

            /* We use the construct delegate to pick the correct existing
             * object to be the target of deserialization.
             */
            Func <object, object> construct = parent => null;

            if (property != null && !property.CanWrite)
            {
                construct = parent => property.GetValue(parent, null);
            }

            return((input, parent) =>
            {
                object existing = construct(parent);
                object obj2 = input.ReadObject(reader, existing);
                setter(parent, obj2);
            });
        }
Ejemplo n.º 29
0
        private static ReadElement GetElementReader(ContentTypeReaderManager manager, MemberInfo member)
        {
            var property = member as PropertyInfo;
            var field    = member as FieldInfo;

            // properties must have public get and set
            if (property != null && (property.CanWrite == false || property.CanRead == false))
            {
                return(null);
            }

            if (property != null && property.Name == "Item")
            {
                var getMethod = ReflectionHelpers.GetPropertyGetMethod(property);
                var setMethod = ReflectionHelpers.GetPropertySetMethod(property);

                if ((getMethod != null && getMethod.GetParameters().Length > 0) ||
                    (setMethod != null && setMethod.GetParameters().Length > 0))
                {
                    /*
                     * This is presumably a property like this[indexer] and this
                     * should not get involved in the object deserialization
                     * */
                    return(null);
                }
            }

            var attr = ReflectionHelpers.GetCustomAttribute(member, typeof(ContentSerializerIgnoreAttribute));

            if (attr != null)
            {
                return(null);
            }

            var contentSerializerAttribute =
                ReflectionHelpers.GetCustomAttribute(member, typeof(ContentSerializerAttribute)) as
                ContentSerializerAttribute;

            var isSharedResource = false;

            if (contentSerializerAttribute != null)
            {
                isSharedResource = contentSerializerAttribute.SharedResource;
            }
            else
            {
                if (property != null)
                {
                    if (!ReflectionHelpers.PropertyIsPublic(property))
                    {
                        return(null);
                    }
                }
                else
                {
                    if (!field.IsPublic)
                    {
                        return(null);
                    }

                    // evolutional: Added check to skip initialise only fields
                    if (field.IsInitOnly)
                    {
                        return(null);
                    }

                    // Private fields can be serialized if they have ContentSerializerAttribute added to them
                    if (field.IsPrivate && contentSerializerAttribute == null)
                    {
                        return(null);
                    }
                }
            }

            Action <object, object> setter;
            ContentTypeReader       reader;
            Type elementType;

            if (property != null)
            {
                elementType = property.PropertyType;
                reader      = manager.GetTypeReader(property.PropertyType);
                setter      = (o, v) => property.SetValue(o, v, null);
            }
            else
            {
                elementType = field.FieldType;
                reader      = manager.GetTypeReader(field.FieldType);
                setter      = field.SetValue;
            }

            if (isSharedResource)
            {
                return((input, parent) =>
                {
                    Action <object> action = value => setter(parent, value);
                    input.ReadSharedResource(action);
                });
            }

            Func <object> construct = () => null;

            if (ReflectionHelpers.IsConcreteClass(elementType))
            {
                var constructor = elementType.GetDefaultConstructor();
                if (constructor != null)
                {
                    construct = () => constructor.Invoke(null);
                }
            }

            // Reading elements serialized as "object".
            if (reader == null && elementType == typeof(object))
            {
                return((input, parent) =>
                {
                    var obj2 = input.ReadObject <object>();
                    setter(parent, obj2);
                });
            }

            // evolutional: Fix. We can get here and still be NULL, exit gracefully
            if (reader == null)
            {
                return(null);
            }

            return((input, parent) =>
            {
                var existing = construct();
                var obj2 = input.ReadObject(reader, existing);
                setter(parent, obj2);
            });
        }
Ejemplo n.º 30
0
        public T Load <T>(string assetName)
        {
            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            // Check for windows-style directory separator character
            //Lowercase assetName (monodroid specification all assests are lowercase)
            assetName = Path.Combine(_rootDirectory, assetName.Replace('\\', Path.DirectorySeparatorChar)).ToLower();

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }

            /*else if ((typeof(T) == typeof(Song)))
             * {
             *  assetName = SongReader.Normalize(assetName);
             * }
             * else if ((typeof(T) == typeof(SoundEffect)))
             * {
             *  assetName = SoundEffectReader.Normalize(assetName);
             * }
             * else if ((typeof(T) == typeof(Video)))
             * {
             *  assetName = Video.Normalize(assetName);
             * }*/
            else
            {
                throw new NotSupportedException("Format not supported");
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (Path.GetExtension(assetName).ToUpper() != ".XNB")
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    //Basically the same as Texture2D.FromFile but loading from the assets instead of a filePath
                    Stream  assetStream = File.Open(assetName, FileMode.Open, FileAccess.Read);
                    Bitmap  image       = (Bitmap)Bitmap.FromStream(assetStream);
                    ESImage theTexture  = new ESImage(image, graphicsDeviceService.GraphicsDevice.PreferedFilter);
                    result = new Texture2D(theTexture)
                    {
                        Name = Path.GetFileNameWithoutExtension(assetName)
                    };
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }

                /*if ((typeof(T) == typeof(Song)))
                 *  result = new Song(assetName);
                 * if ((typeof(T) == typeof(SoundEffect)))
                 *  result = new SoundEffect(assetName);
                 * if ((typeof(T) == typeof(Video)))
                 *  result = new Video(assetName);*/
            }
            else
            {
                // Load a XNB file
                //Loads from Assets directory + /assetName
                Stream assetStream = File.Open(assetName, FileMode.Open, FileAccess.Read);

                ContentReader            reader      = new ContentReader(this, assetStream, this.graphicsDeviceService.GraphicsDevice);
                ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                foreach (ContentTypeReader r in reader.TypeReaders)
                {
                    r.Initialize(typeManager);
                }
                // we need to read a byte here for things to work out, not sure why
                reader.ReadByte();

                // Get the 1-based index of the typereader we should use to start decoding with
                int index = reader.ReadByte();
                ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                result = reader.ReadObject <T>(contentReader);

                reader.Close();
                assetStream.Close();
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            return((T)result);
        }
Ejemplo n.º 31
0
        protected internal override void Initialize(ContentTypeReaderManager manager)
        {
            Type readerType = typeof(T);

            elementReader = manager.GetTypeReader(readerType);
        }
Ejemplo n.º 32
0
        private static ReadElement GetElementReader(ContentTypeReaderManager manager, MemberInfo member)
        {
            var property = member as PropertyInfo;
            var field    = member as FieldInfo;

            Debug.Assert(field != null || property != null);

            if (property != null)
            {
                // Properties must have at least a getter.
                if (property.CanRead == false)
                {
                    return(null);
                }

                // Skip over indexer properties.
                if (property.GetIndexParameters().Any())
                {
                    return(null);
                }
            }

            // Are we explicitly asked to ignore this item?
            if (ReflectionHelpers.GetCustomAttribute <ContentSerializerIgnoreAttribute>(member) != null)
            {
                return(null);
            }

            var contentSerializerAttribute = ReflectionHelpers.GetCustomAttribute <ContentSerializerAttribute>(member);

            if (contentSerializerAttribute == null)
            {
                if (property != null)
                {
                    // There is no ContentSerializerAttribute, so non-public
                    // properties cannot be deserialized.
                    if (!ReflectionHelpers.PropertyIsPublic(property))
                    {
                        return(null);
                    }

                    // If the read-only property has a type reader,
                    // and CanDeserializeIntoExistingObject is true,
                    // then it is safe to deserialize into the existing object.
                    if (!property.CanWrite)
                    {
                        var typeReader = manager.GetTypeReader(property.PropertyType);
                        if (typeReader == null || !typeReader.CanDeserializeIntoExistingObject)
                        {
                            return(null);
                        }
                    }
                }
                else
                {
                    // There is no ContentSerializerAttribute, so non-public
                    // fields cannot be deserialized.
                    if (!field.IsPublic)
                    {
                        return(null);
                    }

                    // evolutional: Added check to skip initialise only fields
                    if (field.IsInitOnly)
                    {
                        return(null);
                    }
                }
            }

            Action <object, object> setter;
            Type elementType;

            if (property != null)
            {
                elementType = property.PropertyType;
                if (property.CanWrite)
                {
                    setter = (o, v) => property.SetValue(o, v, null);
                }
                else
                {
                    setter = (o, v) => { }
                };
            }
            else
            {
                elementType = field.FieldType;
                setter      = field.SetValue;
            }

            // Shared resources get special treatment.
            if (contentSerializerAttribute != null && contentSerializerAttribute.SharedResource)
            {
                return((input, parent) =>
                {
                    Action <object> action = value => setter(parent, value);
                    input.ReadSharedResource(action);
                });
            }

            // We need to have a reader at this point.
            var reader = manager.GetTypeReader(elementType);

            if (reader == null)
            {
                if (elementType == typeof(System.Array))
                {
                    reader = new ArrayReader <Array>();
                }
                else
                {
                    throw new ContentLoadException(string.Format("Content reader could not be found for {0} type.", elementType.FullName));
                }
            }

            // We use the construct delegate to pick the correct existing
            // object to be the target of deserialization.
            Func <object, object> construct = parent => null;

            if (property != null && !property.CanWrite)
            {
                construct = parent => property.GetValue(parent, null);
            }

            return((input, parent) =>
            {
                var existing = construct(parent);
                var obj2 = input.ReadObject(reader, existing);
                setter(parent, obj2);
            });
        }