Ejemplo n.º 1
0
        internal ObjectLayer(ContentReader reader, ObjectRegistry registry)
            : base(reader)
        {
            _registry = registry;
            _objects = new List<ObjectInstance>();

            int objCount = reader.ReadInt32();
            for (int i = 0; i < objCount; i++) {
                int id = reader.ReadInt32();
                int dx = reader.ReadInt32();
                int dy = reader.ReadInt32();
                float rotation = reader.ReadSingle();
                float scaleX = reader.ReadSingle();
                float scaleY = reader.ReadSingle();

                PropertyCollection properties = new PropertyCollection(reader);

                _objects.Add(new ObjectInstance(_registry.GetObjectPool(id), id, dx, dy) {
                    Rotation = rotation,
                    ScaleX = scaleX,
                    ScaleY = scaleY,
                    Properties = properties,
                });
            }
        }
Ejemplo n.º 2
0
        internal Tileset(ContentReader reader)
            : this()
        {
            _manager = reader.ContentManager;

            int version = reader.ReadInt16();
            int id = reader.ReadInt16();

            TileWidth = reader.ReadInt16();
            TileHeight = reader.ReadInt16();
            string texAsset = reader.ReadString();

            Properties = new PropertyCollection(reader);

            int tileCount = reader.ReadInt16();
            for (int i = 0; i < tileCount; i++) {
                int tileId = reader.ReadInt16();
                int tileX = reader.ReadInt16();
                int tileY = reader.ReadInt16();

                Tile tile = new Tile(tileId, this, tileX, tileY)
                {
                    Properties = new PropertyCollection(reader),
                };
                _tiles.Add(tileId, tile);
            }

            _texture = _manager.Load<Texture2D>(texAsset);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the Wall class.
 /// Important: SetFromToVectors must be called afterwards!
 /// </summary>
 /// <param name="reader">The Content Type Reader.</param>
 public Wall(ContentReader reader)
 {
     fromIndex = reader.ReadInt32();
       toIndex = reader.ReadInt32();
       height = reader.ReadSingle();
       wallTexture = reader.ReadExternalReference<Texture2D>();
 }
Ejemplo n.º 4
0
        public static VGFontData Deserialize(ContentReader reader)
        {
            var data = new VGFontData
            {
                FillRule = (VGFillRule)reader.ReadByte(),
                EmSquareSize = reader.ReadSingle(),
                LeadingSize = reader.ReadSingle(),
                Extents = reader.ReadVector4(),
                Vertices = new StencilVertex[reader.ReadInt32()],
                Glyphs = new VGFontData.GlyphInfo[reader.ReadInt32()]
            };

            for (int i = 0; i < data.Vertices.Length; i++)
                data.Vertices[i] = StencilVertex.Deserialize(reader);

            for (int i = 0; i < data.Glyphs.Length; i++)
                data.Glyphs[i] = new VGFontData.GlyphInfo
                {
                    Character = reader.ReadChar(),
                    Offset = reader.ReadInt32(),
                    Triangles = reader.ReadInt32(),
                    Escape = new Vector2
                    {
                        X = reader.ReadSingle(),
                        Y = reader.ReadSingle()
                    }
                };

            data.Kerning = VGKerningTable.Deserialize(reader);
            return data;
        }
Ejemplo n.º 5
0
        private void ReadBones(ContentReader input)
        {
            ModelBone[] bones = new ModelBone[input.ReadInt32()];

            for (int i = 0; i < bones.Length; i++)
            {
                string name = input.ReadObject<string>();
                Matrix transform = input.ReadMatrix();
                bones[i] = new ModelBone(i, name, transform);
            }

            this.bones = new ModelBoneCollection(bones);

            foreach (ModelBone bone in bones)
            {
                ModelBone newParent = this.ReadBoneReference(input);
                int size = input.ReadInt32();
                ModelBone[] newChildren = new ModelBone[size];
                for (int j = 0; j < size; j++)
                {
                    newChildren[j] = this.ReadBoneReference(input);
                }
                bone.SetParentChildren(newParent, newChildren);
            }
        }
		/// <summary></summary><param name="reader"></param>
		public ParticleSystemCompiledShaderData(ContentReader reader)
		{
			this.CompressedShaderCode = reader.ReadBytes(reader.ReadInt32());
			this.ColourSamplerIndex = reader.ReadInt32();
			this.UserSamplerIndex = reader.ReadInt32();
			this.LifeSamplerIndex = reader.ReadInt32();
		}
Ejemplo n.º 7
0
        internal TileLayer(ContentReader reader, TileRegistry registry)
            : base(reader)
        {
            _registry = registry;

            TileWidth = reader.ReadInt16();
            TileHeight = reader.ReadInt16();
            Width = reader.ReadInt16();
            Height = reader.ReadInt16();

            _tiles = new TileGrid(Width, Height);

            int stackCount = reader.ReadInt32();
            for (int i = 0; i < stackCount; i++) {
                int dx = reader.ReadInt16();
                int dy = reader.ReadInt16();

                int tcount = reader.ReadInt16();
                Tile[] st = new Tile[tcount];

                for (int j = 0; j < tcount; j++) {
                    st[j] = _registry[reader.ReadInt16()];
                }

                _tiles[dx, dy] = new TileStack(st);
            }
        }
Ejemplo n.º 8
0
        public InstancedSkinnedModel(ContentReader reader)
        {
            _model = reader.ReadObject<Model>();
            _instancedSkinningData = new InstancedSkinningData(reader);

            _graphicsDevice = ((IGraphicsDeviceService)reader.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService))).GraphicsDevice;
        }
 internal OgmoLayerSettings(ContentReader reader)
 {
     this.GridColor = reader.ReadColor();
     this.GridDrawSize = reader.ReadInt32();
     this.GridSize = reader.ReadInt32();
     this.Name = reader.ReadString();
 }
