/// <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);
        }
        protected internal override SpriteFont Read(
            ContentReader input,
            SpriteFont existingInstance
            )
        {
            if (existingInstance != null)
            {
                // Read the texture into the existing texture instance
                input.ReadObject <Texture2D>(existingInstance.textureValue);

                /* Discard the rest of the SpriteFont data as we are only
                 * reloading GPU resources for now
                 */
                input.ReadObject <List <Rectangle> >();
                input.ReadObject <List <Rectangle> >();
                input.ReadObject <List <char> >();
                input.ReadInt32();
                input.ReadSingle();
                input.ReadObject <List <Vector3> >();
                if (input.ReadBoolean())
                {
                    input.ReadChar();
                }
                return(existingInstance);
            }
            else
            {
                // Create a fresh SpriteFont instance
                Texture2D        texture        = input.ReadObject <Texture2D>();
                List <Rectangle> glyphs         = input.ReadObject <List <Rectangle> >();
                List <Rectangle> cropping       = input.ReadObject <List <Rectangle> >();
                List <char>      charMap        = input.ReadObject <List <char> >();
                int            lineSpacing      = input.ReadInt32();
                float          spacing          = input.ReadSingle();
                List <Vector3> kerning          = input.ReadObject <List <Vector3> >();
                char?          defaultCharacter = null;
                if (input.ReadBoolean())
                {
                    defaultCharacter = new char?(input.ReadChar());
                }
                return(new SpriteFont(
                           texture,
                           glyphs,
                           cropping,
                           charMap,
                           lineSpacing,
                           spacing,
                           kerning,
                           defaultCharacter
                           ));
            }
        }
Beispiel #3
0
        protected internal override Dictionary <TKey, TValue> Read(ContentReader input, Dictionary <TKey, TValue> existingInstance)
        {
            int count = input.ReadInt32();
            Dictionary <TKey, TValue> dictionary = existingInstance;

            if (dictionary == null)
            {
                dictionary = new Dictionary <TKey, TValue>(count);
            }
            else
            {
                dictionary.Clear();
            }

            for (int i = 0; i < count; i++)
            {
                TKey   key;
                TValue value;

#if WINRT
                if (keyType.GetTypeInfo().IsValueType)
#else
                if (keyType.IsValueType)
#endif
                {
                    key = input.ReadObject <TKey>(keyReader);
                }
                else
                {
                    int readerType = input.ReadByte();
                    key = input.ReadObject <TKey>(input.TypeReaders[readerType - 1]);
                }

#if WINRT
                if (valueType.GetTypeInfo().IsValueType)
#else
                if (valueType.IsValueType)
#endif
                {
                    value = input.ReadObject <TValue>(valueReader);
                }
                else
                {
                    int readerType = input.ReadByte();
                    value = input.ReadObject <TValue>(input.TypeReaders[readerType - 1]);
                }

                dictionary.Add(key, value);
            }
            return(dictionary);
        }
Beispiel #4
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);
            }
        }
Beispiel #5
0
        protected internal override EffectMaterial Read(ContentReader input, EffectMaterial existingInstance)
        {
            var effect         = input.ReadExternalReference <Effect> ();
            var effectMaterial = new EffectMaterial(effect);

            var dict = input.ReadObject <Dictionary <string, object> > ();

            foreach (KeyValuePair <string, object> item in dict)
            {
                var parameter = effectMaterial.Parameters [item.Key];
                if (parameter != null)
                {
                    if (typeof(Texture).IsAssignableFrom(item.Value.GetType()))
                    {
                        parameter.SetValue((Texture)item.Value);
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
                else
                {
#if DEBUG
                    Console.WriteLine("No parameter " + item.Key);
#endif
                }
            }


            return(effectMaterial);
        }
Beispiel #6
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);
              }
        }
        public InstancedSkinnedModel(ContentReader reader)
        {
            _model = reader.ReadObject<Model>();
            _instancedSkinningData = new InstancedSkinningData(reader);

            _graphicsDevice = ((IGraphicsDeviceService)reader.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService))).GraphicsDevice;
        }
Beispiel #8
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>();
        }
Beispiel #9
0
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
            var path = input.ReadString();

            if (!String.IsNullOrEmpty(path))
            {
#if WINRT
                const char notSeparator = '/';
                const char separator    = '\\';
#else
                const char notSeparator = '\\';
                var        separator    = Path.DirectorySeparatorChar;
#endif
                path = path.Replace(notSeparator, separator);

                // Get a uri for the asset path using the file:// schema and no host
                var src = new Uri("file:///" + input.AssetName.Replace(notSeparator, separator));

                // Add the relative path to the external reference
                var dst = new Uri(src, path);

                // The uri now contains the path to the external reference within the content manager
                // Get the local path and skip the first character (the path separator)
                path = dst.LocalPath.Substring(1);

                // Adds the ContentManager's RootDirectory
                path = Path.Combine(input.ContentManager.RootDirectoryFullPath, path);
            }

            var durationMs = input.ReadObject <int>();

            return(new Song(path, durationMs));
        }
Beispiel #10
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 to 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.
                assetName = FileHelpers.NormalizeFilePathSeparators(
                    Path.Combine(RootDirectoryFullPath, assetName)
                    );
                assetName = Normalize <T>(assetName);
                ReloadRawAsset(currentAsset, assetName, originalAssetName);
            }
        }
Beispiel #11
0
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
            string path3    = input.ReadString();
            string filename = TitleContainer.GetFilename(Path.Combine(input.ContentManager.RootDirectory, input.ContentManager.CurrentAssetDirectory, path3));

            input.ReadObject <int>();
            return(new Song(filename));
        }
        /// <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();
        }
Beispiel #13
0
 protected internal override T?Read(ContentReader input, T?existingInstance)
 {
     if (input.ReadBoolean())
     {
         return(input.ReadObject <T>(elementReader));
     }
     return(null);
 }
Beispiel #14
0
        internal static SkinnedModel Read(ContentReader input)
        {
            SkinnedModel skinnedModel = new SkinnedModel();

            skinnedModel.model = input.ReadObject<Model>();
            skinnedModel.ReadBones(input);
            skinnedModel.ReadAnimations(input);
            return skinnedModel;
        }
