Beispiel #1
0
        public void SetSprite(string contentManagerName, Sprite sprite, bool setTextures)
        {
            // Set Texture and PixelSize BEFORE setting Scale so that the Scale
            // overrides it if it's different.
            if (setTextures)
            {
#if !MONODROID
                if (mTextureInstance != null)
                {
                    sprite.Texture = mTextureInstance;
                }

                else
#endif
                // Sprites can have NULL textures as of April 18, 2009
                if (!string.IsNullOrEmpty(Texture))
                {
                    sprite.Texture = FlatRedBallServices.Load <Texture2D>(Texture, contentManagerName);
                }
            }
            sprite.X = X;
            sprite.Y = Y;
            sprite.Z = Z;

            sprite.RotationX         = RotationX;
            sprite.RotationY         = RotationY;
            sprite.RotationZ         = RotationZ;
            sprite.RotationZVelocity = RotationZVelocity;


            sprite.PixelSize               = ConstantPixelSize;
            sprite.TopTextureCoordinate    = TopTextureCoordinate;
            sprite.BottomTextureCoordinate = BottomTextureCoordinate;
            sprite.LeftTextureCoordinate   = LeftTextureCoordinate;
            sprite.RightTextureCoordinate  = RightTextureCoordinate;
            // End of stuff to set before setting Scale

            sprite.ScaleX         = ScaleX;
            sprite.ScaleXVelocity = ScaleXVelocity;
            sprite.ScaleY         = ScaleY;
            sprite.ScaleYVelocity = ScaleYVelocity;

            sprite.XVelocity = XVelocity;
            sprite.YVelocity = YVelocity;
            sprite.ZVelocity = ZVelocity;

            sprite.XAcceleration = XAcceleration;
            sprite.YAcceleration = YAcceleration;
            sprite.ZAcceleration = ZAcceleration;

            sprite.RelativeX = RelativeX;
            sprite.RelativeY = RelativeY;
            sprite.RelativeZ = RelativeZ;

            sprite.RelativeRotationX = RelativeRotationX;
            sprite.RelativeRotationY = RelativeRotationY;
            sprite.RelativeRotationZ = RelativeRotationZ;

            sprite.Name    = Name;
            sprite.Animate = Animate;

            if (setTextures)
            {
                SetRuntimeAnimationChain(contentManagerName, sprite,
#if !MONODROID
                                         mAnimationChainListInstance,
#else
                                         null,
#endif
                                         CurrentChain,
                                         AnimationChains, AnimationChainsFile

                                         );
            }

            float valueToDivideBy = 255 / GraphicalEnumerations.MaxColorComponentValue;

            sprite.Alpha          = (255 - Fade) / valueToDivideBy;
            sprite.AlphaRate      = -FadeRate / valueToDivideBy;
            sprite.BlendOperation = GraphicalEnumerations.TranslateBlendOperation(BlendOperation);

            sprite.RedRate   = TintRedRate / valueToDivideBy;
            sprite.GreenRate = TintGreenRate / valueToDivideBy;
            sprite.BlueRate  = TintBlueRate / valueToDivideBy;

            GraphicalEnumerations.SetColors(sprite, TintRed, TintGreen, TintBlue, ColorOperation);

            // If the Texture is null, we may want to use "Color" instead of "ColorTextureAlpha"
#if !FRB_MDX
            if (sprite.Texture == null && sprite.ColorOperation == FlatRedBall.Graphics.ColorOperation.ColorTextureAlpha)
            {
                sprite.ColorOperation = FlatRedBall.Graphics.ColorOperation.Color;
            }
#endif

            sprite.mOrdered = Ordered;

            sprite.Visible = Visible;

            sprite.TextureAddressMode = TextureAddressMode;

            sprite.FlipHorizontal = FlipHorizontal;
            sprite.FlipVertical   = FlipVertical;
        }
 void GameForm_Activated(object sender, EventArgs e)
 {
     FlatRedBallServices.Update(null);
     GuiManager.Cursor.ResetCursor();
 }
Beispiel #3
0
        public static void StaticInitialize(string projectFileName)
        {
            if (mManagers == null)
            {
                mManagers = new SystemManagers();
                mManagers.Initialize(FlatRedBallServices.GraphicsDevice);
                mManagers.Renderer.Camera.AbsoluteLeft = 0;
                mManagers.Renderer.Camera.AbsoluteTop  = 0;

                var viewport = mManagers.Renderer.GraphicsDevice.Viewport;
                viewport.Width  = FlatRedBall.Math.MathFunctions.RoundToInt(FlatRedBall.Camera.Main.DestinationRectangle.Width);
                viewport.Height = FlatRedBall.Math.MathFunctions.RoundToInt(FlatRedBall.Camera.Main.DestinationRectangle.Height);
                mManagers.Renderer.GraphicsDevice.Viewport = viewport;

                GraphicalUiElement.CanvasHeight = FlatRedBall.Camera.Main.OrthogonalHeight;
                GraphicalUiElement.CanvasWidth  = FlatRedBall.Camera.Main.OrthogonalWidth;


                // Need to do the zoom here in response to the FRB camera vs. the Gum camera
                mManagers.Renderer.Camera.Zoom = viewport.Height / (float)GraphicalUiElement.CanvasHeight;
                mManagers.Renderer.Camera.CameraCenterOnScreen = CameraCenterOnScreen.TopLeft;
                mManagers.Renderer.Camera.X = 0;
                mManagers.Renderer.Camera.Y = 0;

                SystemManagers.Default = mManagers;
                FlatRedBallServices.AddManager(RenderingLibrary.SystemManagers.Default);

                RenderingLibrary.Graphics.Text.RenderBoundaryDefault = false;
            }

            if (projectFileName == null)
            {
                throw new Exception("The GumIDB must be initialized with a valid (non-null) project file.");
            }

            string errors;

            mProjectFileName = projectFileName;

            if (FlatRedBall.IO.FileManager.IsRelative(mProjectFileName))
            {
                mProjectFileName = FlatRedBall.IO.FileManager.RelativeDirectory + mProjectFileName;
            }

            // First let's set the relative directory to the file manager's relative directory so we can load
            // the file normally...
            ToolsUtilities.FileManager.RelativeDirectory = FlatRedBall.IO.FileManager.RelativeDirectory;

            ObjectFinder.Self.GumProjectSave = GumProjectSave.Load(projectFileName, out errors);

#if DEBUG
            if (ObjectFinder.Self.GumProjectSave == null)
            {
                throw new Exception("Could not find Gum project at " + projectFileName);
            }
#endif

            // Now we can set the directory to Gum's root:
            ToolsUtilities.FileManager.RelativeDirectory = ToolsUtilities.FileManager.GetDirectory(mProjectFileName);

            // The Gum tool does a lot more init than this, but we're going to only do a subset
            //of initialization for performance
            // reasons:
            foreach (var item in ObjectFinder.Self.GumProjectSave.Screens)
            {
                // Only initialize using the default state
                if (item.DefaultState != null)
                {
                    item.Initialize(item.DefaultState);
                }
            }
            foreach (var item in ObjectFinder.Self.GumProjectSave.Components)
            {
                // Only initialize using the default state
                if (item.DefaultState != null)
                {
                    item.Initialize(item.DefaultState);
                }
            }
            foreach (var item in ObjectFinder.Self.GumProjectSave.StandardElements)
            {
                // Only initialize using the default state
                if (item.DefaultState != null)
                {
                    item.Initialize(item.DefaultState);
                }
            }

            StandardElementsManager.Self.Initialize();
        }
        public void ForceUpdateImageData()
        {
            #region Update the texture
            if (mImageData != null)
            {
                for (int x = 0; x < mNumberOfXTiles; x++)
                {
                    for (int y = 0; y < mNumberOfYTiles; y++)
                    {
                        Color colorToSet;

                        if (mBlockedTiles[x][y] == 0)
                        {
                            if (mRevealedTiles[x][y] == 0)
                            {
                                colorToSet = HiddenClearedColor;
                            }
                            else
                            {
                                colorToSet = RevealedClearedColor;
                            }
                        }
                        else
                        {
                            if (mRevealedTiles[x][y] == 0)
                            {
                                colorToSet = HiddenBlockedColor;
                            }
                            else
                            {
                                colorToSet = RevealedBlockedColor;
                            }
                        }


                        //byte blue = (byte)(255 * (mBlockedTiles[x][y] & 1));
                        //byte green = (byte)(255 * (mRevealedTiles[x][y] & 1));
                        //byte red = 255;


                        mImageData.SetPixel(x, y, colorToSet);
                    }
                }

                ContentManager contentManager = FlatRedBallServices.GetContentManagerByName(this.ContentManagerName);
                //FlatRedBallServices.GlobalContentManager);

                if (mSprite != null)
                {
                    if (mSprite.Texture != null)
                    {
                        contentManager.UnloadAsset(mSprite.Texture);
                        mSprite.Texture.Dispose();
                    }

                    bool generateMipmaps = false;
                    mSprite.Texture = mImageData.ToTexture2D(generateMipmaps, FlatRedBallServices.GraphicsDevice);
                    contentManager.AddDisposable("VisibilityGridTexture #" + NumberCreated, mSprite.Texture);
                    NumberCreated++;
                }
            }
            #endregion
        }