Ejemplo n.º 10
0
        public XACTPatch(ContentReader input)
        {
            try
            {
                input.ReadByte();
                char[] header = input.ReadChars(4);
                if ( string.Compare( new string(header), "S**T" ) != 0 )
                    throw new Exception( "Caught Exception: Binary not in S**T format!" );
                int count = input.ReadInt32();
                if ( count > 128 ) count = 128; // Cap the maximum number of instruments
                for ( uint i = 0; i < count; ++i )
                {
                    _InstrumentInfo info = new _InstrumentInfo();
                    info.Name = input.ReadString();

                    byte flags = input.ReadByte();
                    info.Repeat = false; info.StretchRange = false;
                    if ((flags & 0x80) > 0) info.Repeat = true;      //if repeat
                    if ((flags & 0x40) > 0) info.StretchRange = true; //if range
                    int patchNumber = (int)(flags & 0x0F);
                    //info.PatchNumber = (byte)(flags & 0x0F);

                    info.AttackSpeed = input.ReadByte();
                    info.ReleaseSpeed = input.ReadByte();

                    m_Instruments[patchNumber] = info;
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
 internal OgmoGridLayer(ContentReader reader, OgmoLevel level)
     : base(reader)
 {
     OgmoGridLayerSettings settings = level.Project.GetLayerSettings<OgmoGridLayerSettings>(this.Name);
     if (settings.ExportAsObjects)
     {
         rectData = new List<Rectangle>();
         int objectCount = reader.ReadInt32();
         if (objectCount > 0)
         {
             for (int i = 0; i < objectCount; i++)
             {
                 Rectangle rect = Rectangle.Empty;
                 rect.X = reader.ReadInt32();
                 rect.Y = reader.ReadInt32();
                 rect.Width = reader.ReadInt32();
                 rect.Height = reader.ReadInt32();
                 rectData.Add(rect);
             }
         }
     }
     else
     {
         byte[] data = Convert.FromBase64String(reader.ReadString());
         string stringData = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
         int tx = level.Width / settings.GridSize;
         int ty = level.Height / settings.GridSize;
         rawData = new int[tx, ty];
         for (int y = 0; y < ty; y++)
             for (int x = 0; x < tx; x++)
                 rawData[x, y] = int.Parse(stringData[y * tx + x].ToString(), CultureInfo.InvariantCulture);
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the Tower class.
        /// </summary>
        /// <param name="reader">The Content Reader for Castle XML Files</param>
        public Tower(ContentReader reader)
        {
            id = reader.ReadInt32();
              hasCannon = reader.ReadBoolean();
              var position = reader.ReadObject<Vector2>();
              x = (int)position.X;
              y = (int)position.Y;
              height = reader.ReadSingle();
              corners = reader.ReadInt32();
              radius = reader.ReadSingle();
              coverRadius = reader.ReadSingle();
              coverHeight = reader.ReadSingle();
              viewDirection = new Vector3(x, coverHeight + 2, y + 1);

              wallTexture = reader.ReadExternalReference<Texture2D>();
              coverTexture = reader.ReadExternalReference<Texture2D>();

              ////InitTowerGraphics();

              if (HasCannon)
              {
            hasCannon = true;
            cannon = new Cannon(X, coverHeight, Y, null);
              }
        }
 internal OgmoTileLayerSettings(ContentReader reader)
     : base(reader)
 {
     this.ExportTileIDs = reader.ReadBoolean();
     this.ExportTileSize = reader.ReadBoolean();
     this.MultipleTilesets = reader.ReadBoolean();
 }
Ejemplo n.º 14
0
        public SkyBox(ContentReader input)
        {
            // Graphics Device-Instanz abrufen
              this.GraphicsDevice = ((IGraphicsDeviceService)input.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService))).GraphicsDevice;

              // Vertices einlesen und Vertex Buffer initialisieren
              VertexPositionTexture[] vertices = input.ReadObject<VertexPositionTexture[]>();
              this.vertexBuffer = new VertexBuffer(this.GraphicsDevice, typeof(VertexPositionTexture), vertices.Length, BufferUsage.None);
              this.vertexBuffer.SetData<VertexPositionTexture>(vertices);

              // Anzahl der Vertices speichern
              this.numVertices = vertices.Length;

              // Division durch 3 ergibt die Anzahl der Primitive, da eine Dreiecksliste verwendet wird
              this.numPrimitives = this.numPrimitives / 3;

              // Vertex-Beschreibung erzeugen
              this.vertexDeclaration = new VertexDeclaration(VertexPositionTexture.VertexDeclaration.GetVertexElements());

              // BasicEffect-Instanz erzeugen
              this.effect = new BasicEffect(this.GraphicsDevice);

              // Texturen einlesen
              this.frontTexture = input.ReadExternalReference<Texture2D>();
              this.backTexture = input.ReadExternalReference<Texture2D>();
              this.leftTexture = input.ReadExternalReference<Texture2D>();
              this.rightTexture = input.ReadExternalReference<Texture2D>();
              this.topTexture = input.ReadExternalReference<Texture2D>();
              this.bottomTexture = input.ReadExternalReference<Texture2D>();
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Constructs a new skinning data object.
        /// </summary>
        public InstancedSkinningData(ContentReader input)
        {
            this.texture = input.ReadObject<Texture2D>();
            this.animations = input.ReadObject<IDictionary<string, InstancedAnimationClip>>();

            Vector4[] data = new Vector4[this.texture.Width * this.texture.Height];
            this.texture.GetData<Vector4>(data);
        }
Ejemplo n.º 16
0
        internal static SkinnedModel Read(ContentReader input)
        {
            SkinnedModel skinnedModel = new SkinnedModel();

            skinnedModel.model = input.ReadObject<Model>();
            skinnedModel.ReadBones(input);
            skinnedModel.ReadAnimations(input);
            return skinnedModel;
        }
Ejemplo n.º 17
0
 private static VertexDeclaration[] ReadVertexDeclarations(ContentReader input)
 {
     int length = input.ReadInt32();
     VertexDeclaration[] declarationArray = new VertexDeclaration[length];
     for (int i = 0; i < length; i++)
     {
         declarationArray[i] = input.ReadObject<VertexDeclaration>();
     }
     return declarationArray;
 }
Ejemplo n.º 18
0
 internal static Model Read(ContentReader input)
 {
     Model model = new Model();
     model.ReadBones(input);
     VertexDeclaration[] vertexDeclarations = ReadVertexDeclarations(input);
     model.ReadMeshes(input, vertexDeclarations);
     model.root = model.ReadBoneReference(input);
     model.Tag = input.ReadObject<object>();
     return model;
 }
 internal OgmoProjectSettings(ContentReader reader)
 {
     this.Height = reader.ReadInt32();
     this.MaxHeight = reader.ReadInt32();
     this.MaxWidth = reader.ReadInt32();
     this.MinHeight = reader.ReadInt32();
     this.MinWidth = reader.ReadInt32();
     this.Width = reader.ReadInt32();
     this.WorkingDirectory = reader.ReadString();
 }
 internal OgmoTileset(ContentReader reader)
 {
     this.Name = reader.ReadString();
     this.Texture = reader.ReadExternalReference<Texture2D>();
     this.TextureFile = reader.ReadString();
     this.TileHeight = reader.ReadInt32();
     this.TileWidth = reader.ReadInt32();
     if (this.Texture != null)
         this.CreateSources();
 }
Ejemplo n.º 21
0
        /// <summary>
        /// ContentReaderからGraphicsDeviceを取得する
        /// </summary>
        public static GraphicsDevice GetGraphicsDevice( ContentReader input )
        {
            IServiceProvider serviceProvider = input.ContentManager.ServiceProvider;

              IGraphicsDeviceService deviceService =
              (IGraphicsDeviceService)serviceProvider.GetService(
                                      typeof( IGraphicsDeviceService ) );

              return deviceService.GraphicsDevice;
        }
Ejemplo n.º 22
0
 public static void DeveloperID(ref Dictionary<string, object> devTypes, ContentReader reader, object obj)
 {
     if (reader.ReadBoolean())
     {
         string key = reader.ReadString();
         if (devTypes != null)
         {
             devTypes.Add(key, obj);
         }
     }
 }
Ejemplo n.º 23
0
        internal Layer(ContentReader reader)
        {
            ScaleX = 1f;
            ScaleY = 1f;

            Id = reader.ReadInt16();
            Name = reader.ReadString();
            Visible = reader.ReadBoolean();
            Opacity = reader.ReadSingle();
            Properties = new PropertyCollection(reader);
        }
 internal OgmoTile(ContentReader reader, OgmoTileLayer layer)
 {
     this.Height = reader.ReadInt32();
     this.Position = reader.ReadVector2();
     this.SourceIndex = reader.ReadInt32();
     Vector2 offset = reader.ReadVector2();
     Point point = new Point((int)offset.X, (int)offset.Y);
     this.TextureOffset = point;
     string tilesetName = reader.ReadString();
     this.Tileset = layer.GetTileset(tilesetName);
     this.Width = reader.ReadInt32();
 }
        public InstancedSkinnedModel(ContentReader reader)
        {
            this.model = reader.ReadObject<Model>();
            this.instancedSkinningData = new InstancedSkinningData(reader);

            GraphicsDevice device = ((IGraphicsDeviceService)reader.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService))).GraphicsDevice;

            // Create InstancedSkinnedModelMeshes from the ModelMeshes
            foreach (ModelMesh mesh in this.model.Meshes)
            {
                meshes.Add(new InstancedSkinnedModelMesh(mesh, this.instancedSkinningData.AnimationTexture, device));
            }
        }
Ejemplo n.º 26
0
        internal InstancedModel( ContentReader input )
        {
            graphicsDevice = RenderHelper.GetGraphicsDevice( input );

              int partCount = input.ReadInt32();

              for ( int i = 0; i < partCount; i++ )
              {
            modelParts.Add( new InstancedModelPart( this, input, graphicsDevice ) );
              }

              Tag = input.ReadObject<object>();
        }
Ejemplo n.º 27
0
        public EntityGraphics(ContentReader reader)
        {
            id = reader.ReadInt32();
            width = reader.ReadInt32();
            height = reader.ReadInt32();
            frames = reader.ReadInt32();
            image = reader.ReadString();

            texture = reader.ContentManager.Load<Texture2D>(@"gfx\entities\" + image);

            modes = new string[texture.Height / height];
            for (int i = 0; i < modes.Length; ++i)
                modes[i] = reader.ReadString();
        }
Ejemplo n.º 28
0
        internal ObjectLayer(ContentReader reader, ObjectRegistry registry)
            : base(reader)
        {
            _registry = registry;
            _objects = new List<ObjectInstance>();

            int objCount = reader.ReadInt32();
            for (int i = 0; i < objCount; i++) {
                int dx = reader.ReadInt32();
                int dy = reader.ReadInt32();
                int id = reader.ReadInt16();

                _objects.Add(new ObjectInstance(_registry.GetObjectPool(id), id, dx, dy));
            }
        }
Ejemplo n.º 29
0
        private void ReadAnimations(ContentReader input)
        {
            int numAnimationClips = input.ReadInt32();
            Dictionary<string, AnimationClip> animationClipDictionary =
                new Dictionary<string, AnimationClip>();

            // Read all animation clips
            for (int i = 0; i < numAnimationClips; i++)
            {
                input.ReadSharedResource<AnimationClip>(
                    delegate(AnimationClip animationClip) { animationClipDictionary.Add(animationClip.Name, animationClip); });
            }

            animationClips = new AnimationClipDictionary(animationClipDictionary);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Constructor reads instanced model data from our custom XNB format.
        /// </summary>
        internal InstancedModelPart( ContentReader input, GraphicsDevice graphicsDevice )
        {
            this.graphicsDevice = graphicsDevice;

              // Load the model data.
              indexCount = input.ReadInt32();
              vertexCount = input.ReadInt32();
              vertexStride = input.ReadInt32();

              vertexDeclaration = input.ReadObject<VertexDeclaration>();
              vertexBuffer = input.ReadObject<VertexBuffer>();
              indexBuffer = input.ReadObject<IndexBuffer>();

              input.ReadSharedResource<Effect>( delegate( Effect value )
              {
            effect = value;

            // accessors
            EffectParameterColor = effect.Parameters["Color"];
            EffectParameterDiffuseMap = effect.Parameters["DiffuseMap"];
            EffectParameterSpecularPower = effect.Parameters["SpecularPower"];

            effectParameterView = effect.Parameters["View"];
            effectParameterProjection = effect.Parameters["Projection"];
            effectParameterEye = effect.Parameters["Eye"];
            effectParameterVertexCount = effect.Parameters["VertexCount"];
            effectParameterInstanceTransforms = effect.Parameters["InstanceTransforms"];
              } );

              // Work out how many shader instances we can fit into a single batch.
              int indexOverflowLimit = ushort.MaxValue / vertexCount;

              maxInstances = Math.Min( indexOverflowLimit, MaxShaderMatrices );

              // On Xbox, we must replicate several copies of our index buffer data for
              // the VFetch instancing technique. We could alternatively precompute this
              // in the content processor, but that would bloat the size of the XNB file.
              // It is more efficient to generate the repeated values at load time.
              //
              // We also require replicated index data for the Windows ShaderInstancing
              // technique, but this is computed lazily on Windows, so as to avoid
              // bloating the index buffer if it turns out that we only ever use the
              // HardwareInstancingTechnique (which does not require any repeated data).

              ReplicateIndexData();
        }
Ejemplo n.º 31
0
 protected internal override Plane Read(ContentReader input, Plane existingInstance)
 {
     existingInstance.Normal = input.ReadVector3();
     existingInstance.D      = input.ReadSingle();
     return(existingInstance);
 }
Ejemplo n.º 32
0
        private void Read(object parent, ContentReader input, MemberInfo member)
        {
            PropertyInfo property = member as PropertyInfo;
            FieldInfo    field    = member as FieldInfo;

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

            if (property != null && property.Name == "Item")
            {
#if WINRT
                var getMethod = property.GetMethod;
                var setMethod = property.SetMethod;
#else
                var getMethod = property.GetGetMethod();
                var setMethod = property.GetSetMethod();
#endif

                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;
                }
            }
#if WINRT
            Attribute attr = member.GetCustomAttribute(typeof(ContentSerializerIgnoreAttribute));
#else
            Attribute attr = Attribute.GetCustomAttribute(member, typeof(ContentSerializerIgnoreAttribute));
#endif
            if (attr != null)
            {
                return;
            }
#if WINRT
            Attribute attr2 = member.GetCustomAttribute(typeof(ContentSerializerAttribute));
#else
            Attribute attr2 = Attribute.GetCustomAttribute(member, typeof(ContentSerializerAttribute));
#endif
            bool isSharedResource = false;
            if (attr2 != null)
            {
                var cs = attr2 as ContentSerializerAttribute;
                isSharedResource = cs.SharedResource;
            }
            else
            {
                if (property != null)
                {
#if WINRT
                    if (property.GetMethod != null && !property.GetMethod.IsPublic)
                    {
                        return;
                    }
                    if (property.SetMethod != null && !property.SetMethod.IsPublic)
                    {
                        return;
                    }
#else
                    foreach (MethodInfo info in property.GetAccessors(true))
                    {
                        if (info.IsPublic == false)
                        {
                            return;
                        }
                    }
#endif
                }
                else
                {
                    if (!field.IsPublic)
                    {
                        return;
                    }
                }
            }
            ContentTypeReader reader = null;

            Type elementType = null;

            if (property != null)
            {
                reader = manager.GetTypeReader(elementType = property.PropertyType);
            }
            else
            {
                reader = manager.GetTypeReader(elementType = field.FieldType);
            }
            if (!isSharedResource)
            {
                object existingChildObject = CreateChildObject(property, field);
                object obj2;

                if (reader == null && elementType == typeof(object))
                {
                    /* Reading elements serialized as "object" */
                    obj2 = input.ReadObject <object>();
                }
                else
                {
                    /* Default */
                    obj2 = input.ReadObject(reader, existingChildObject);
                }

                if (property != null)
                {
                    property.SetValue(parent, obj2, null);
                }
                else
                {
                    // Private fields can be serialized if they have ContentSerializerAttribute added to them
                    if (field.IsPrivate == false || attr2 != null)
                    {
                        field.SetValue(parent, obj2);
                    }
                }
            }
            else
            {
                Action <object> action = delegate(object value)
                {
                    if (property != null)
                    {
                        property.SetValue(parent, value, null);
                    }
                    else
                    {
                        field.SetValue(parent, value);
                    }
                };
                input.ReadSharedResource(action);
            }
        }
Ejemplo n.º 33
0
        protected virtual void ReloadAsset <T>(string originalAssetName, T currentAsset)
        {
            string assetName = originalAssetName;

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentNullException("assetName");
            }
            if (disposed)
            {
                throw new ObjectDisposedException("ContentManager");
            }

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

            Stream stream = null;

            try
            {
                //try load it traditionally
                stream = OpenStream(assetName);

                // Try to load as XNB file
                try
                {
                    using (BinaryReader xnbReader = new BinaryReader(stream))
                    {
                        using (ContentReader reader = GetContentReaderFromXnb(assetName, ref stream, xnbReader, null))
                        {
                            reader.InitializeTypeReaders();
                            reader.ReadObject <T>(currentAsset);
                            reader.ReadSharedResources();
                        }
                    }
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }
            catch (ContentLoadException)
            {
                // Try to reload as a non-xnb file.
                // Just textures supported for now.

                assetName = TitleContainer.GetFilename(Path.Combine(RootDirectory, assetName));

                assetName = Normalize <T>(assetName);

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

            object result = null;

            // FIXME: Should this block be here? -flibit
            if (graphicsDeviceService == null)
            {
                graphicsDeviceService = ServiceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            Stream stream            = null;
            string modifiedAssetName = String.Empty;             // Will be used if we have to guess a filename

            try
            {
                stream = OpenStream(assetName);
            }
            catch (Exception e)
            {
                // Okay, so we couldn't open it. Maybe it needs a different extension?
                // FIXME: This only works for files on the disk, what about custom streams? -flibit
                modifiedAssetName = FileHelpers.NormalizeFilePathSeparators(
                    Path.Combine(RootDirectoryFullPath, assetName)
                    );
                if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Texture))
                {
                    modifiedAssetName = Texture2DReader.Normalize(modifiedAssetName);
                }
                else if ((typeof(T) == typeof(SoundEffect)))
                {
                    modifiedAssetName = SoundEffectReader.Normalize(modifiedAssetName);
                }
                else if ((typeof(T) == typeof(Effect)))
                {
                    modifiedAssetName = EffectReader.Normalize(modifiedAssetName);
                }
                else if ((typeof(T) == typeof(Song)))
                {
                    modifiedAssetName = SongReader.Normalize(modifiedAssetName);
                }
                else if ((typeof(T) == typeof(Video)))
                {
                    modifiedAssetName = VideoReader.Normalize(modifiedAssetName);
                }

                // Did we get anything...?
                if (String.IsNullOrEmpty(modifiedAssetName))
                {
                    // Nope, nothing we're aware of!
                    throw new ContentLoadException(
                              "Could not load asset " + assetName + "! Error: " + e.Message,
                              e
                              );
                }

                stream = TitleContainer.OpenStream(modifiedAssetName);
            }

            // Check for XNB header
            stream.Read(xnbHeader, 0, xnbHeader.Length);
            if (xnbHeader[0] == 'X' &&
                xnbHeader[1] == 'N' &&
                xnbHeader[2] == 'B' &&
                targetPlatformIdentifiers.Contains((char)xnbHeader[3]))
            {
                using (BinaryReader xnbReader = new BinaryReader(stream))
                    using (ContentReader reader = GetContentReaderFromXnb(assetName, ref stream, xnbReader, recordDisposableObject))
                    {
                        result = reader.ReadAsset <T>();
                        GraphicsResource resource = result as GraphicsResource;
                        if (resource != null)
                        {
                            resource.Name = assetName;
                        }
                    }
            }
            else
            {
                // It's not an XNB file. Try to load as a raw asset instead.

                // FIXME: Assuming seekable streams! -flibit
                stream.Seek(0, SeekOrigin.Begin);

                if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Texture))
                {
                    Texture2D texture = Texture2D.FromStream(
                        graphicsDeviceService.GraphicsDevice,
                        stream
                        );
                    texture.Name = assetName;
                    result       = texture;
                }
                else if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = SoundEffect.FromStream(stream);
                }
                else if ((typeof(T) == typeof(Effect)))
                {
                    byte[] data = new byte[stream.Length];
                    stream.Read(data, 0, (int)stream.Length);
                    result = new Effect(graphicsDeviceService.GraphicsDevice, data);
                }
                else if ((typeof(T) == typeof(Song)))
                {
                    // FIXME: Not using the stream! -flibit
                    result = new Song(modifiedAssetName);
                }
                else if ((typeof(T) == typeof(Video)))
                {
                    // FIXME: Not using the stream! -flibit
                    result = new Video(modifiedAssetName);
                }
                else
                {
                    stream.Close();
                    throw new ContentLoadException("Could not load " + assetName + " asset!");
                }

                /* Because Raw Assets skip the ContentReader step, they need to have their
                 * disposables recorded here. Doing it outside of this catch will
                 * result in disposables being logged twice.
                 */
                IDisposable disposableResult = result as IDisposable;
                if (disposableResult != null)
                {
                    if (recordDisposableObject != null)
                    {
                        recordDisposableObject(disposableResult);
                    }
                    else
                    {
                        disposableAssets.Add(disposableResult);
                    }
                }

                /* Because we're not using a BinaryReader for raw assets, we
                 * need to close the stream ourselves.
                 * -flibit
                 */
                stream.Close();
            }

            return((T)result);
        }