Beispiel #15
0
        protected internal override List <T> Read(ContentReader input, List <T> existingInstance)
        {
            int      capacity = input.ReadInt32();
            List <T> list     = existingInstance ?? new List <T>(capacity);

            for (int index = 0; index < capacity; ++index)
            {
                if (typeof(T).IsValueType)
                {
                    list.Add(input.ReadObject <T>(this.elementReader));
                }
                else
                {
                    int num = (int)input.ReadByte();
                    list.Add(input.ReadObject <T>(input.TypeReaders[num - 1]));
                }
            }
            return(list);
        }
Beispiel #16
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;
 }
        protected internal override Dictionary <TKey, TValue> Read(ContentReader input, Dictionary <TKey, TValue> existingInstance)
        {
            int count = input.ReadInt32();
            Dictionary <TKey, TValue> dictionary = existingInstance;

            if (dictionary == null)
            {
                dictionary = new Dictionary <TKey, TValue>(count);
            }
            else
            {
                dictionary.Clear();
            }

            for (int i = 0; i < count; i++)
            {
                TKey   key;
                TValue value;

                if (ReflectionHelpers.IsValueType(keyType))
                {
                    key = input.ReadObject <TKey>(keyReader);
                }
                else
                {
                    var readerType = input.Read7BitEncodedInt();
                    key = readerType > 0 ? input.ReadObject <TKey>(input.TypeReaders[readerType - 1]) : default(TKey);
                }

                if (ReflectionHelpers.IsValueType(valueType))
                {
                    value = input.ReadObject <TValue>(valueReader);
                }
                else
                {
                    var readerType = input.Read7BitEncodedInt();
                    value = readerType > 0 ? input.ReadObject <TValue>(input.TypeReaders[readerType - 1]) : default(TValue);
                }

                dictionary.Add(key, value);
            }
            return(dictionary);
        }
Beispiel #18
0
        protected internal override SpriteFont Read(ContentReader input, SpriteFont existingInstance)
        {
            Texture2D texture = input.ReadObject <Texture2D>();

            texture.IsSpriteFontTexture = true;
            List <Rectangle> glyphs         = input.ReadObject <List <Rectangle> >();
            List <Rectangle> cropping       = input.ReadObject <List <Rectangle> >();
            List <char>      charMap        = input.ReadObject <List <char> >();
            int            lineSpacing      = input.ReadInt32();
            float          spacing          = input.ReadSingle();
            List <Vector3> kerning          = input.ReadObject <List <Vector3> >();
            char?          defaultCharacter = null;

            if (input.ReadBoolean())
            {
                defaultCharacter = new char?(input.ReadChar());
            }
            return(new SpriteFont(texture, glyphs, cropping, charMap, lineSpacing, spacing, kerning, defaultCharacter));
        }
        internal static AnimationClip Read(ContentReader input)
        {
            string animationName = input.ReadString();
            TimeSpan animationDuration = input.ReadObject<TimeSpan>();

            // Read animation clip channels
            Dictionary<string, AnimationChannel> animationChannelDictionary =
                new Dictionary<string, AnimationChannel>();

            int numAnimationChannels = input.ReadInt32();
            for (int i = 0; i < numAnimationChannels; i++)
            {
                string channelName = input.ReadString();

                // Read animation channel keyframes
                int numChannelKeyframes = input.ReadInt32();
                List<AnimationChannelKeyframe> keyframeList =
                    new List<AnimationChannelKeyframe>(numChannelKeyframes);

                for (int j = 0; j < numChannelKeyframes; j++)
                {
                    TimeSpan keyframeTime = input.ReadObject<TimeSpan>();

                    // Read keyframe pose
                    Pose keyframePose;
                    keyframePose.Translation = input.ReadVector3();
                    keyframePose.Orientation = input.ReadQuaternion();
                    keyframePose.Scale = input.ReadVector3();

                    keyframeList.Add(new AnimationChannelKeyframe(keyframeTime, keyframePose));
                }

                AnimationChannel animationChannel = new AnimationChannel(keyframeList);

                // Add the animation channel to the dictionary
                animationChannelDictionary.Add(channelName, animationChannel);
            }

            return
                new AnimationClip(animationName, animationDuration,
                    new AnimationChannelDictionary(animationChannelDictionary));
        }
Beispiel #20
0
 protected internal override T?Read(ContentReader input, T?existingInstance)
 {
     if (input.ReadBoolean())
     {
         return(new T?(input.ReadObject <T>(this.elementReader)));
     }
     else
     {
         return(new T?());
     }
 }
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
            string path = input.ReadString();

            // Songs don't have the full directory path in their .xnb. Build it.
            path = Path.Combine(input.ContentManager.RootDirectory, input.ContentManager.CurrentAssetDirectory, path);
            path = TitleContainer.GetFilename(path);

            /*int durationMS =*/ input.ReadObject <int>();

            return(new Song(path));
        }
Beispiel #22
0
        protected internal override Video Read(ContentReader input, Video existingInstance)
        {
            string path = input.ReadObject <string>();

            if (!string.IsNullOrEmpty(path))
            {
                // Add the ContentManager's RootDirectory
                var dirPath = Path.Combine(input.ContentManager.RootDirectoryFullPath, input.AssetName);

                // Resolve the relative path
                path = FileHelpers.ResolveRelativePath(dirPath, path);
            }

            var durationMS      = input.ReadObject <int>();
            var width           = input.ReadObject <int>();
            var height          = input.ReadObject <int>();
            var framesPerSecond = input.ReadObject <float>();
            var soundTrackType  = input.ReadObject <int>(); // 0 = Music, 1 = Dialog, 2 = Music and dialog

            return(new Video(path, durationMS)
            {
                Width = width,
                Height = height,
                FramesPerSecond = framesPerSecond,
                VideoSoundtrackType = (VideoSoundtrackType)soundTrackType
            });
        }
Beispiel #23
0
        protected internal override Video Read(
            ContentReader input,
            Video existingInstance
            )
        {
            string path = FileHelpers.ResolveRelativePath(
                Path.Combine(
                    input.ContentManager.RootDirectoryFullPath,
                    input.AssetName
                    ),
                input.ReadObject <string>()
                );

            /* The path string includes the ".wmv" extension. Let's see if this
             * file exists in a format we actually support...
             */
            path = Normalize(path.Substring(0, path.Length - 4));
            if (String.IsNullOrEmpty(path))
            {
                throw new ContentLoadException();
            }

            int   durationMS      = input.ReadObject <int>();
            int   width           = input.ReadObject <int>();
            int   height          = input.ReadObject <int>();
            float framesPerSecond = input.ReadObject <float>();
            VideoSoundtrackType soundTrackType = (VideoSoundtrackType)input.ReadObject <int>();

            return(new Video(path, durationMS, width, height, framesPerSecond, soundTrackType));
        }