Beispiel #5
0
        public TweenerManager()
        {
            mTweeners = new List <Tweener>();

            FlatRedBallServices.AddManager(this);
        }
Beispiel #6
0
        public virtual void Destroy()
        {
            if (mLastLoadedScene != null)
            {
                mLastLoadedScene.Clear();
            }

            // All of the popups should be destroyed as well
            foreach (Screen s in mPopups)
            {
                s.Destroy();
            }

            SpriteManager.RemoveSpriteList(mSprites);

            // It's common for users to forget to add Particle Sprites
            // to the mSprites SpriteList.  This will either create leftover
            // particles when the next screen loads or will throw an assert when
            // the ScreenManager checks if there are any leftover Sprites.  To make
            // things easier we'll just clear the Particle Sprites here.  If you don't
            // want this done (not likely), remove the following line, but only do so if
            // you really know what you're doing!
            SpriteManager.RemoveAllParticleSprites();

            // Destory all SpriteGrids that belong to this Screen
            foreach (SpriteGrid sg in mSpriteGrids)
            {
                sg.Destroy();
            }


            // Destroy all SpriteFrames that belong to this Screen
            while (mSpriteFrames.Count != 0)
            {
                SpriteManager.RemoveSpriteFrame(mSpriteFrames[0]);
            }

            TextManager.RemoveText(mTexts);

            while (mPolygons.Count != 0)
            {
                ShapeManager.Remove(mPolygons[0]);
            }

            while (mLines.Count != 0)
            {
                ShapeManager.Remove(mLines[0]);
            }

            while (mAxisAlignedRectangles.Count != 0)
            {
                ShapeManager.Remove(mAxisAlignedRectangles[0]);
            }

            while (mCircles.Count != 0)
            {
                ShapeManager.Remove(mCircles[0]);
            }

#if !SILVERLIGHT
            while (mPositionedModels.Count != 0)
            {
                ModelManager.RemoveModel(mPositionedModels[0]);
            }
#endif

            if (UnloadsContentManagerWhenDestroyed)
            {
                FlatRedBallServices.Unload(mContentManagerName);
            }

            if (mLayer != null)
            {
                SpriteManager.RemoveLayer(mLayer);
            }

            for (int i = 0; i < mLayers.Count; i++)
            {
                SpriteManager.RemoveLayer(mLayers[i]);
            }
        }
Beispiel #7
0
        private void CreateButtons()
        {
            #region Consts used in button creation

            const float buttonScaleX           = 2.0f;
            const float buttonScaleY           = 1.5f;
            const float distanceBetweenButtons = .5f;
            const float buttonY = 5;

            #endregion

            int buttonsAddedSoFar = 0;

            #region To Start
            mToStart = new Button(mCursor);
            AddWindow(mToStart);
            mToStart.SetOverlayTextures(
                FlatRedBallServices.Load <Texture2D>(@"Content\ToStartButton.png", FlatRedBallServices.GlobalContentManager),
                null);
            mToStart.ScaleX = buttonScaleX;
            mToStart.ScaleY = buttonScaleY;
            mToStart.X      = distanceBetweenButtons + buttonScaleX + buttonsAddedSoFar * (distanceBetweenButtons + 2 * buttonScaleX);
            mToStart.Y      = buttonY;
            mToStart.Click += ToStartClick;
            buttonsAddedSoFar++;
            #endregion

            #region Play

            mPlay = new ToggleButton(mCursor);
            AddWindow(mPlay);
            mPlay.SetOverlayTextures(
                FlatRedBallServices.Load <Texture2D>(@"Content\PlayButton.png", FlatRedBallServices.GlobalContentManager),
                null);
            mPlay.ScaleX = buttonScaleX;
            mPlay.ScaleY = buttonScaleY;
            mPlay.X      = distanceBetweenButtons + buttonScaleX + buttonsAddedSoFar * (distanceBetweenButtons + 2 * buttonScaleX);
            mPlay.Y      = buttonY;
            mPlay.Click += PlayClick;
            buttonsAddedSoFar++;

            #endregion

            #region Pause

            mPause = new ToggleButton(mCursor);
            AddWindow(mPause);
            mPause.SetOverlayTextures(
                FlatRedBallServices.Load <Texture2D>(@"Content\PauseButton.png", FlatRedBallServices.GlobalContentManager),
                null);
            mPause.ScaleX = buttonScaleX;
            mPause.ScaleY = buttonScaleY;
            mPause.X      = distanceBetweenButtons + buttonScaleX + buttonsAddedSoFar * (distanceBetweenButtons + 2 * buttonScaleX);
            mPause.Y      = buttonY;
            mPause.Click += PauseClick;
            buttonsAddedSoFar++;

            #endregion

            mStop = new Button(mCursor);
            AddWindow(mStop);
            mStop.SetOverlayTextures(
                FlatRedBallServices.Load <Texture2D>(@"Content\StopButton.png", FlatRedBallServices.GlobalContentManager),
                null);
            mStop.ScaleX = buttonScaleX;
            mStop.ScaleY = buttonScaleY;
            mStop.X      = distanceBetweenButtons + buttonScaleX + buttonsAddedSoFar * (distanceBetweenButtons + 2 * buttonScaleX);
            mStop.Y      = buttonY;
            mStop.Click += StopClick;
            buttonsAddedSoFar++;

            mLoadSong = new Button(mCursor);
            AddWindow(mLoadSong);
            mLoadSong.SetOverlayTextures(
                FlatRedBallServices.Load <Texture2D>(@"Content\EjectButton.png", FlatRedBallServices.GlobalContentManager),
                null);
            mLoadSong.ScaleX = buttonScaleX;
            mLoadSong.ScaleY = buttonScaleY;
            mLoadSong.X      = distanceBetweenButtons + buttonScaleX + buttonsAddedSoFar * (distanceBetweenButtons + 2 * buttonScaleX);
            mLoadSong.Y      = buttonY;
            mLoadSong.Click += OpenSongWindow;
            buttonsAddedSoFar++;
        }
        /* This creates a MapDrawableBatch (MDB) from the list of sprites provided to us by the FlatRedBall (FRB) Scene XML (scnx) file. */
        public static MapDrawableBatch FromSpriteSaves(List <SpriteSave> spriteSaveList, int startingIndex, int count, string contentManagerName, bool verifySameTexturesPerLayer)
        {
#if DEBUG
            if (verifySameTexturesPerLayer)
            {
                VerifySingleTexture(spriteSaveList, startingIndex, count);
            }
#endif

            // We got it!  We are going to make some assumptions:
            // First we need the texture.  We'll assume all Sprites
            // use the same texture:

            // TODO: I (Bryan) really HATE this assumption. But it will work for now.
            SpriteSave firstSprite = spriteSaveList[startingIndex];

            // This is the file name of the texture, but the file name is relative to the .scnx location
            string textureRelativeToScene = firstSprite.Texture;
            // so we load the texture
            Texture2D texture = FlatRedBallServices.Load <Texture2D>(textureRelativeToScene, contentManagerName);

            if (!MathFunctions.IsPowerOfTwo(texture.Width) || !MathFunctions.IsPowerOfTwo(texture.Height))
            {
                throw new Exception("The dimensions of the texture file " + texture.Name + " are not power of 2!");
            }


            // Assume all the dimensions of the textures are the same. I.e. all tiles use the same texture width and height.
            // This assumption is safe for Iso and Ortho tile maps.
            int tileFileDimensionsWidth  = 0;
            int tileFileDimensionsHeight = 0;
            if (spriteSaveList.Count > startingIndex)
            {
                SpriteSave s = spriteSaveList[startingIndex];

                // deduce the dimensionality of the tile from the texture coordinates
                tileFileDimensionsWidth  = (int)System.Math.Round((double)((s.RightTextureCoordinate - s.LeftTextureCoordinate) * texture.Width));
                tileFileDimensionsHeight = (int)System.Math.Round((double)((s.BottomTextureCoordinate - s.TopTextureCoordinate) * texture.Height));
            }


            // alas, we create the MDB
            MapDrawableBatch mMapBatch = new MapDrawableBatch(count, tileFileDimensionsWidth, tileFileDimensionsHeight, texture);

            int lastIndexExclusive = startingIndex + count;

            for (int i = startingIndex; i < lastIndexExclusive; i++)
            {
                SpriteSave spriteSave = spriteSaveList[i];

                // We don't want objects within the IDB to have a different Z than the IDB itself
                // (if possible) because that makes the IDB behave differently when using sorting vs.
                // the zbuffer.
                const bool setZTo0 = true;
                mMapBatch.Paste(spriteSave, setZTo0);
            }



            return(mMapBatch);
        }