Ejemplo n.º 35
0
        private ContentReader GetContentReaderFromXnb(string originalAssetName, ref Stream stream, BinaryReader xnbReader, Action <IDisposable> recordDisposableObject)
        {
            byte version    = xnbReader.ReadByte();
            byte flags      = xnbReader.ReadByte();
            bool compressed = (flags & 0x80) != 0;

            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();
                MemoryStream decompressedStream = new MemoryStream(
                    new byte[decompressedSize],
                    0,
                    decompressedSize,
                    true,
                    true                     // This MUST be true! We may need GetBuffer()!
                    );
                // Default window size for XNB encoded files is 64Kb (need 16 bits to represent it)
                LzxDecoder dec          = new LzxDecoder(16);
                int        decodedBytes = 0;
                long       startPos     = stream.Position;
                long       pos          = startPos;

                while (pos - startPos < compressedSize)
                {
                    /* The compressed stream is separated into blocks that will
                     * decompress into 32kB or some other size if specified.
                     * Normal, 32kB output blocks will have a short indicating
                     * the size of the block before the block starts. Blocks
                     * that have a defined output will be preceded by a byte of
                     * value 0xFF (255), then a short indicating the output size
                     * and another for the block size. All shorts for these
                     * cases are encoded in big endian order.
                     */
                    int hi         = stream.ReadByte();
                    int lo         = stream.ReadByte();
                    int block_size = (hi << 8) | lo;
                    int frame_size = 0x8000;                     // Frame size is 32kB by default
                    // Does this block define a frame size?
                    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;
                    }
                    // Either says there is nothing to decode
                    if (block_size == 0 || frame_size == 0)
                    {
                        break;
                    }
                    dec.Decompress(stream, block_size, decompressedStream, frame_size);
                    pos          += block_size;
                    decodedBytes += frame_size;

                    /* Reset the position of the input just in case the bit
                     * buffer read in some unused bytes.
                     */
                    stream.Seek(pos, SeekOrigin.Begin);
                }
                if (decompressedStream.Position != decompressedSize)
                {
                    throw new ContentLoadException(
                              "Decompression of " + originalAssetName + " failed. "
                              );
                }
                decompressedStream.Seek(0, SeekOrigin.Begin);
                reader = new ContentReader(
                    this,
                    decompressedStream,
                    graphicsDeviceService.GraphicsDevice,
                    originalAssetName,
                    version,
                    recordDisposableObject
                    );
            }
            else
            {
                reader = new ContentReader(
                    this,
                    stream,
                    graphicsDeviceService.GraphicsDevice,
                    originalAssetName,
                    version,
                    recordDisposableObject
                    );
            }
            return(reader);
        }