Beispiel #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Castle"/> class.
        /// </summary>
        /// <param name="reader">The castle content reader</param>
        public Castle(ContentReader reader)
        {
            this.id = 0;

              if (reader == null)
              {
            throw new ArgumentNullException("reader");
              }

              this.name = reader.ReadString();
              this.price = reader.ReadInt32();

              var tempTowers = reader.ReadObject<Tower[]>();

              var sumX = 0.0f;
              var sumZ = 0.0f;

              this.towers = new Collection<Tower>();
              foreach (Tower t in tempTowers)
              {
            sumX += t.X;
            sumZ += t.Y;
            this.towers.Add(t);
              }

              this.walls = new List<Wall>();
              var tempWalls = reader.ReadObject<Wall[]>();
              foreach (var w in tempWalls)
              {
            w.SetFromToVectors(
            new Vector3(this.towers[w.FromIndex].X, 0.0f, this.towers[w.FromIndex].Y),
            new Vector3(this.towers[w.ToIndex].X, 0.0f, this.towers[w.ToIndex].Y));

            this.walls.Add(w);
              }

              this.center = new Vector3(sumX / this.towers.Count, 0.0f, sumZ / this.towers.Count);
              this.currentTower = 0;
        }
Beispiel #25
0
        protected internal override T[] Read(ContentReader input, T[] existingInstance)
        {
            uint num1 = input.ReadUInt32();

            T[] objArray = existingInstance ?? new T[(IntPtr)num1];
            if (typeof(T).IsValueType)
            {
                for (uint index = 0U; index < num1; ++index)
                {
                    objArray[(IntPtr)index] = input.ReadObject <T>(this.elementReader);
                }
            }
            else
            {
                for (uint index = 0U; index < num1; ++index)
                {
                    int num2 = input.Read7BitEncodedInt();
                    objArray[(IntPtr)index] = num2 > 0 ? input.ReadObject <T>(input.TypeReaders[num2 - 1]) : default(T);
                }
            }
            return(objArray);
        }
        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));
            }
        }
Beispiel #27
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>();
        }
Beispiel #28
0
        protected internal override List <T> Read(ContentReader input, List <T> existingInstance)
        {
            int      count = input.ReadInt32();
            List <T> list  = existingInstance;

            if (list == null)
            {
                list = new List <T>(count);
            }
            for (int i = 0; i < count; i++)
            {
                if (ReflectionHelpers.IsValueType(typeof(T)))
                {
                    list.Add(input.ReadObject <T>(elementReader));
                }
                else
                {
                    var readerType = input.Read7BitEncodedInt();
                    list.Add(readerType > 0 ? input.ReadObject <T>(input.TypeReaders[readerType - 1]) : default(T));
                }
            }
            return(list);
        }
        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);
        }
Beispiel #30
0
        protected virtual void ReloadAsset <T>(string originalAssetName, T currentAsset)
        {
            string str = originalAssetName;

            if (string.IsNullOrEmpty(str))
            {
                throw new ArgumentNullException("assetName");
            }
            if (this.disposed)
            {
                throw new ObjectDisposedException("ContentManager");
            }
            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = this.serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }
            try
            {
                Stream stream = this.OpenStream(str);
                try
                {
                    using (BinaryReader xnbReader = new BinaryReader(stream))
                    {
                        using (ContentReader contentReaderFromXnb = this.GetContentReaderFromXnb(str, ref stream, xnbReader, (Action <IDisposable>)null))
                        {
                            contentReaderFromXnb.InitializeTypeReaders();
                            contentReaderFromXnb.ReadObject <T>(currentAsset);
                            contentReaderFromXnb.ReadSharedResources();
                        }
                    }
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }
            catch (ContentLoadException ex)
            {
                string assetName = this.Normalize <T>(TitleContainer.GetFilename(Path.Combine(this.RootDirectory, str)));
                this.ReloadRawAsset <T>(currentAsset, assetName, originalAssetName);
            }
        }
Beispiel #31
0
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
            string fileName = input.ReadString();

            if (!string.IsNullOrEmpty(fileName))
            {
                char   newChar     = Path.DirectorySeparatorChar;
                string relativeUri = fileName.Replace('\\', newChar);
                string path2       = new Uri(new Uri("file:///" + input.AssetName.Replace('\\', newChar)), relativeUri).LocalPath.Substring(1);
                fileName = Path.Combine(input.ContentManager.RootDirectoryFullPath, path2);
            }
            int durationMS = input.ReadObject <int>();

            return(new Song(fileName, durationMS));
        }
Beispiel #32
0
        internal InstancedModelPart( InstancedModel owner, ContentReader input,
            GraphicsDevice graphicsDevice)
        {
            this.owner = owner;

              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;
            effectVertexCountParam = Effect.Parameters["VertexCount"];
            effectViewParam = Effect.Parameters["View"];
            effectProjectionParam = Effect.Parameters["Projection"];
            effectEyeParam = Effect.Parameters["EyePosition"];
              } );

              originalVertexDeclaration = vertexDeclaration.GetVertexElements();
        }
Beispiel #33
0
        protected internal override T[] Read(ContentReader input, T[] existingInstance)
        {
            int count = input.ReadInt32();

            T[] array = existingInstance;
            if (array == null)
            {
                array = new T[count];
            }
            for (int i = 0; i < count; i++)
            {
                Type objectType = typeof(T);
                if (objectType.IsValueType)
                {
                    array[i] = input.ReadObject <T>(elementReader);
                }
                else
                {
                    int readerType = input.ReadByte();
                    array[i] = input.ReadObject <T>(input.TypeReaders[readerType - 1]);
                }
            }
            return(array);
        }