Beispiel #9
0
 public static Sprite AddSpriteFromAchx(string achxFile)
 {
     return(SpriteManager.AddSprite(FlatRedBallServices.Load <AnimationChainList>(achxFile,
                                                                                  FlatRedBallServices.GlobalContentManager)));
 }
Beispiel #10
0
 /// <summary>
 /// Draws the way FlatRedBall draws by default
 /// </summary>
 private void DrawWithFrbDefaults()
 {
     FlatRedBallServices.Draw();
 }
Beispiel #11
0
 /// <summary>
 /// Draws entire buffer using shaders
 /// </summary>
 private void DrawWithShaders()
 {
     // draw game to render target
     FlatRedBallServices.Draw();
 }
        protected void OnResize(bool forceResize)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                return; // don't want to change the camera when we minimize the screen
            }
            if (SpriteManager.IsInitialized)
            {
                FlatRedBallServices.ForceClientSizeUpdates();
                //		SpriteManager.FindDevice();

                bool updateFieldOfView = forceResize ||
                                         SpriteManager.Cameras[0].DestinationRectangle.Height != DisplayRectangle.Height;

                if (SpriteManager.Camera.Orthogonal == false)
                {
                    float ratioChange = DisplayRectangle.Height / (float)SpriteManager.Cameras[0].DestinationRectangle.Height;


                    SpriteManager.Cameras[0].DestinationRectangle = this.DisplayRectangle;

                    if (updateFieldOfView)
                    {
                        double yAt600        = Math.Sin(Math.PI / 8.0);
                        double xAt600        = Math.Cos(Math.PI / 8.0);
                        double desiredYAt600 = yAt600 * (double)DisplayRectangle.Height / 600.0;
                        float  desiredAngle  = (float)Math.Atan2(desiredYAt600, xAt600);
                        SpriteManager.Cameras[0].FieldOfView = 2 * desiredAngle;
                    }
                }
                else
                {
                    double unitPerPixel = SpriteManager.Camera.OrthogonalHeight / SpriteManager.Cameras[0].DestinationRectangle.Height;

                    SpriteManager.Camera.OrthogonalHeight         = (float)(DisplayRectangle.Height * unitPerPixel);
                    SpriteManager.Camera.OrthogonalWidth          = (float)(DisplayRectangle.Width * unitPerPixel);
                    SpriteManager.Cameras[0].DestinationRectangle = this.DisplayRectangle;

                    SpriteManager.Cameras[0].FixAspectRatioYConstant();
                    if (updateFieldOfView)
                    {
                        double yAt600        = Math.Sin(Math.PI / 8.0);
                        double xAt600        = Math.Cos(Math.PI / 8.0);
                        double desiredYAt600 = yAt600 * (double)DisplayRectangle.Height / 600.0;
                        float  desiredAngle  = (float)Math.Atan2(desiredYAt600, xAt600);
                        SpriteManager.Cameras[0].FieldOfView = 2 * desiredAngle;
                    }
                }

                // Shifts are no longer needed - top left is 0,0
                //GuiManager.ShiftBy(
                //    -(float)(TopLeftPixel.X + SpriteManager.Cameras[0].XEdge),
                //    -(float)(SpriteManager.Cameras[0].YEdge - TopLeftPixel.Y),
                //    false // Don't shift SpriteFrame GUI
                //    );

                TopLeftPixel.X = -SpriteManager.Cameras[0].XEdge;
                TopLeftPixel.Y = SpriteManager.Cameras[0].YEdge;

                //GuiManager.RefreshTextSize();
            }
        }
 private void Draw()
 {
     FlatRedBallServices.Draw();
 }
 public virtual void FrameUpdate()
 {
     FlatRedBallServices.Update(null);
 }
Beispiel #15
0
 public Texture2D LoadTexture2D(string path)
 {
     return(FlatRedBallServices.Load <Texture2D>(path));
 }
        private object LoadSplx(ReferencedFileSave r)
        {
            var toReturn = FlatRedBallServices.Load <SplineList>(ElementRuntime.ContentDirectory + r.Name, GluxManager.ContentManagerName);

            return(toReturn);
        }
Beispiel #17
0
        public static void StaticInitialize(string projectFileName)
        {
            if (mManagers == null)
            {
                mManagers = new SystemManagers();
                mManagers.Initialize(FlatRedBallServices.GraphicsDevice);
                mManagers.Renderer.Camera.AbsoluteLeft = 0;
                mManagers.Renderer.Camera.AbsoluteTop  = 0;


                // Need to do the zoom here in response to the FRB camera vs. the Gum camera
                mManagers.Renderer.Camera.CameraCenterOnScreen = CameraCenterOnScreen.TopLeft;
                mManagers.Renderer.Camera.X = 0;
                mManagers.Renderer.Camera.Y = 0;

                SystemManagers.Default = mManagers;
                FlatRedBallServices.AddManager(RenderingLibrary.SystemManagers.Default);

                RenderingLibrary.Graphics.Text.RenderBoundaryDefault = false;
                // FlatRedBall uses premult alpha.
                RenderingLibrary.Graphics.Renderer.NormalBlendState = Microsoft.Xna.Framework.Graphics.BlendState.AlphaBlend;

                UpdateDisplayToMainFrbCamera();


                var idb = new GumIdb();
                // We don't want the UI to be at Z=0 because it will render
                // at the same Z along with FRB entities and environments so UI might
                // be hidden. The proper way to solve this is to use Layers, but
                // this shouldn't be creating new Layers, that's up to the user.
                // Let's make it have a positive Z so it draws in more things at once
                idb.Z = 10;

                // This could be called on a secondary thread, like if called by GlobalContent, so we
                // want this to happen on the primary thread:
                Action primaryThreadAction = () =>
                {
                    FlatRedBall.SpriteManager.AddDrawableBatch(idb);
                    FlatRedBall.Screens.ScreenManager.PersistentDrawableBatches.Add(idb);
                };

                var instruction = new FlatRedBall.Instructions.DelegateInstruction(primaryThreadAction);
                FlatRedBall.Instructions.InstructionManager.AddSafe(instruction);
                Self = idb;
            }

            if (projectFileName == null)
            {
                throw new Exception("The GumIDB must be initialized with a valid (non-null) project file.");
            }

            string errors;

            mProjectFileName = projectFileName;

            if (FlatRedBall.IO.FileManager.IsRelative(mProjectFileName))
            {
                mProjectFileName = FlatRedBall.IO.FileManager.RelativeDirectory + mProjectFileName;
            }

            // First let's set the relative directory to the file manager's relative directory so we can load
            // the file normally...
            ToolsUtilities.FileManager.RelativeDirectory = FlatRedBall.IO.FileManager.RelativeDirectory;

            GumLoadResult result;

            ObjectFinder.Self.GumProjectSave = GumProjectSave.Load(mProjectFileName, out result);

#if DEBUG
            if (ObjectFinder.Self.GumProjectSave == null)
            {
                throw new Exception("Could not find Gum project at " + mProjectFileName);
            }

            if (!string.IsNullOrEmpty(result.ErrorMessage))
            {
                throw new Exception(result.ErrorMessage);
            }

            if (result.MissingFiles.Count != 0)
            {
                throw new Exception("Missing files starting with " + result.MissingFiles[0]);
            }
#endif

            // Now we can set the directory to Gum's root:
            ToolsUtilities.FileManager.RelativeDirectory = ToolsUtilities.FileManager.GetDirectory(mProjectFileName);

            // The Gum tool does a lot more init than this, but we're going to only do a subset
            //of initialization for performance
            // reasons:
            foreach (var item in ObjectFinder.Self.GumProjectSave.Screens)
            {
                // Only initialize using the default state
                if (item.DefaultState != null)
                {
                    item.Initialize(item.DefaultState);
                }
            }
            foreach (var item in ObjectFinder.Self.GumProjectSave.Components)
            {
                // Only initialize using the default state
                if (item.DefaultState != null)
                {
                    item.Initialize(item.DefaultState);
                }
            }
            foreach (var item in ObjectFinder.Self.GumProjectSave.StandardElements)
            {
                // Only initialize using the default state
                if (item.DefaultState != null)
                {
                    item.Initialize(item.DefaultState);
                }
                //for atlased colored rectangles
                if (item.Name == "ColoredRectangle")
                {
                    RenderingLibrary.Graphics.SolidRectangle.AtlasedTextureName = "..\\Graphics\\Misc\\ColoredRectangle.png";
                }
            }

            StandardElementsManager.Self.Initialize();
        }
 static EmitterList LoadEmix(ReferencedFileSave r)
 {
     return(FlatRedBallServices.Load <EmitterList>(ElementRuntime.ContentDirectory + r.Name, GluxManager.ContentManagerName));
 }