Ejemplo n.º 36
0
 protected internal override short Read(ContentReader input, short existingInstance)
 {
     return(input.ReadInt16());
 }
Ejemplo n.º 37
0
 public ContentTypeReaderManager(ContentReader reader)
 {
     _reader = reader;
 }
Ejemplo n.º 38
0
 protected internal override char Read(ContentReader input, char existingInstance)
 {
     return(input.ReadChar());
 }
Ejemplo n.º 39
0
        public ContentTypeReader[] LoadAssetReaders(ContentReader reader)
        {
            // Dummy variables required for it to work on iDevices ** DO NOT DELETE **
            // This forces the classes not to be optimized out when deploying to iDevices
            ListReader <Char>         hCharListReader      = new ListReader <Char>();
            ListReader <Rectangle>    hRectangleListReader = new ListReader <Rectangle>();
            ListReader <Vector3>      hVector3ListReader   = new ListReader <Vector3>();
            ListReader <StringReader> hStringListReader    = new ListReader <StringReader>();
            SpriteFontReader          hSpriteFontReader    = new SpriteFontReader();
            Texture2DReader           hTexture2DReader     = new Texture2DReader();
            CharReader      hCharReader      = new CharReader();
            RectangleReader hRectangleReader = new RectangleReader();
            StringReader    hStringReader    = new StringReader();
            Vector3Reader   hVector3Reader   = new Vector3Reader();

            int numberOfReaders;

            ContentTypeReader[] contentReaders;

            // The first 4 bytes should be the "XNBw" header. i use that to detect an invalid file
            byte[] headerBuffer = new byte[4];
            reader.Read(headerBuffer, 0, 4);
            string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 4);

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

            // I think these two bytes are some kind of version number. Either for the XNB file or the type readers
            byte version    = reader.ReadByte();
            byte compressed = reader.ReadByte();
            // The next int32 is the length of the XNB file
            int xnbLength = reader.ReadInt32();

            if (compressed != 0)
            {
                throw new NotImplementedException("MonoGame cannot read compressed XNB files. Please use the XNB files from the Debug build of your XNA game instead. If someone wants to contribute decompression logic, that would be fantastic.");
            }

            // The next byte i read tells me the number of content readers in this XNB file
            numberOfReaders = reader.ReadByte();
            contentReaders  = new ContentTypeReader[numberOfReaders];

            // For each reader in the file, we read out the length of the string which contains the type of the reader,
            // then we read out the string. Finally we instantiate an instance of that reader using reflection
            for (int i = 0; i < numberOfReaders; i++)
            {
                // This string tells us what reader we need to decode the following data
                // string readerTypeString = reader.ReadString();
                string originalReaderTypeString = reader.ReadString();

                // Need to resolve namespace differences
                string readerTypeString = originalReaderTypeString;

                /*if(readerTypeString.IndexOf(", Microsoft.Xna.Framework") != -1)
                 * {
                 *      string[] tokens = readerTypeString.Split(new char[] { ',' });
                 *      readerTypeString = "";
                 *      for(int j = 0; j < tokens.Length; j++)
                 *      {
                 *              if(j != 0)
                 *                      readerTypeString += ",";
                 *
                 *              if(j == 1)
                 *                      readerTypeString += " Microsoft.Xna.Framework";
                 *              else
                 *                      readerTypeString += tokens[j];
                 *      }
                 *      readerTypeString = readerTypeString.Replace(", Microsoft.Xna.Framework", "@");
                 * }*/

                if (readerTypeString.Contains("PublicKey"))
                {
                    readerTypeString = readerTypeString.Split(new char[] { '[', '[' })[0] + "[" +
                                       readerTypeString.Split(new char[] { '[', '[' })[2].Split(',')[0] + "]";
                }

                readerTypeString = readerTypeString.Replace("Microsoft.Xna.Framework", "Microsoft.Xna.Framework");
                Type l_readerType = Type.GetType(readerTypeString);

                if (l_readerType != null)
                {
                    contentReaders[i] = (ContentTypeReader)Activator.CreateInstance(l_readerType, true);
                }
                else
                {
                    throw new ContentLoadException("Could not find matching content reader of type " + originalReaderTypeString);
                }



                // I think the next 4 bytes refer to the "Version" of the type reader,
                // although it always seems to be zero
                int typeReaderVersion = reader.ReadInt32();
            }

            return(contentReaders);
        }
 protected internal override BoundingFrustum Read(ContentReader input, BoundingFrustum existingInstance)
 {
     return(new BoundingFrustum(input.ReadMatrix()));
 }
