Apidcloud

Loading Bar - Gibbo2D

Jul 10th, 2015
308
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #region Copyrights
  2. /*
  3. Gibbo2D License - Version 1.0
  4. Copyright (c) 2013 - Gibbo2D Team
  5. Founders Joao Alves <joao.cpp.sca@gmail.com> & Luis Fernandes <luisapidcloud@hotmail.com>
  6.  
  7. Permission is granted to use this software and associated documentation files (the "Software") free of charge,
  8. to any person or company. The code can be used, modified and merged without restrictions, but you cannot sell
  9. the software itself and parts where this license applies. Still, permission is granted for anyone to sell
  10. applications made using this software (for example, a game). This software cannot be claimed as your own,
  11. except for copyright holders. This license notes should also be available on any of the changed or added files.
  12.  
  13. The software is provided "as is", without warranty of any kind, express or implied, including but not limited to
  14. the warranties of merchantability, fitness for a particular purpose and non-infrigement. In no event shall the
  15. authors or copyright holders be liable for any claim, damages or other liability.
  16.  
  17. The license applies to all versions of the software, both newer and older than the one listed, unless a newer copy
  18. of the license is available, in which case the most recent copy of the license supercedes all others.
  19.  
  20. */
  21. #endregion
  22.  
  23. using System;
  24. using Gibbo.Library;
  25. using System.Threading.Tasks;
  26. using System.IO;
  27. using Microsoft.Xna.Framework.Graphics;
  28. using Microsoft.Xna.Framework;
  29. using System.Threading;
  30.  
  31. namespace Samples
  32. {
  33.     /// <summary>
  34.     /// Sample controller.
  35.     ///
  36.     /// Notice:
  37.     /// If you want the controller to be updated / drawn in the editor,
  38.     /// implement ExtendedObjectComponent instead.
  39.     /// </summary>
  40.     class LoadingBar : ObjectComponent
  41.     {
  42.         #region fields
  43.  
  44.         private readonly float WINDOW_WIDTH = SceneManager.GraphicsDevice.Viewport.Width;
  45.         private readonly float WINDOW_HEIGHT = SceneManager.GraphicsDevice.Viewport.Height;
  46.  
  47.         private const int BAR_WIDTH = 300;
  48.         private const int BAR_HEIGHT = 50;
  49.  
  50.         private const int OFFSET_X = 2;
  51.         private const int OFFSET_Y = 2;
  52.  
  53.         private Task _task;
  54.         private CancellationTokenSource _cancellationTokenSource;
  55.         private CancellationToken _cancellationToken;
  56.  
  57.         private Texture2D _textureBack, _textureLoading;
  58.  
  59.         private Color _colorLoadingBackground = Color.White;
  60.         private Color _colorLoading = Color.CornflowerBlue;
  61.  
  62.         // Loading bar current width and height
  63.         private int _currentWidth = 0;
  64.         private int _currentHeight = BAR_HEIGHT - OFFSET_Y * 2; // height is fixed, since it's a horizontal loading bar
  65.  
  66.         // Loading percentage
  67.         private float _percentage = 0.0f;
  68.  
  69.         private int _posX, _posY;
  70.  
  71.         #endregion
  72.  
  73.         #region Properties
  74.  
  75.         public Color ColorLoadingBackground
  76.         {
  77.             get { return _colorLoadingBackground; }
  78.             set { _colorLoadingBackground = value; }
  79.         }
  80.  
  81.         public Color ColorLoading
  82.         {
  83.             get { return _colorLoading; }
  84.             set { _colorLoading = value; }
  85.         }
  86.        
  87.         #endregion
  88.  
  89.         #region methods
  90.  
  91.         /// <summary>
  92.         /// Initialize this instance.
  93.         /// </summary>
  94.         public override void Initialize()
  95.         {
  96.             // create back texture
  97.             _textureBack = new Texture2D(SceneManager.ActiveScene.Graphics.GraphicsDevice, 1, 1);
  98.             _textureBack.SetData<Color>(new Color[] { ColorLoadingBackground });
  99.  
  100.             // create loading texture
  101.             _textureLoading = new Texture2D(SceneManager.ActiveScene.Graphics.GraphicsDevice, 1, 1);
  102.             _textureLoading.SetData<Color>(new Color[] { ColorLoading });
  103.  
  104.             // calculate and store the position of the textures (center both horitontally and vertically)
  105.             _posX = (int)(WINDOW_WIDTH / 2 - BAR_WIDTH / 2);
  106.             _posY = (int)(WINDOW_HEIGHT / 2 - BAR_HEIGHT / 2);
  107.  
  108.             // subscribe to exiting event, in order to properly cancel the task created below if needed
  109.             SceneManager.GameWindow.Exiting += GameWindow_Exiting;
  110.  
  111.             // create cancellation tokens in order to cancel the task created below
  112.             _cancellationTokenSource = new CancellationTokenSource();
  113.             _cancellationToken = _cancellationTokenSource.Token;
  114.  
  115.             // create and run task using the cancellation token above
  116.             _task = Task.Factory.StartNew(() => LoadContent(), _cancellationToken);
  117.  
  118.         }
  119.  
  120.         /// <summary>
  121.         /// Load Content to memory. Useful when loading heavy scenes.
  122.         /// </summary>
  123.         private void LoadContent()
  124.         {
  125.             // Retrieve every file from Content folder
  126.             string[] files = Directory.GetFiles(SceneManager.GameProject.ProjectPath + @"\Content\", "*", SearchOption.AllDirectories);
  127.  
  128.             int done = 0;
  129.  
  130.             // iterate through every file
  131.             foreach (var file in files)
  132.             {
  133.                 // break the loop if cancellation was requested
  134.                 if (_cancellationToken.IsCancellationRequested)
  135.                 {
  136.                     break;
  137.                 }
  138.  
  139.                 // Load file to memory
  140.                 TextureLoader.FromFile(file);
  141.  
  142.                 // calculate percentage based on the loaded files
  143.                 _percentage = ++done * 100 / files.Length;
  144.  
  145.                 Console.WriteLine(_percentage.ToString());
  146.             }
  147.         }
  148.  
  149.         public override void Update(GameTime gameTime)
  150.         {
  151.             // update bars width based on loading percentage
  152.             _currentWidth = (int)(_percentage * (BAR_WIDTH - OFFSET_X * 2) / 100);
  153.         }
  154.  
  155.         /// <summary>
  156.         /// Component Draw
  157.         /// </summary>
  158.         /// <param name="gameTime">Game time.</param>
  159.         /// <param name="spriteBatch">Sprite batch.</param>
  160.         public override void Draw(Microsoft.Xna.Framework.GameTime gameTime, Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch)
  161.         {
  162.             spriteBatch.Begin();
  163.  
  164.             spriteBatch.Draw(_textureBack, new Rectangle(_posX, _posY, BAR_WIDTH, BAR_HEIGHT), Color.White);
  165.  
  166.             spriteBatch.Draw(_textureLoading, new Rectangle(_posX + OFFSET_X, _posY + OFFSET_Y, _currentWidth, _currentHeight), Color.White);
  167.  
  168.             spriteBatch.End();
  169.         }
  170.  
  171.         void GameWindow_Exiting(object sender, EventArgs e)
  172.         {
  173.             if (!_task.IsCompleted)
  174.             {
  175.                 Console.WriteLine("Cancel Called");
  176.                 _cancellationTokenSource.Cancel();
  177.             }
  178.  
  179.             _cancellationTokenSource.Dispose();
  180.         }
  181.  
  182.         #endregion
  183.     }
  184. }
RAW Paste Data