Beispiel #19
0
 /// <summary>
 /// Performs FlatRedBall drawing services.
 /// </summary>
 /// <param name="gameTime">Container for information about time elapsed since last update.</param>
 protected override void Draw(GameTime gameTime)
 {
     FlatRedBallServices.Draw();
     base.Draw(gameTime);
 }
Beispiel #20
0
        public FlatRedBall.ManagedSpriteGroups.SpriteFrame ToSpriteFrame(string contentManagerName)
        {
            Texture2D textureToUse = null;

#if !MONODROID
            if (ParentSprite.mTextureInstance != null)
            {
                textureToUse = ParentSprite.mTextureInstance;
            }
            else
            {
#endif
            textureToUse =
                FlatRedBallServices.Load <Texture2D>(ParentSprite.Texture, contentManagerName);

#if !MONODROID
        }
#endif

            FlatRedBall.ManagedSpriteGroups.SpriteFrame spriteFrame =
                new FlatRedBall.ManagedSpriteGroups.SpriteFrame(
                    textureToUse,
                    (FlatRedBall.ManagedSpriteGroups.SpriteFrame.BorderSides)BorderSides);

            spriteFrame.Name = ParentSprite.Name;

            spriteFrame.Position = new Vector3(
                ParentSprite.X, ParentSprite.Y, ParentSprite.Z);

            spriteFrame.RelativePosition = new Vector3(
                ParentSprite.RelativeX, ParentSprite.RelativeY, ParentSprite.RelativeZ);

            spriteFrame.RotationX = ParentSprite.RotationX;
            spriteFrame.RotationY = ParentSprite.RotationY;
            spriteFrame.RotationZ = ParentSprite.RotationZ;

            spriteFrame.RelativeRotationX = ParentSprite.RelativeRotationX;
            spriteFrame.RelativeRotationY = ParentSprite.RelativeRotationY;
            spriteFrame.RelativeRotationZ = ParentSprite.RelativeRotationZ;

            spriteFrame.ScaleX = ParentSprite.ScaleX;
            spriteFrame.ScaleY = ParentSprite.ScaleY;

            spriteFrame.TextureBorderWidth = TextureBorderWidth;
            spriteFrame.SpriteBorderWidth  = SpriteBorderWidth;

            spriteFrame.Visible = ParentSprite.Visible;


            spriteFrame.Animate = ParentSprite.Animate;
            SpriteSave.SetRuntimeAnimationChain(
                contentManagerName,
                spriteFrame,
#if !MONODROID
                ParentSprite.mAnimationChainListInstance,
#else
                null,
#endif
                ParentSprite.CurrentChain, ParentSprite.AnimationChains, ParentSprite.AnimationChainsFile);


            float valueToDivideBy = 255 / GraphicalEnumerations.MaxColorComponentValue;


            spriteFrame.Red   = ParentSprite.TintRed / valueToDivideBy;
            spriteFrame.Green = ParentSprite.TintGreen / valueToDivideBy;
            spriteFrame.Blue  = ParentSprite.TintBlue / valueToDivideBy;

            spriteFrame.Alpha = (255 - ParentSprite.Fade) / valueToDivideBy;

            spriteFrame.BlendOperation = GraphicalEnumerations.TranslateBlendOperation(ParentSprite.BlendOperation);

            GraphicalEnumerations.SetColors(spriteFrame, ParentSprite.TintRed, ParentSprite.TintGreen, ParentSprite.TintBlue, ParentSprite.ColorOperation);

            if (spriteFrame.CenterSprite != null)
            {
                spriteFrame.CenterSprite.mOrdered = ParentSprite.Ordered;
            }

            return(spriteFrame);
        }
        public TextureCoordinatesSelectionWindow() :
            base(GuiManager.Cursor)
        {
            // Victor says:  This class USED to
            // add itself to the GuiManager.  This
            // is no longer recommended as it makes
            // windows not as reusable.  Therefore, I
            // removed the automatic adding to the GuiManager.
            // This might break your code if you're using this,
            // so if your TextureCoordinatesSelectionWindow isn't
            // showing up, you might want to make sure you're adding
            // it to the GuiManager.

            #region Create "this" and add it to the GuiManager
            HasMoveBar = true;
            ScaleY     = 12.5f;
            ScaleX     = 11.4f;

            Resizable     = true;
            MinimumScaleX = ScaleX;
            MinimumScaleY = ScaleY;

            this.Resizing += OnWindowResize;
            #endregion

            #region Create the texture display area

            mTextureDisplayArea = new Window(mCursor);
            AddWindow(mTextureDisplayArea);

            mTextureDisplayArea.DrawBorders  = false;
            mTextureDisplayArea.Push        += OnWindowPush;
            mTextureDisplayArea.Dragging    += OnWindowDrag;
            mTextureDisplayArea.Click       += OnWindowClick;
            mTextureDisplayArea.RollingOver += this.OnRollOver;
            mTextureDisplayArea.DoubleClick += OnWindowDoubleClick;

            mTextureDisplayArea.MouseWheelScroll += MouseWheelZoom;

            mTextureDisplayArea.SecondaryClick += RightClickMenu;

            #endregion

            mSelectedArea = new Window(mCursor);
            mTextureDisplayArea.AddWindow(mSelectedArea);
            mSelectedArea.ScaleX      = 3;
            mSelectedArea.ScaleY      = 3;
            mSelectedArea.BaseTexture =
                FlatRedBallServices.Load <Texture2D>("genGfx/targetBox.bmp", GuiManager.InternalGuiContentManagerName);
            mSelectedArea.Enabled     = false; // so it doesn't block input from the this (the parent Window)
            mSelectedArea.DrawBorders = false;
            mSelectedArea.Alpha       = 127;

            mAddToListButton = new Button(mCursor);
            AddWindow(mAddToListButton);
            mAddToListButton.Text    = "Add To List";
            mAddToListButton.Visible = false;

            #region Pixel Perfect ToggleButton and ComboBoxes

            mPixelPerfect = new ToggleButton(mCursor);
            AddWindow(mPixelPerfect);

            mPixelPerfect.ScaleX = 5;
            mPixelPerfect.SetText("Free", "Snapping");
            mPixelPerfect.Press();
            mPixelPerfect.Click += PixelPerfectClick;

            mMinimumXSelection = new ComboBox(mCursor);
            AddWindow(mMinimumXSelection);
            mMinimumXSelection.ScaleX = 3;
            mMinimumXSelection.AddItem("1");
            mMinimumXSelection.AddItem("4");
            mMinimumXSelection.AddItem("8");
            mMinimumXSelection.AddItem("16");
            mMinimumXSelection.AddItem("32");
            mMinimumXSelection.Text = "1";

            mMinimumYSelection = new ComboBox(mCursor);
            AddWindow(mMinimumYSelection);
            mMinimumYSelection.ScaleX = 3;
            mMinimumYSelection.AddItem("1");
            mMinimumYSelection.AddItem("4");
            mMinimumYSelection.AddItem("8");
            mMinimumYSelection.AddItem("16");
            mMinimumYSelection.AddItem("32");
            mMinimumYSelection.Text = "1";

            #endregion

            #region Create the ScrollBars
            mVerticalScrollBar = new ScrollBar(mCursor);
            AddWindow(mVerticalScrollBar);
            mVerticalScrollBar.UpButtonClick   += AdjustToVerticalScrollBar;
            mVerticalScrollBar.DownButtonClick += AdjustToVerticalScrollBar;
            mVerticalScrollBar.PositionBarMove += AdjustToVerticalScrollBar;

            mHorizontalScrollBar = new ScrollBar(mCursor);
            AddWindow(mHorizontalScrollBar);
            mHorizontalScrollBar.UpButtonClick   += AdjustToVerticalScrollBar;
            mHorizontalScrollBar.DownButtonClick += AdjustToVerticalScrollBar;
            mHorizontalScrollBar.PositionBarMove += AdjustToVerticalScrollBar;
            mHorizontalScrollBar.Alignment        = ScrollBar.ScrollBarAlignment.Horizontal;
            mHorizontalScrollBar.ScaleY           = 1;
            #endregion

            OnWindowResize(this);
        }