Ejemplo n.º 41
0
        protected T ReadAsset <T>(string assetName, Action <IDisposable> recordDisposableObject)
        {
            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentNullException("assetName");
            }
            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");
                }
            }

            Stream stream = null;

            try
            {
                //try load it traditionally
                stream = OpenStream(assetName);

                // Try to load as XNB file
                try
                {
                    using (BinaryReader xnbReader = new BinaryReader(stream))
                    {
                        using (ContentReader reader = GetContentReaderFromXnb(assetName, ref stream, xnbReader, recordDisposableObject))
                        {
                            result = reader.ReadAsset <T>();
                            if (result is GraphicsResource)
                            {
                                ((GraphicsResource)result).Name = originalAssetName;
                            }
                        }
                    }
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }
            catch (ContentLoadException ex)
            {
                //MonoGame try to load as a non-content file

                assetName = TitleContainer.GetFilename(Path.Combine(RootDirectory, assetName));

                assetName = Normalize <T>(assetName);

                if (string.IsNullOrEmpty(assetName))
                {
                    throw new ContentLoadException("Could not load " + originalAssetName + " asset as a non-content file!", ex);
                }

                result = ReadRawAsset <T>(assetName, originalAssetName);

                // Because Raw Assets skip the ContentReader step, they need to have their
                // disopsables recorded here. Doing it outside of this catch will
                // result in disposables being logged twice.
                if (result is IDisposable)
                {
                    if (recordDisposableObject != null)
                    {
                        recordDisposableObject(result as IDisposable);
                    }
                    else
                    {
                        disposableAssets.Add(result as IDisposable);
                    }
                }
            }

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

            return((T)result);
        }