Beispiel #34
0
        protected internal override T[] Read(ContentReader input, T[] existingInstance)
        {
            uint count = input.ReadUInt32();

            T[] array = existingInstance;
            if (array == null)
            {
                array = new T[count];
            }

            if (typeof(T).IsValueType)
            {
                for (uint i = 0; i < count; i += 1)
                {
                    array[i] = input.ReadObject <T>(elementReader);
                }
            }
            else
            {
                for (uint i = 0; i < count; i += 1)
                {
                    int readerType = input.Read7BitEncodedInt();
                    if (readerType > 0)
                    {
                        array[i] = input.ReadObject <T>(
                            input.TypeReaders[readerType - 1]
                            );
                    }
                    else
                    {
                        array[i] = default(T);
                    }
                }
            }
            return(array);
        }
Beispiel #35
0
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
            var path = input.ReadString();

            if (!String.IsNullOrEmpty(path))
            {
                // Add the ContentManager's RootDirectory
                var dirPath = Path.Combine(input.ContentManager.RootDirectoryFullPath, input.AssetName);

                // Resolve the relative path
                path = FileHelpers.ResolveRelativePath(dirPath, path);
            }

            var durationMs = input.ReadObject <int>();

            return(new Song(path, durationMs));
        }
Beispiel #36
0
        protected internal override EffectMaterial Read(ContentReader input, EffectMaterial existingInstance)
        {
            EffectMaterial effectMaterial = new EffectMaterial(input.ReadExternalReference <Effect>());

            foreach (KeyValuePair <string, object> keyValuePair in input.ReadObject <Dictionary <string, object> >())
            {
                EffectParameter effectParameter = effectMaterial.Parameters[keyValuePair.Key];
                if (effectParameter != null)
                {
                    if (!typeof(Texture).IsAssignableFrom(keyValuePair.Value.GetType()))
                    {
                        throw new NotImplementedException();
                    }
                    effectParameter.SetValue((Texture)keyValuePair.Value);
                }
            }
            return(effectMaterial);
        }
Beispiel #37
0
        protected internal override Video Read(ContentReader input, Video existingInstance)
        {
            string path = input.ReadObject <string>();

            path = Path.Combine(input.ContentManager.RootDirectory, path);
            path = TitleContainer.GetFilename(path);

            /*int durationMS =*/ input.ReadObject <int>();
            /*int width =*/ input.ReadObject <int>();
            /*int height =*/ input.ReadObject <int>();
            /*float framesPerSecond =*/ input.ReadObject <Single>();
            /*int soundTrackType =*/ input.ReadObject <int>();   // 0 = Music, 1 = Dialog, 2 = Music and dialog
            return(new Video(path));
        }
Beispiel #38
0
        protected internal override Song Read(ContentReader input, Song existingInstance)
        {
            string path = input.ReadString();

            path = Path.Combine(input.ContentManager.RootDirectory, path);
            path = TitleContainer.GetFilename(path);

            /* The path string includes the ".wma" extension. Let's see if this
             * file exists in a format we actually support...
             */
            path = Normalize(Path.GetFileNameWithoutExtension(path));
            if (String.IsNullOrEmpty(path))
            {
                throw new ContentLoadException();
            }

            int durationMs = input.ReadObject <int>();

            return(new Song(path, durationMs));
        }
        protected internal override EffectMaterial Read(ContentReader input, EffectMaterial existingInstance)
        {
            var effect         = input.ReadExternalReference <Effect> ();
            var effectMaterial = new EffectMaterial(effect);

            var dict = input.ReadObject <Dictionary <string, object> > ();

            foreach (KeyValuePair <string, object> item in dict)
            {
                var parameter = effectMaterial.Parameters [item.Key];
                if (parameter != null)
                {
                    Type itemType = item.Value.GetType();

                    if (ReflectionHelpers.IsAssignableFromType(typeof(Texture), itemType))
                    {
                        parameter.SetValue((Texture)item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(int), itemType))
                    {
                        parameter.SetValue((int)item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(bool), itemType))
                    {
                        parameter.SetValue((bool)item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(float), itemType))
                    {
                        parameter.SetValue((float)item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(float []), itemType))
                    {
                        parameter.SetValue((float[])item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(Vector2), itemType))
                    {
                        parameter.SetValue((Vector2)item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(Vector2 []), itemType))
                    {
                        parameter.SetValue((Vector2 [])item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(Vector3), itemType))
                    {
                        parameter.SetValue((Vector3)item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(Vector3 []), itemType))
                    {
                        parameter.SetValue((Vector3 [])item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(Vector4), itemType))
                    {
                        parameter.SetValue((Vector4)item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(Vector4 []), itemType))
                    {
                        parameter.SetValue((Vector4 [])item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(Matrix), itemType))
                    {
                        parameter.SetValue((Matrix)item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(Matrix []), itemType))
                    {
                        parameter.SetValue((Matrix[])item.Value);
                    }
                    else if (ReflectionHelpers.IsAssignableFromType(typeof(Quaternion), itemType))
                    {
                        parameter.SetValue((Quaternion)item.Value);
                    }
                    else
                    {
                        throw new NotSupportedException("Parameter type is not supported");
                    }
                }
                else
                {
                    Debug.WriteLine("No parameter " + item.Key);
                }
            }

            return(effectMaterial);
        }
        internal static SkinnedModelBasicEffect Read(ContentReader input)
        {
            IGraphicsDeviceService graphicsDeviceService = (IGraphicsDeviceService)
                    input.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService));

            GraphicsDevice graphicsDevice = graphicsDeviceService.GraphicsDevice;
            SkinnedModelBasicEffect basicEffect = new SkinnedModelBasicEffect(graphicsDevice,
                (EffectPool)null);

            basicEffect.material.EmissiveColor = input.ReadVector3();
            basicEffect.material.DiffuseColor = input.ReadVector3();
            basicEffect.material.SpecularColor = input.ReadVector3();
            basicEffect.material.SpecularPower = input.ReadSingle();

            basicEffect.DiffuseMapEnabled = input.ReadBoolean();
            basicEffect.NormalMapEnabled = input.ReadBoolean();
            basicEffect.SpecularMapEnabled = input.ReadBoolean();
            basicEffect.DiffuseMap = input.ReadObject<Texture2D>(); ;
            basicEffect.NormalMap = input.ReadObject<Texture2D>(); ;
            basicEffect.SpecularMap = input.ReadObject<Texture2D>(); ;

            basicEffect.lightEnabled = false;
            basicEffect.enabledLights = EnabledLights.One;

            return basicEffect;
        }
