TextureAtlasReader.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #region License
  2. // Copyright 2016 Kastellanos Nikolaos
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using Microsoft.Xna.Framework;
  18. using Microsoft.Xna.Framework.Content;
  19. using Microsoft.Xna.Framework.Graphics;
  20. using tainicom.Aether.Atlas;
  21. namespace tainicom.Aether.Graphics.Content
  22. {
  23. public class TextureAtlasReader : ContentTypeReader<TextureAtlas>
  24. {
  25. protected override TextureAtlas Read(ContentReader input, TextureAtlas existingInstance)
  26. {
  27. System.Diagnostics.Debugger.Launch();
  28. IGraphicsDeviceService graphicsDeviceService = (IGraphicsDeviceService)input.ContentManager.ServiceProvider.GetService(typeof(IGraphicsDeviceService));
  29. var device = graphicsDeviceService.GraphicsDevice;
  30. TextureAtlas output = existingInstance ?? new TextureAtlas();
  31. // read standard Texture2D
  32. output.Texture = ReadTexture2D(input, output.Texture);
  33. // read Sprites
  34. var count = input.ReadInt32();
  35. for (int i = 0; i < count; i++)
  36. {
  37. var name = input.ReadString();
  38. var destinationRect = new Rectangle(input.ReadInt32(), input.ReadInt32(), input.ReadInt32(), input.ReadInt32());
  39. output.Sprites[name] = new Sprite(output.Texture, destinationRect);
  40. }
  41. return output;
  42. }
  43. private Texture2D ReadTexture2D(ContentReader input, Texture2D existingInstance)
  44. {
  45. Texture2D output = null;
  46. try
  47. {
  48. output = input.ReadRawObject<Texture2D>(existingInstance);
  49. }
  50. catch(NotSupportedException)
  51. {
  52. var assembly = typeof(Microsoft.Xna.Framework.Content.ContentTypeReader).Assembly;
  53. var texture2DReaderType = assembly.GetType("Microsoft.Xna.Framework.Content.Texture2DReader");
  54. var texture2DReader = (ContentTypeReader)Activator.CreateInstance(texture2DReaderType, true);
  55. output = input.ReadRawObject<Texture2D>(texture2DReader, existingInstance);
  56. }
  57. return output;
  58. }
  59. }
  60. }