Beispiel #22
0
        // made public for unit tests
        public static void Initialize(Texture2D guiTextureToUse, Cursor cursor)
#endif
        {
#if FRB_MDX || XNA3_1
            RemoveInvisibleDominantWindows = true;
#else
            RemoveInvisibleDominantWindows = false;
#endif
            mPerishableArrayReadOnly = new ReadOnlyCollection <IWindow>(mPerishableArray);
            // Currently make the FRB XNA default to not using the UI, but the FRB MDX to true
            TextHeight  = 2;
            TextSpacing = 1;

            mUIEnabled = true;



            //		sr.WriteLine("Inside the GuiManager constructor");
            //		sr.Close();
            mCursors = new List <Cursor>();

            mCursors.Add(cursor);

            mWindowArray         = new WindowArray();
            mReadOnlyWindowArray = new ReadOnlyCollection <IWindow>(mWindowArray);

            mDominantWindows = new List <IWindow>();

#if !MONOGAME && !SILVERLIGHT && !UNIT_TESTS && !XNA4
            RenderingBasedInitializize();
#endif

            BringsClickedWindowsToFront = true;


            try
            {
#if FRB_MDX
                if (System.IO.File.Exists(FlatRedBall.IO.FileManager.RelativeDirectory + "Assets/Textures/upDirectory.bmp"))
                {
                    mUpDirectory = FlatRedBallServices.Load <Texture2D>(
                        FlatRedBall.IO.FileManager.RelativeDirectory + "Assets/Textures/upDirectory.bmp",
                        InternalGuiContentManagerName);
                }
                if (System.IO.File.Exists(FlatRedBall.IO.FileManager.RelativeDirectory + "Assets/Textures/cursorTextBox.bmp"))
                {
                    mCursorTextBox = FlatRedBallServices.Load <Texture2D>(
                        FlatRedBall.IO.FileManager.RelativeDirectory + "Assets/Textures/cursorTextBox.bmp",
                        InternalGuiContentManagerName);
                }



                if (guiTextureToUse != null && guiTextureToUse != "")
                {
                    guiTexture = FlatRedBallServices.Load <Texture2D>(
                        guiTextureToUse, InternalGuiContentManagerName);

                    RefreshTextSize();
                }
#elif SUPPORTS_FRB_DRAWN_GUI
                guiTexture = guiTextureToUse;

                RefreshTextSize();
#endif
            }
            catch (Exception e)
            {
                throw e;
            }
            try
            {
                nfi = new System.Globalization.NumberFormatInfo();
                //replaced the above line with the one below to used streamed images.


                ShowingCursorTextBox = true;

                renderingNotes = new List <String>();
            }
            catch (Exception e)
            {
                throw e;
            }

#if SUPPORTS_FRB_DRAWN_GUI
            SetPropertyGridTypeAssociations();
#endif

            // Let's do some updates because we want to make sure our "last" values are set to the current value
            // so we don't have any movement on the cursor initially:
            cursor.Update(TimeManager.CurrentTime);
            cursor.Update(TimeManager.CurrentTime);
        }