Beispiel #41
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);
        }
        internal static SkinnedEffect Read(ContentReader input)
        {
            IGraphicsDeviceService graphicsDeviceService = (IGraphicsDeviceService)
                    input.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService));

            GraphicsDevice graphicsDevice = graphicsDeviceService.GraphicsDevice;

            SkinnedEffect basicEffect = new SkinnedEffect(graphicsDevice);


            input.ReadVector3();
            input.ReadVector3();
            input.ReadVector3();
            input.ReadSingle();

            input.ReadBoolean();
            input.ReadBoolean();
            input.ReadBoolean();
            input.ReadObject<Texture2D>(); 
            input.ReadObject<Texture2D>(); 
            input.ReadObject<Texture2D>(); 

            return basicEffect;
        }
Beispiel #43
0
        private void Read(object parent, ContentReader input, MemberInfo member)
        {
            PropertyInfo property = member as PropertyInfo;
            FieldInfo    field    = member as FieldInfo;

            if (property != (PropertyInfo)null && (!property.CanWrite || !property.CanRead))
            {
                return;
            }
            if (property != (PropertyInfo)null && property.Name == "Item")
            {
                MethodInfo getMethod = property.GetGetMethod();
                MethodInfo setMethod = property.GetSetMethod();
                if (getMethod != (MethodInfo)null && getMethod.GetParameters().Length > 0 || setMethod != (MethodInfo)null && setMethod.GetParameters().Length > 0)
                {
                    return;
                }
            }
            if (Attribute.GetCustomAttribute(member, typeof(ContentSerializerIgnoreAttribute)) != null)
            {
                return;
            }
            Attribute customAttribute = Attribute.GetCustomAttribute(member, typeof(ContentSerializerAttribute));
            bool      flag            = false;

            if (customAttribute != null)
            {
                flag = (customAttribute as ContentSerializerAttribute).SharedResource;
            }
            else if (property != (PropertyInfo)null)
            {
                foreach (MethodBase methodBase in property.GetAccessors(true))
                {
                    if (!methodBase.IsPublic)
                    {
                        return;
                    }
                }
            }
            else if (!field.IsPublic)
            {
                return;
            }
            Type type;
            ContentTypeReader typeReader = !(property != (PropertyInfo)null) ? this.manager.GetTypeReader(type = field.FieldType) : this.manager.GetTypeReader(type = property.PropertyType);

            if (!flag)
            {
                object childObject = ReflectiveReader <T> .CreateChildObject(property, field);

                object obj = typeReader != null || !(type == typeof(object)) ? input.ReadObject <object>(typeReader, childObject) : input.ReadObject <object>();
                if (property != (PropertyInfo)null)
                {
                    property.SetValue(parent, obj, (object[])null);
                }
                else
                {
                    if (field.IsPrivate && customAttribute == null)
                    {
                        return;
                    }
                    field.SetValue(parent, obj);
                }
            }
            else
            {
                Action <object> fixup = (Action <object>)(value =>
                {
                    if (property != (PropertyInfo)null)
                    {
                        property.SetValue(parent, value, (object[])null);
                    }
                    else
                    {
                        field.SetValue(parent, value);
                    }
                });
                input.ReadSharedResource <object>(fixup);
            }
        }
Beispiel #44
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;
 }