Ejemplo n.º 42
0
        private ContentReader GetContentReaderFromXnb(string originalAssetName, ref Stream stream, BinaryReader xnbReader, Action <IDisposable> recordDisposableObject)
        {
            // The first 4 bytes should be the "XNB" header. i use that to detect an invalid file
            byte x        = xnbReader.ReadByte();
            byte n        = xnbReader.ReadByte();
            byte b        = xnbReader.ReadByte();
            byte platform = xnbReader.ReadByte();

            if (x != 'X' || n != 'N' || b != 'B' ||
                !(targetPlatformIdentifiers.Contains((char)platform)))
            {
                throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?");
            }

            byte version = xnbReader.ReadByte();
            byte flags   = xnbReader.ReadByte();

            bool compressedLzx = (flags & ContentCompressedLzx) != 0;
            bool compressedLz4 = (flags & ContentCompressedLz4) != 0;

            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 (compressedLzx || compressedLz4)
            {
                // Decompress the xnb
                int          decompressedSize   = xnbReader.ReadInt32();
                MemoryStream decompressedStream = null;

                if (compressedLzx)
                {
                    //thanks to ShinAli (https://bitbucket.org/alisci01/xnbdecompressor)
                    // default window size for XNB encoded files is 64Kb (need 16 bits to represent it)
                    LzxDecoder dec = new LzxDecoder(16);
                    decompressedStream = new MemoryStream(decompressedSize);
                    int  compressedSize = xnbLength - 14;
                    long startPos       = stream.Position;
                    long pos            = startPos;

                    while (pos - startPos < compressedSize)
                    {
                        // the compressed stream is seperated into blocks that will decompress
                        // into 32Kb or some other size if specified.
                        // normal, 32Kb output blocks will have a short indicating the size
                        // of the block before the block starts
                        // blocks that have a defined output will be preceded by a byte of value
                        // 0xFF (255), then a short indicating the output size and another
                        // for the block size
                        // all shorts for these cases are encoded in big endian order
                        int hi         = stream.ReadByte();
                        int lo         = stream.ReadByte();
                        int block_size = (hi << 8) | lo;
                        int frame_size = 0x8000; // frame size is 32Kb by default
                        // does this block define a frame size?
                        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;
                        }

                        // either says there is nothing to decode
                        if (block_size == 0 || frame_size == 0)
                        {
                            break;
                        }

                        dec.Decompress(stream, block_size, decompressedStream, frame_size);
                        pos += block_size;

                        // reset the position of the input just incase the bit buffer
                        // read in some unused bytes
                        stream.Seek(pos, SeekOrigin.Begin);
                    }

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

                    decompressedStream.Seek(0, SeekOrigin.Begin);
                }
                else if (compressedLz4)
                {
                    // Decompress to a byte[] because Windows 8 doesn't support MemoryStream.GetBuffer()
                    var buffer = new byte[decompressedSize];
                    using (var decoderStream = new Lz4DecoderStream(stream))
                    {
                        if (decoderStream.Read(buffer, 0, buffer.Length) != decompressedSize)
                        {
                            throw new ContentLoadException("Decompression of " + originalAssetName + " failed. ");
                        }
                    }
                    // Creating the MemoryStream with a byte[] shares the buffer so it doesn't allocate any more memory
                    decompressedStream = new MemoryStream(buffer);
                }

                reader = new ContentReader(this, decompressedStream, this.graphicsDeviceService.GraphicsDevice,
                                           originalAssetName, version, recordDisposableObject);
            }
            else
            {
                reader = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice,
                                           originalAssetName, version, recordDisposableObject);
            }
            return(reader);
        }