Beispiel #23
0
        public void PerformLoadScn(string fileName, bool replace)
        {
            // This method is public because this method is called if the user drags a
            // .scnx onto the SpriteEditor

            #region Mark how many objects before loading in case there is an insertion.
            // If there is an insertion, only the newly-added objects should have post load
            // logic performed on them

            int numSpritesBefore         = GameData.Scene.Sprites.Count;
            int numOfSGsBefore           = GameData.Scene.SpriteGrids.Count;
            int numOfSpriteFramesBefore  = GameData.Scene.SpriteFrames.Count;
            int numberOfPositionedModels = GameData.Scene.PositionedModels.Count;

            #endregion

            SpriteEditorScene tempSES = SpriteEditorScene.FromFile(fileName);

            #region See if there are any Models that reference files that aren't on disk

            string sceneDirectory = FileManager.GetDirectory(fileName);
            for (int i = 0; i < tempSES.PositionedModelSaveList.Count; i++)
            {
                PositionedModelSave modelSave = tempSES.PositionedModelSaveList[i];

                if (!FileManager.FileExists(modelSave.ModelFileName))
                {
                    // See if there's a .x with that name

                    if (FileManager.FileExists(sceneDirectory + modelSave.ModelFileName + ".x"))
                    {
                        modelSave.ModelFileName = modelSave.ModelFileName + ".x";
                    }
                }
            }
            #endregion

            #region Now, see if there are any other files that haven't been found and create the error window

            List <string> texturesNotFound = tempSES.GetMissingFiles();
            if (texturesNotFound.Count != 0)
            {
                OkListWindow okListWindow = new OkListWindow(
                    "There are files that the .scnx references which cannot be located.",
                    "Error loading .scnx");

                foreach (string file in texturesNotFound)
                {
                    okListWindow.AddItem(file);
                }

                return;
            }
            #endregion

            #region if replacing, clear the old scene out
            if (replace)
            {
                SpriteManager.RemoveScene(GameData.Scene, true);
                FlatRedBallServices.Unload(GameData.SceneContentManager);

                tempSES.SetCamera(GameData.Camera);

#if FRB_MDX
                if (tempSES.CoordinateSystem == FlatRedBall.Math.CoordinateSystem.RightHanded)
                {
                    GameData.Camera.Z *= -1;
                }
#endif

                GameData.EditorProperties.PixelSize = tempSES.PixelSize;

                GuiData.EditorPropertiesGrid.Refresh();

                // 4/16/2011:  The following line of code
                // was causing errors when saving the .scnx
                // file through CTRL+S.  Taking it out because
                // I don't see why we need this anyway.
                // GameData.FileName = FileManager.RemoveExtension(fileName);
                GameData.FileName = fileName;
                FlatRedBallServices.Owner.Text = "SpriteEditor - Currently editing " + GameData.FileName;

                GuiData.MenuStrip.LastFileTypeLoaded = FileManager.GetExtension(fileName);
            }
            #endregion


            Scene newlyLoadedScene = tempSES.ToScene <EditorSprite>(GameData.SceneContentManager);

            GameData.Scene.AddToThis(newlyLoadedScene);
            // This caused
            // a double-add.
            // Not sure why we're
            // adding GameData.Scene.
            //GameData.Scene.AddToManagers();
            newlyLoadedScene.AddToManagers();

            GuiData.ListWindow.RefreshListsShown();

            #region Add the used Textures to the texture ListBox

            for (int i = numSpritesBefore; i < GameData.Scene.Sprites.Count; i++)
            {
                GuiData.ListWindow.Add(GameData.Scene.Sprites[i].Texture);
                GuiData.ListWindow.Add(GameData.Scene.Sprites[i].AnimationChains);
            }

            for (int i = numOfSpriteFramesBefore; i < GameData.Scene.SpriteFrames.Count; i++)
            {
                GuiData.ListWindow.Add(GameData.Scene.SpriteFrames[i].Texture);
                GuiData.ListWindow.Add(GameData.Scene.SpriteFrames[i].AnimationChains);
            }

            for (int i = numOfSGsBefore; i < GameData.Scene.SpriteGrids.Count; i++)
            {
                SpriteGrid sg = GameData.Scene.SpriteGrids[i];
                sg.PopulateGrid(GameData.Camera.X, GameData.Camera.Y, 0f);

                sg.RefreshPaint();
                List <Texture2D> texturesToAdd = sg.GetUsedTextures();
                foreach (Texture2D tex in texturesToAdd)
                {
                    GuiData.ListWindow.Add(tex);
                }
            }
            #endregion

            CheckForExtraFiles(FileManager.RemoveExtension(fileName));
            GameData.Scene.Sprites.SortZInsertionDescending();


            if (tempSES.AssetsRelativeToSceneFile)
            {
                FileManager.ResetRelativeToCurrentDirectory();
            }
        }
        public static LayeredTileMap FromTiledMapSave(string tiledMapSaveFile, string contentManager, TiledMapSave tms)
        {
            // Ultimately properties are tied to tiles by the tile name.
            // If a tile has no name but it has properties, those properties
            // will be lost in the conversion. Therefore, we have to add name properties.
            tms.MoveTypeToProperties();

#if DEBUG
            CheckForDuplicateTilesets(tms);
#endif

            tms.NameUnnamedTilesetTiles();
            tms.NameUnnamedObjects();


            string directory = FlatRedBall.IO.FileManager.GetDirectory(tiledMapSaveFile);

            var rtmi = ReducedTileMapInfo.FromTiledMapSave(
                tms, 1, 0, directory, FileReferenceType.Absolute);

            var toReturn = FromReducedTileMapInfo(rtmi, contentManager, tiledMapSaveFile);

            AddShapeCollections(toReturn, tms);

            foreach (var layer in tms.MapLayers)
            {
                var matchingLayer = toReturn.MapLayers.FirstOrDefault(item => item.Name == layer.Name);


                if (matchingLayer != null)
                {
                    if (layer is MapLayer)
                    {
                        var mapLayer = layer as MapLayer;
                        foreach (var propertyValues in mapLayer.properties)
                        {
                            matchingLayer.Properties.Add(new NamedValue
                            {
                                Name  = propertyValues.StrippedName,
                                Value = propertyValues.value,
                                Type  = propertyValues.Type
                            });
                        }

                        matchingLayer.Visible = mapLayer.visible == 1;
                        matchingLayer.Alpha   = mapLayer.Opacity;
                    }
                }
            }


            foreach (var tileset in tms.Tilesets)
            {
                foreach (var tile in tileset.TileDictionary.Values)
                {
                    int propertyCountFromTileset = 0;

                    if (tile.properties.Count != 0)
                    {
                        // this needs a name:
                        string name = tile.properties.FirstOrDefault(item => item.StrippedName.ToLowerInvariant() == "name")?.value;
                        // todo - eventually need to copy default values from the Tileset to the tile here
                        AddPropertiesToMap(tms, toReturn.TileProperties, tile.properties, null, name);
                    }
                }
            }

            foreach (var objectLayer in tms.objectgroup)
            {
                if (objectLayer.@object != null)
                {
                    foreach (var objectInstance in objectLayer.@object)
                    {
                        TMXGlueLib.Tileset tileset   = null;
                        int propertyCountFromTileset = 0;

                        var             objectProperties  = objectInstance.properties;
                        List <property> tilesetProperties = null;
                        if (objectInstance.gid != null)
                        {
                            var gidNoFlip = objectInstance.GidNoFlip;

                            tileset = tms.GetTilesetForGid(gidNoFlip.Value);
                            if (tileset.TileDictionary.ContainsKey(gidNoFlip.Value - tileset.Firstgid))
                            {
                                tilesetProperties        = tileset.TileDictionary[gidNoFlip.Value - tileset.Firstgid].properties;
                                propertyCountFromTileset = tilesetProperties.Count;
                            }
                        }


                        if (objectProperties.Count + propertyCountFromTileset != 0)
                        {
                            string name = objectInstance.Name;
                            // if name is null, check the properties:
                            if (string.IsNullOrEmpty(name))
                            {
                                name = objectProperties.FirstOrDefault(item => item.StrippedNameLower == "name")?.value;
                            }

                            var objectInstanceIsTile = objectInstance.gid != null;

                            if (objectInstanceIsTile)
                            {
                                AddPropertiesToMap(tms, toReturn.TileProperties, objectProperties, tilesetProperties, name);
                            }
                            else
                            {
                                AddPropertiesToMap(tms, toReturn.ShapeProperties, objectProperties, tilesetProperties, name);
                            }
                        }
                    }
                }
            }

            var tmxDirectory = FileManager.GetDirectory(tiledMapSaveFile);

            // add image layers
            foreach (var imageLayer in tms.ImageLayers)
            {
                var imageLayerFile = tmxDirectory + imageLayer.ImageObject.Source;
                var texture        = FlatRedBallServices.Load <Microsoft.Xna.Framework.Graphics.Texture2D>(imageLayerFile);

                var newSprite = new Sprite
                {
                    Texture = texture,
                    Width   = imageLayer.ImageObject.Width,
                    Height  = imageLayer.ImageObject.Height,
                    X       = imageLayer.ImageObject.Width / 2 + imageLayer.OffsetX,
                    Y       = -imageLayer.ImageObject.Height / 2 + imageLayer.OffsetY
                };

                var mdb = new MapDrawableBatch(1, texture);
                mdb.Alpha = imageLayer.Opacity;
                mdb.AttachTo(toReturn, false);
                mdb.Paste(newSprite);
                mdb.Visible = imageLayer.Visible;

                toReturn.mMapLists.Add(mdb);
            }

            var animationDictionary = new Dictionary <string, AnimationChain>();

            // add animations
            foreach (var tileset in tms.Tilesets)
            {
                string tilesetImageFile = tmxDirectory + tileset.Images[0].Source;

                if (tileset.SourceDirectory != ".")
                {
                    tilesetImageFile = tmxDirectory + tileset.SourceDirectory + tileset.Images[0].Source;
                }

                var texture = FlatRedBallServices.Load <Microsoft.Xna.Framework.Graphics.Texture2D>(tilesetImageFile, contentManager);

                foreach (var tile in tileset.Tiles.Where(item => item.Animation != null && item.Animation.Frames.Count != 0))
                {
                    var animation = tile.Animation;

                    var animationChain = new AnimationChain();
                    foreach (var frame in animation.Frames)
                    {
                        var animationFrame = new AnimationFrame();
                        animationFrame.FrameLength = frame.Duration / 1000.0f;
                        animationFrame.Texture     = texture;

                        int tileIdRelative = frame.TileId;
                        int globalTileId   = (int)(tileIdRelative + tileset.Firstgid);

                        int leftPixel;
                        int rightPixel;
                        int topPixel;
                        int bottomPixel;
                        TiledMapSave.GetPixelCoordinatesFromGid((uint)globalTileId, tileset, out leftPixel, out topPixel, out rightPixel, out bottomPixel);

                        animationFrame.LeftCoordinate  = MapDrawableBatch.CoordinateAdjustment + leftPixel / (float)texture.Width;
                        animationFrame.RightCoordinate = -MapDrawableBatch.CoordinateAdjustment + rightPixel / (float)texture.Width;

                        animationFrame.TopCoordinate    = MapDrawableBatch.CoordinateAdjustment + topPixel / (float)texture.Height;
                        animationFrame.BottomCoordinate = -MapDrawableBatch.CoordinateAdjustment + bottomPixel / (float)texture.Height;


                        animationChain.Add(animationFrame);
                    }

                    var property = tile.properties.FirstOrDefault(item => item.StrippedNameLower == "name");

                    if (property == null)
                    {
                        throw new InvalidOperationException(
                                  $"The tile with ID {tile.id} has an animation, but it doesn't have a Name property, which is required for animation.");
                    }
                    else
                    {
                        animationDictionary.Add(property.value, animationChain);
                    }
                }
            }

            toReturn.Animation = new LayeredTileMapAnimation(animationDictionary);

            AddTileShapeCollections(toReturn, tms);


            toReturn.MapProperties = tms.properties
                                     .Select(propertySave => new NamedValue
            {
                Name = propertySave.name, Value = propertySave.value, Type = propertySave.Type
            })
                                     .ToList();


            return(toReturn);
        }