Beispiel #45
0
        internal Map(ContentReader reader)
        {
            // read in the basic map information
            Version = new Version(reader.ReadString());
            Orientation = (Orientation)reader.ReadByte();
            Width = reader.ReadInt32();
            Height = reader.ReadInt32();
            TileWidth = reader.ReadInt32();
            TileHeight = reader.ReadInt32();
            Properties = new PropertyCollection();
            Properties.Read(reader);

            // create a list for our tiles
            List<Tile> tiles = new List<Tile>();
            Tiles = new Collection<Tile>(tiles);

            // read in each tile set
            int numTileSets = reader.ReadInt32();
            for (int i = 0; i < numTileSets; i++)
            {
                // get the id and texture
                int firstId = reader.ReadInt32();
                string tilesetName = reader.ReadString();

                bool collisionSet = reader.ReadBoolean();

                Texture2D texture = reader.ReadExternalReference<Texture2D>();

                // read in each individual tile
                int numTiles = reader.ReadInt32();
                for (int j = 0; j < numTiles; j++)
                {
                    int id = firstId + j;

                    // Read the source rectangle from the file.
                    Rectangle source = reader.ReadObject<Rectangle>();

                    PropertyCollection props = new PropertyCollection();
                    props.Read(reader);

                    // Read in color data for collision purposes
                    // You'll probably want to limit this to just the tilesets that are used for collision
                    // I'm checking for the name of my tileset that contains wall tiles
                    // Color data takes up a fair bit of RAM
                    Color[] collisionData = null;
                    bool[] collisionBitData = null;
                    if (collisionSet)
                    {
                        int numOfBytes = TileWidth * TileHeight;
                        collisionData = new Color[numOfBytes];
                        collisionBitData = new bool[numOfBytes];

                        texture.GetData<Color>(
                            0,
                            source,
                            collisionData,
                            0,
                            numOfBytes
                        );

                        for (int col = 0; col < numOfBytes; col++)
                        {
                            if (collisionData[col].A > 0)
                            {
                                collisionBitData[col] = true;
                            }
                        }
                        collisionData = null;
                    }

                    Tile t = new Tile(texture, source, props, collisionBitData);
                    while (id >= tiles.Count)
                    {
                        tiles.Add(null);
                    }
                    tiles.Insert(id, t);
                }
            }

            // read in all the layers
            List<Layer> layers = new List<Layer>();
            Layers = new Collection<Layer>(layers);
            int numLayers = reader.ReadInt32();
            for (int i = 0; i < numLayers; i++)
            {
                Layer layer = null;

                // read generic layer data
                string type = reader.ReadString();
                string name = reader.ReadString();
                int width = reader.ReadInt32();
                int height = reader.ReadInt32();
                bool visible = reader.ReadBoolean();
                float opacity = reader.ReadSingle();
                PropertyCollection props = new PropertyCollection();
                props.Read(reader);

                // using the type, figure out which object to create
                if (type == "layer")
                {
                    int[] data = reader.ReadObject<int[]>();
                    layer = new TileLayer(name, width, height, visible, opacity, props, this, data);
                }
                else if (type == "objectgroup")
                {
                    List<MapObject> objects = new List<MapObject>();

                    // read in all of our objects
                    int numObjects = reader.ReadInt32();
                    for (int j = 0; j < numObjects; j++)
                    {
                        string objName = reader.ReadString();
                        string objType = reader.ReadString();
                        Rectangle objLoc = reader.ReadObject<Rectangle>();
                        List<Point> objPoints = reader.ReadObject<List<Point>>();
                        PropertyCollection objProps = new PropertyCollection();
                        objProps.Read(reader);

                        objects.Add(new MapObject(objName, objType, objLoc, objPoints, objProps));
                    }

                    layer = new MapObjectLayer(name, width, height, visible, opacity, props, objects);
                }
                else
                {
                    throw new Exception("Invalid type: " + type);
                }

                layers.Add(layer);
                namedLayers.Add(name, layer);
            }
        }
        private void loadMD3Data(ContentReader input, MD3Object m)
        {
            //load meshes
            m.meshes = new List<MD3SubMeshes>();
            int part = input.ReadInt32();
            if (part == 0)
                m.part = TMD3Part.HEAD;
            else if (part == 1)
                m.part = TMD3Part.LOWER;
            else
                m.part = TMD3Part.UPPER;

            m.num_frames = input.ReadInt32();
            int sub_meshes_count = input.ReadInt32();
            for (int i = 0; i < sub_meshes_count; ++i)
            {
                MD3SubMeshes sub_mesh = new MD3SubMeshes();
                sub_mesh.indices = new List<int>();
                sub_mesh.vertices = new List<Vector3>();
                sub_mesh.normals = new List<Vector3>();
                sub_mesh.text_coord = new List<Vector2>();
                sub_mesh.skins = new List<string>();
                sub_mesh.meshinfo.strName = input.ReadString();
                input.ReadObject<List<int>>(sub_mesh.indices);
                input.ReadObject<List<Vector3>>(sub_mesh.vertices);
                input.ReadObject<List<Vector3>>(sub_mesh.normals);
                input.ReadObject<List<Vector2>>(sub_mesh.text_coord);
                m.meshes.Add(sub_mesh);
            }

            //load tags
            m.tags = new List<MD3tag>();
            int tags_count = input.ReadInt32();
            for (int i = 0; i < tags_count; ++i)
            {
                MD3tag tag = new MD3tag();
                tag.strName = input.ReadString();
                tag.vPosition = input.ReadVector3();
                tag.rotation = input.ReadMatrix();
                m.tags.Add(tag);
            }
            //load bounding_boxes
            m.bounding_boxes = new List<BoundingBox>();
            int bb_count = input.ReadInt32();
            for (int i = 0; i < bb_count; ++i)
            {
                BoundingBox bb = new BoundingBox();
                bb.Min = input.ReadVector3();
                bb.Max = input.ReadVector3();
                m.bounding_boxes.Add(bb);
            }
        }
        internal static SkinnedModelBasicEffect Read(ContentReader input)
        {
            IGraphicsDeviceService graphicsDeviceService = (IGraphicsDeviceService)
                    input.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService));

            GraphicsDevice graphicsDevice = graphicsDeviceService.GraphicsDevice;

            //ResourceContentManager cnt = new ResourceContentManager(input.ContentManager.ServiceProvider, Resource1.ResourceManager);            z
#if WINDOWS           
            SkinnedModelBasicEffect basicEffect = new SkinnedModelBasicEffect(graphicsDevice, Resource1.SkinnedModelEffect);
#else
            SkinnedModelBasicEffect basicEffect = new SkinnedModelBasicEffect(graphicsDevice, Resource1.SkinnedModelEffect2);
#endif
            

            input.ReadVector3();
            input.ReadVector3();
            input.ReadVector3();
            input.ReadSingle();

            basicEffect.DiffuseMapEnabled = input.ReadBoolean();
            basicEffect.NormalMapEnabled = input.ReadBoolean();
            basicEffect.SpecularMapEnabled = input.ReadBoolean();
            basicEffect.DiffuseMap = input.ReadObject<Texture2D>(); ;
            basicEffect.NormalMap = input.ReadObject<Texture2D>(); ;
            basicEffect.SpecularMap = input.ReadObject<Texture2D>(); ;            

            return basicEffect;
        }
Beispiel #48
0
        /// <summary>
        /// The constructor reads model data from our custom XNB format.
        /// This is called by the CustomModelReader class, which is invoked
        /// whenever you ask the ContentManager to read a CustomModel object.
        /// </summary>
        internal CustomModel( ContentReader input )
        {
            int partCount = input.ReadInt32();

              for ( int i = 0; i < partCount; i++ )
              {
            ModelPart modelPart = new ModelPart();

            // Simple data types like integers can be read directly.
            modelPart.TriangleCount = input.ReadInt32();
            modelPart.VertexCount = input.ReadInt32();
            modelPart.VertexStride = input.ReadInt32();

            // These XNA Framework types can be read using the ReadObject method,
            // which calls into the appropriate ContentTypeReader for each type.
            // The framework provides built-in ContentTypeReader implementations
            // for important types such as vertex declarations, vertex buffers,
            // index buffers, effects, and textures.
            modelPart.VertexDeclaration = input.ReadObject<VertexDeclaration>();
            modelPart.VertexBuffer = input.ReadObject<VertexBuffer>();
            modelPart.IndexBuffer = input.ReadObject<IndexBuffer>();

            // Shared resources have to be read in a special way. Because the same
            // object can be referenced from many different parts of the file, the
            // actual object data is stored at the end of the XNB binary. When we
            // call ReadSharedResource we are just reading an ID that will later be
            // used to locate the actual data, so ReadSharedResource is unable to
            // directly return the shared instance. Instead, it takes in a delegate
            // parameter, and will call us back as soon as the shared value becomes
            // available. We use C# anonymous delegate syntax to store the value
            // into its final location.
            input.ReadSharedResource<Effect>( delegate( Effect effect )
            {
              //Effect effect = value.Clone( value.GraphicsDevice );
              if ( effect.Parameters["DiffuseMap"].GetValueTexture2D() != null )
              {
            if ( effect.Parameters["NormalMap"].GetValueTexture2D() != null )
            {
              effect.CurrentTechnique = effect.Techniques["NormalDiffuseColor"];
              modelPart.VertexDeclaration = new VertexDeclaration( effect.GraphicsDevice,
                                                                   VertexPositionNormalTextureTangentBinormal.VertexElements );
            }
            else
            {
              effect.CurrentTechnique = effect.Techniques["DiffuseColor"];
              modelPart.VertexDeclaration = new VertexDeclaration( effect.GraphicsDevice,
                                                                   VertexPositionNormalTexture.VertexElements );
            }
              }
              else
              {
            effect.CurrentTechnique = effect.Techniques["ColorDefault"];
            modelPart.VertexDeclaration = new VertexDeclaration( effect.GraphicsDevice,
                                                                 VertexPositionNormalColor.VertexElements );
              }
              modelPart.Effect = effect;
              modelPart.EffectParamWorld = modelPart.Effect.Parameters["World"];
              modelPart.EffectParamView = modelPart.Effect.Parameters["View"];
              modelPart.EffectParamProjection = modelPart.Effect.Parameters["Projection"];
              modelPart.EffectParamEye = modelPart.Effect.Parameters["Eye"];
              modelPart.EffectParamColor = modelPart.Effect.Parameters["Color"];
            } );

            modelParts.Add( modelPart );
              }
        }