Beispiel #25
0
        public static object ConvertStringValueToValueOfType(string value, string desiredType, string contentManagerName, bool trimQuotes)
        {
            value = value.Trim(); // this is in case there is a space in front - I don't think we need it.

            //Fix any exported CSV bugs (such as quotes around a boolean)
            if (trimQuotes ||
                (value != null && (desiredType != typeof(string).FullName && desiredType != typeof(char).FullName) &&
                 value.Contains("\"") == false)   // If it has a quote, then we don't want to trim.
                )
            {
                if (!value.StartsWith("new ") && desiredType != typeof(string).FullName)
                {
                    value = FlatRedBall.Utilities.StringFunctions.RemoveWhitespace(value);
                }
                value = value.Replace("\"", "");
            }

            // Do the conversion
            #region Convert To Object

            // String needs to be first because it could contain equals and
            // we don't want to cause problems
            bool   handled  = false;
            object toReturn = null;

            if (desiredType == typeof(string).FullName)
            {
                toReturn = value;
                handled  = true;
            }

            if (!handled)
            {
                TryHandleComplexType(value, desiredType, out handled, out toReturn);
            }

            if (!handled)
            {
                #region bool

                if (desiredType == typeof(bool).FullName)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return(false);
                    }

                    // value could be upper case like "TRUE" or "True".  Make it lower
                    value = value.ToLower();

                    toReturn = bool.Parse(value);
                    handled  = true;
                }

                #endregion

                #region int, Int32, Int16, uint, long

                else if (desiredType == typeof(int).FullName || desiredType == typeof(Int32).FullName || desiredType == typeof(Int16).FullName ||
                         desiredType == typeof(uint).FullName || desiredType == typeof(long).FullName || desiredType == typeof(byte).FullName)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return(0);
                    }


                    int indexOfDecimal = value.IndexOf('.');

                    if (value.IndexOf(",") != -1)
                    {
                        value = value.Replace(",", "");
                    }

                    #region uint
#if FRB_XNA
                    if (desiredType == typeof(uint).FullName)
                    {
                        if (indexOfDecimal == -1)
                        {
                            return(uint.Parse(value));
                        }
                        else
                        {
                            return((uint)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture))));
                        }
                    }
#endif
                    #endregion

                    #region byte
#if FRB_XNA
                    if (desiredType == typeof(byte).FullName)
                    {
                        if (indexOfDecimal == -1)
                        {
                            return(byte.Parse(value));
                        }
                        else
                        {
                            return((byte)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture))));
                        }
                    }
#endif
                    #endregion

                    #region long
                    if (desiredType == typeof(long).FullName)
                    {
                        if (indexOfDecimal == -1)
                        {
                            return(long.Parse(value));
                        }
#if FRB_XNA
                        else
                        {
                            return((long)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture))));
                        }
#endif
                    }

                    #endregion

                    #region regular int
                    else
                    {
                        if (indexOfDecimal == -1)
                        {
                            return(int.Parse(value));
                        }
#if FRB_XNA
                        else
                        {
                            return((int)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture))));
                        }
#endif
                    }
                    #endregion
                }

                #endregion

                #region float, Single

                else if (desiredType == typeof(float).FullName || desiredType == typeof(Single).FullName)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return(0f);
                    }

                    return(float.Parse(value, CultureInfo.InvariantCulture));
                }

                #endregion

                #region double

                else if (desiredType == typeof(double).FullName)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return(0.0);
                    }

                    return(double.Parse(value, CultureInfo.InvariantCulture));
                }

                #endregion


                #region Decimal

                else if (desiredType == typeof(decimal).FullName)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return(0.0m);
                    }

                    return(decimal.Parse(value, CultureInfo.InvariantCulture));
                }

                #endregion


#if !FRB_RAW
                #region Texture2D

                else if (desiredType == typeof(Texture2D).FullName)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return(null);
                    }
#if !SILVERLIGHT && !ZUNE
                    if (FileManager.IsRelative(value))
                    {
                        // Vic says:  This used to throw an exception on relative values.  I'm not quite
                        // sure why this is the case...why don't we just make it relative to the relative
                        // directory?  Maybe there's a reason to have this exception, but I can't think of
                        // what it is, and I'm writing a tutorial on how to load Texture2Ds from CSVs right
                        // now and it totally makes sense that the user would want to use a relative directory.
                        // In fact, the user will want to always use a relative directory so that their project is
                        // portable.
                        //throw new ArgumentException("Texture path must be absolute to load texture.  Path: " + value);
                        value = FileManager.RelativeDirectory + value;
                    }

                    // Try to load a compiled asset first
                    if (FileManager.FileExists(FileManager.RemoveExtension(value) + @".xnb"))
                    {
                        Texture2D texture =
                            FlatRedBallServices.Load <Texture2D>(FileManager.RemoveExtension(value), contentManagerName);


                        // Vic asks:  Why did we have to set the name?  This is redundant and gets
                        // rid of the standardized file name which causes caching to not work properly.
                        // texture.Name = FileManager.RemoveExtension(value);
                        return(texture);
                    }
                    else
                    {
                        Texture2D texture =
                            FlatRedBallServices.Load <Texture2D>(value, contentManagerName);

                        // Vic asks:  Why did we have to set the name?  This is redundant and gets
                        // rid of the standardized file name which causes caching to not work properly.
                        // texture.Name = value;
                        return(texture);
                    }
#else
                    return(null);
#endif
                }

                #endregion

                #region Matrix

                else if (desiredType == typeof(Matrix).FullName)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return(Matrix.Identity);
                    }

                    value = StripParenthesis(value);

                    // Split the string
                    string[] stringvalues = value.Split(new char[] { ',' });

                    if (stringvalues.Length != 16)
                    {
                        throw new ArgumentException("String to Matrix conversion requires 16 values, " +
                                                    "supplied string contains " + stringvalues.Length + " values", "value");
                    }

                    // Convert to floats
                    float[] values = new float[16];
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
                    }

                    // Parse to matrix
                    Matrix m = new Matrix(
                        values[0], values[1], values[2], values[3],
                        values[4], values[5], values[6], values[7],
                        values[8], values[9], values[10], values[11],
                        values[12], values[13], values[14], values[15]
                        );

                    return(m);
                }

                #endregion

                #region Vector2

                else if (desiredType == typeof(Vector2).FullName)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return(new Vector2(0, 0));
                    }

                    value = StripParenthesis(value);

                    // Split the string
                    string[] stringvalues = value.Split(new char[] { ',' });

                    if (stringvalues.Length != 2)
                    {
                        throw new ArgumentException("String to Vector2 conversion requires 2 values, " +
                                                    "supplied string contains " + stringvalues.Length + " values", "value");
                    }

                    // Convert to floats
                    float[] values = new float[2];
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
                    }

                    return(new Vector2(values[0], values[1]));
                }

                #endregion

                #region Vector3

                else if (desiredType == typeof(Vector3).FullName)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return(new Vector3(0, 0, 0));
                    }

                    value = StripParenthesis(value);


                    // Split the string
                    string[] stringvalues = value.Split(new char[] { ',' });

                    if (stringvalues.Length != 3)
                    {
                        throw new ArgumentException("String to Vector3 conversion requires 3 values, " +
                                                    "supplied string contains " + stringvalues.Length + " values", "value");
                    }

                    // Convert to floats
                    float[] values = new float[3];
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
                    }

                    return(new Vector3(values[0], values[1], values[2]));
                }

                #endregion

                #region Vector4

                else if (desiredType == typeof(Vector4).FullName)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        return(new Vector4(0, 0, 0, 0));
                    }

                    value = StripParenthesis(value);

                    // Split the string
                    string[] stringvalues = value.Split(new char[] { ',' });

                    if (stringvalues.Length != 4)
                    {
                        throw new ArgumentException("String to Vector4 conversion requires 4 values, " +
                                                    "supplied string contains " + stringvalues.Length + " values", "value");
                    }

                    // Convert to floats
                    float[] values = new float[4];
                    for (int i = 0; i < values.Length; i++)
                    {
                        values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
                    }

                    return(new Vector4(values[0], values[1], values[2], values[3]));
                }

                #endregion
#endif
                #region enum
                else if (IsEnum(desiredType))
                {
#if DEBUG
                    if (string.IsNullOrEmpty(value))
                    {
                        throw new InvalidOperationException("Error trying to create enum value for empty string.  Enum type: " + desiredType);
                    }
#endif


                    bool ignoreCase = true; // 3rd arugment needed for 360

                    Type foundType;

                    if (mUnqualifiedTypeDictionary.ContainsKey(desiredType))
                    {
                        foundType = mUnqualifiedTypeDictionary[desiredType];
                    }
                    else
                    {
                        foundType = TryToGetTypeFromAssemblies(desiredType);
                    }

                    return(Enum.Parse(foundType, value, ignoreCase)); // built-in .NET version
                    //return StringEnum.Parse(typeToConvertTo, value);
                }

                #endregion

                #region Color
#if FRB_XNA
                else if (desiredType == typeof(Color).FullName)
                {
#if WINDOWS_8 || UWP
                    PropertyInfo info = typeof(Color).GetProperty(value);
#else
                    PropertyInfo info = typeof(Color).GetProperty(value, BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static);
#endif

                    if (info == null)
                    {
                        if (value.StartsWith("Color."))
                        {
                            throw new Exception("Could not parse the value " + value + ".  Remove \"Color.\" and instead " +
                                                "use " + value.Substring("Color.".Length));
                        }
                        else
                        {
                            throw new Exception("Could not parse " + value + " as a Color");
                        }
                    }

                    toReturn = info.GetValue(null, null);
                    handled  = true;
                }
#endif
                #endregion

                #endregion

                // Why do we catch exceptions here?  That seems baaaad
                //catch (Exception)
                //{
                //    //int m = 3;
                //}


                if (!handled)
                {
                    throw new NotImplementedException("Cannot convert the value " + value + " to the type " +
                                                      desiredType.ToString());
                }
            }

            return(toReturn);
        }
        /*
         * This is the basic constructor for the GeometryWindow. It uses ToggleButtons instead of Buttons for a functionality aspect.
         * The desire was to have a single click on the button create 1 geometric shape, and then have the button
         * reset itself to the off position. The Button class may be used, but as of August 2nd, 2008, I don't believe has the
         * support for the desired functionality - Aaron
         */
        public GeometryWindow()
            : base()
        {
            base.mName   = "Geometry";
            NumberOfRows = 5;

            this.X = SpriteManager.Camera.XEdge * 2 - this.ScaleX;
            this.Y = 19.0f;

            this.ExtraSpacingBetweenSameRowButtons = .2f;

            #region Add AxisAlignedRectangle
            this.mAxisAlignedRectangleButton      = AddButton(Keys.P);
            this.mAxisAlignedRectangleButton.Text = "AxisAlignedRectangle (P)";
            mAxisAlignedRectangleButton.SetOverlayTextures(FlatRedBallServices.Load <Texture2D>(@"Assets\UI\AxisAlignedRectangle.png"), null);
            mAxisAlignedRectangleButton.Click += AddAxisAlignedRectangle;
            #endregion

            #region Add Circle
            this.mCircleButton      = AddButton(Keys.O);
            this.mCircleButton.Text = "Circle (O)";
            mCircleButton.SetOverlayTextures(FlatRedBallServices.Load <Texture2D>(@"Assets\UI\Circle.png"), null);
            mCircleButton.Click += AddCircle;
            #endregion

            #region Add Polygon (Rectangle)

            this.mRectanglePolygonButton      = AddButton(Keys.I);
            this.mRectanglePolygonButton.Text = "Rectangle Polygon (I)";
            mRectanglePolygonButton.SetOverlayTextures(FlatRedBallServices.Load <Texture2D>(@"Assets\UI\RectanglePolygon.png"), null);
            mRectanglePolygonButton.Click += AddRectanglePolygon;

            #endregion

            #region Add AxisAlignedCube

            this.mAxisAlignedCubeButton      = AddButton(Keys.U);
            this.mAxisAlignedCubeButton.Text = "AxisAlignedCube (U)";
            mAxisAlignedCubeButton.SetOverlayTextures(FlatRedBallServices.Load <Texture2D>(@"Assets\UI\AxisAlignedCube.png"), null);
            mAxisAlignedCubeButton.Click += AddAxisAlignedCube;

            #endregion

            #region Add Sphere

            this.mSphereButton      = AddButton(Keys.Y);
            this.mSphereButton.Text = "Sphere (Y)";
            mSphereButton.SetOverlayTextures(FlatRedBallServices.Load <Texture2D>(@"Assets\UI\Sphere.png"), null);
            mSphereButton.Click += AddSphere;

            #endregion

            #region Edit AxisAlignedRectangle

            mEditAxisAlignedRectangleButton = AddToggleButton();
            mEditAxisAlignedRectangleButton.SetText("Currently NOT editing Axis Aligned Rectangles", "Currently editing Axis Aligned Rectangles");
            Texture2D texture = FlatRedBallServices.Load <Texture2D>(@"Assets\UI\EditAxisAlignedRectangle.png");
            mEditAxisAlignedRectangleButton.SetOverlayTextures(
                FlatRedBallServices.Load <Texture2D>(@"Assets\UI\NoEditAxisAlignedRectangle.png"),
                texture
                );
            mEditAxisAlignedRectangleButton.Press();
            #endregion

            #region Edit Circle
            mEditCircleButton = AddToggleButton();
            mEditCircleButton.SetText("Currently NOT editing Circles", "Currently editing Circles");
            texture = FlatRedBallServices.Load <Texture2D>(@"Assets\UI\EditCircle.png");
            mEditCircleButton.SetOverlayTextures(FlatRedBallServices.Load <Texture2D>(@"Assets\UI\NoEditCircle.png"), texture);
            mEditCircleButton.Press();
            #endregion

            #region Edit Polygon
            mEditPolygonButton = AddToggleButton();
            mEditPolygonButton.SetText("Currently NOT editing Polygons", "Currently editing Polygons");
            texture = FlatRedBallServices.Load <Texture2D>(@"Assets\UI\EditPolygon.png");
            mEditPolygonButton.SetOverlayTextures(FlatRedBallServices.Load <Texture2D>(@"Assets\UI\NoEditPolygon.png"), texture);
            mEditPolygonButton.Press();
            #endregion

            #region Edit AxisAlignedCube
            mEditAxisAlignedCubeButton = AddToggleButton();
            mEditAxisAlignedCubeButton.SetText("Currently NOT editing Axis Aligned Cubes", "Currently editing Axis Aligned Cubes");
            texture = FlatRedBallServices.Load <Texture2D>(@"Assets\UI\EditAxisAlignedCube.png");
            mEditAxisAlignedCubeButton.SetOverlayTextures(FlatRedBallServices.Load <Texture2D>(@"Assets\UI\NoEditAxisAlignedCube.png"), texture);
            mEditAxisAlignedCubeButton.Press();
            #endregion

            #region Edit Sphere
            mEditSphereButton = AddToggleButton();
            mEditSphereButton.SetText("Currently NOT editing Spheres", "Currently editing Spheres");
            texture = FlatRedBallServices.Load <Texture2D>(@"Assets\UI\EditSphere.png");
            mEditSphereButton.SetOverlayTextures(FlatRedBallServices.Load <Texture2D>(@"Assets\UI\NoEditSphere.png"), texture);
            mEditSphereButton.Press();
            #endregion
        }