Beispiel #49
0
 private void ReadMeshes(ContentReader input, VertexDeclaration[] vertexDeclarations)
 {
     int length = input.ReadInt32();
     ModelMesh[] meshes = new ModelMesh[length];
     for (int i = 0; i < length; i++)
     {
         string name = input.ReadObject<string>();
         ModelBone parentBone = this.ReadBoneReference(input);
         BoundingSphere boundingSphere = new BoundingSphere();
         boundingSphere.Center = input.ReadVector3();
         boundingSphere.Radius = input.ReadSingle();
         VertexBuffer vertexBuffer = input.ReadObject<VertexBuffer>();
         IndexBuffer indexBuffer = input.ReadObject<IndexBuffer>();
         object tag = input.ReadObject<object>();
         ModelMeshPart[] meshParts = ReadMeshParts(input, vertexBuffer, indexBuffer, vertexDeclarations);
         meshes[i] = new ModelMesh(name, parentBone, boundingSphere, vertexBuffer, indexBuffer, meshParts, tag);
     }
     this.meshes = new ModelMeshCollection(meshes);
 }
        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);
            }
        }
Beispiel #51
0
 private static ModelMeshPart[] ReadMeshParts(ContentReader input, VertexBuffer vertexBuffer, IndexBuffer indexBuffer, VertexDeclaration[] vertexDeclarations)
 {
     int length = input.ReadInt32();
     ModelMeshPart[] meshParts = new ModelMeshPart[length];
     for (int i = 0; i < length; i++)
     {
         int streamOffset = input.ReadInt32();
         int baseVertex = input.ReadInt32();
         int numVertices = input.ReadInt32();
         int startIndex = input.ReadInt32();
         int primitiveCount = input.ReadInt32();
         int index = input.ReadInt32();
         VertexDeclaration vertexDeclaration = vertexDeclarations[index];
         object tag = input.ReadObject<object>();
         meshParts[i] = new ModelMeshPart(streamOffset, baseVertex, numVertices, startIndex, primitiveCount, vertexBuffer, indexBuffer, vertexDeclaration, tag);
         int uniqueI = i;
         input.ReadSharedResource<Effect>(delegate(Effect effect)
         {
             meshParts[uniqueI].Effect = effect;
         });
     }   
     return meshParts;
  }
        internal static SkinnedModelBasicEffect Read(ContentReader input)
        {
            Effect effect = input.ReadObject<Effect>();

            SkinnedModelBasicEffect basicEffect = new SkinnedModelBasicEffect(effect);

            basicEffect.material.EmissiveColor = input.ReadVector3();
            basicEffect.material.DiffuseColor = input.ReadVector3();
            basicEffect.material.SpecularColor = input.ReadVector3();
            basicEffect.material.SpecularPower = input.ReadSingle();

            basicEffect.DiffuseMapEnabled = input.ReadBoolean();
            basicEffect.NormalMapEnabled = input.ReadBoolean();
            basicEffect.SpecularMapEnabled = input.ReadBoolean();

            basicEffect.DiffuseMap = input.ReadExternalReference<Texture2D>();
            basicEffect.NormalMap = input.ReadExternalReference<Texture2D>();
            basicEffect.SpecularMap = input.ReadExternalReference<Texture2D>();

            basicEffect.lightEnabled = false;
            basicEffect.enabledLights = EnabledLights.One;

            return basicEffect;
        }
Beispiel #53
0
        private void ReadMeshes(ContentReader input)
        {
            int numMeshes = input.ReadInt32();
            List<SkinnedModelMesh> meshList = new List<SkinnedModelMesh>(numMeshes);
            for (int i = 0; i < numMeshes; i++)
            {
                meshList.Add(input.ReadObject<SkinnedModelMesh>());
            }

            meshes = new SkinnedModelMeshCollection(meshList);
        }
Beispiel #54
0
        internal Map(ContentReader reader)
        {
            // read in the basic map information
            Version = new Version(reader.ReadString());
            Orientation = (Orientation)reader.ReadByte();
            WidthInTiles = reader.ReadInt32();
            HeightInTiles = reader.ReadInt32();
            TileWidth = reader.ReadInt32();
            TileHeight = reader.ReadInt32();
            Properties = new PropertyCollection(reader);
            bool makeTilesUnique = reader.ReadBoolean();

            // create a list for our tiles
            List<Tile> tiles = new List<Tile>();
            Tiles = new ReadOnlyCollection<Tile>(tiles);

            // read in each tile set
            int numTileSets = reader.ReadInt32();
            for (int i = 0; i < numTileSets; i++)
            {
                // get the id and texture
                int firstId = reader.ReadInt32();
                Texture2D texture = reader.ReadExternalReference<Texture2D>();

                // read in each individual tile
                int numTiles = reader.ReadInt32();
                for (int j = 0; j < numTiles; j++)
                {
                    int id = firstId + j;
                    Rectangle source = reader.ReadObject<Rectangle>();
                    PropertyCollection props = new PropertyCollection(reader);

                    Tile t = new Tile(texture, source, props);
                    while (id >= tiles.Count)
                    {
                        tiles.Add(null);
                    }
                    tiles.Insert(id, t);
                }
            }

            // read in all the layers
            List<Layer> layers = new List<Layer>();
            Layers = new ReadOnlyCollection<Layer>(layers);
            int numLayers = reader.ReadInt32();
            for (int i = 0; i < numLayers; i++)
            {
                Layer layer = null;

                // read generic layer data
                string type = reader.ReadString();
                string name = reader.ReadString();
                int width = reader.ReadInt32();
                int height = reader.ReadInt32();
                bool visible = reader.ReadBoolean();
                float opacity = reader.ReadSingle();
                PropertyCollection props = new PropertyCollection(reader);

                // calculate the default layer depth of the layer
                float layerDepth = 1f - (LayerDepthSpacing * i);

                // using the type, figure out which object to create
                if (type == "layer")
                {
                    uint[] data = reader.ReadObject<uint[]>();
                    layer = new TileLayer(name, width, height, layerDepth, visible, opacity, props, this, data, makeTilesUnique);
                }
                else if (type == "objectgroup")
                {
                    List<MapObject> objects = new List<MapObject>();

                    // read in all of our objects
                    int numObjects = reader.ReadInt32();
                    for (int j = 0; j < numObjects; j++)
                    {
                        string objName = reader.ReadString();
                        string objType = reader.ReadString();
                        Rectangle objLoc = reader.ReadObject<Rectangle>();
                        PropertyCollection objProps = new PropertyCollection(reader);

                        objects.Add(new MapObject(objName, objType, objLoc, objProps));
                    }

                    layer = new MapObjectLayer(name, width, height, layerDepth, visible, opacity, props, objects);

                    // read in the layer's color
                    (layer as MapObjectLayer).Color = reader.ReadColor();
                }
                else
                {
                    throw new Exception("Invalid type: " + type);
                }

                layers.Add(layer);
                namedLayers.Add(name, layer);
            }
        }
Beispiel #55
0
        protected internal override Model Read(ContentReader reader, Model existingInstance)
        {
            // Read the bone names and transforms.
            uint             boneCount = reader.ReadUInt32();
            List <ModelBone> bones     = new List <ModelBone>((int)boneCount);

            for (uint i = 0; i < boneCount; i += 1)
            {
                string    name   = reader.ReadObject <string>();
                Matrix    matrix = reader.ReadMatrix();
                ModelBone bone   = new ModelBone {
                    Transform = matrix,
                    Index     = (int)i,
                    Name      = name
                };
                bones.Add(bone);
            }
            // Read the bone hierarchy.
            for (int i = 0; i < boneCount; i += 1)
            {
                ModelBone bone = bones[i];
                // Read the parent bone reference.
                int parentIndex = ReadBoneReference(reader, boneCount);
                if (parentIndex != -1)
                {
                    bone.Parent = bones[parentIndex];
                }
                // Read the child bone references.
                uint childCount = reader.ReadUInt32();
                if (childCount != 0)
                {
                    for (uint j = 0; j < childCount; j += 1)
                    {
                        int childIndex = ReadBoneReference(reader, boneCount);
                        if (childIndex != -1)
                        {
                            bone.AddChild(bones[childIndex]);
                        }
                    }
                }
            }

            List <ModelMesh> meshes = new List <ModelMesh>();

            // Read the mesh data.
            int meshCount = reader.ReadInt32();

            for (int i = 0; i < meshCount; i += 1)
            {
                string         name            = reader.ReadObject <string>();
                int            parentBoneIndex = ReadBoneReference(reader, boneCount);
                BoundingSphere boundingSphere  = reader.ReadBoundingSphere();

                // Tag
                object meshTag = reader.ReadObject <object>();

                // Read the mesh part data.
                int partCount = reader.ReadInt32();

                List <ModelMeshPart> parts = new List <ModelMeshPart>(partCount);

                for (uint j = 0; j < partCount; j += 1)
                {
                    ModelMeshPart part;
                    if (existingInstance != null)
                    {
                        part = existingInstance.Meshes[i].MeshParts[(int)j];
                    }
                    else
                    {
                        part = new ModelMeshPart();
                    }

                    part.VertexOffset   = reader.ReadInt32();
                    part.NumVertices    = reader.ReadInt32();
                    part.StartIndex     = reader.ReadInt32();
                    part.PrimitiveCount = reader.ReadInt32();

                    // Tag
                    part.Tag = reader.ReadObject <object>();

                    parts.Add(part);

                    int jj = (int)j;
                    reader.ReadSharedResource <VertexBuffer>(
                        delegate(VertexBuffer v)
                    {
                        parts[jj].VertexBuffer = v;
                    }
                        );
                    reader.ReadSharedResource <IndexBuffer>(
                        delegate(IndexBuffer v)
                    {
                        parts[jj].IndexBuffer = v;
                    }
                        );
                    reader.ReadSharedResource <Effect>(
                        delegate(Effect v)
                    {
                        parts[jj].Effect = v;
                    }
                        );
                }
                if (existingInstance != null)
                {
                    continue;
                }
                ModelMesh mesh = new ModelMesh(reader.GraphicsDevice, parts);
                mesh.Tag        = meshTag;
                mesh.Name       = name;
                mesh.ParentBone = bones[parentBoneIndex];
                mesh.ParentBone.AddMesh(mesh);
                mesh.BoundingSphere = boundingSphere;
                meshes.Add(mesh);
            }
            if (existingInstance != null)
            {
                // Read past remaining data and return existing instance
                ReadBoneReference(reader, boneCount);
                reader.ReadObject <object>();
                return(existingInstance);
            }
            // Read the final pieces of model data.
            int   rootBoneIndex = ReadBoneReference(reader, boneCount);
            Model model         = new Model(reader.GraphicsDevice, bones, meshes);

            model.Root = bones[rootBoneIndex];
            model.BuildHierarchy();
            // Tag?
            model.Tag = reader.ReadObject <object>();
            return(model);
        }
Beispiel #56
0
        internal static SkinnedModelMesh Read(ContentReader input)
        {
            SkinnedModelMesh skinnedModelPart = new SkinnedModelMesh();

            skinnedModelPart.numVertices = input.ReadInt32();
            skinnedModelPart.numTriangles = input.ReadInt32();
            skinnedModelPart.vertices = input.ReadObject<VertexBuffer>();
            skinnedModelPart.indices = input.ReadObject<IndexBuffer>();
            skinnedModelPart.effect = input.ReadObject<SkinnedModelBasicEffect>();

            return skinnedModelPart;
        }