private void TestBtn_Click(object sender, RoutedEventArgs e) { var ShowError = new Action <string>((errMsg) => MessageBox.Show(errMsg, "Error", MessageBoxButton.OK, MessageBoxImage.Error)); var isIncludeExtension = IsIncludeFileTypeCB.IsChecked.GetValueOrDefault(); var isIgnoreExtensionCheck = IsIgnoreExtensionCheck.IsChecked.GetValueOrDefault(); var file = TestInputTxt.Text; var filename = isIncludeExtension ? Path.GetFileName(file) : Path.GetFileNameWithoutExtension(file); var outputName = BuildFilename(filename); var outputFile = outputName + (isIncludeExtension ? "" : Path.GetExtension(file)); if (isIncludeExtension && !isIgnoreExtensionCheck) { //verify output file got extension if (!Path.HasExtension(outputFile)) { ShowError($"Resulting output filename does not have extension.\nOutput: {outputFile} for InputFile: {filename}"); } } TestOutputTxt.Text = outputFile; }
/// <summary> /// Converts the specified PDF file into an XPS file. The new file is stored in the same directory. /// </summary> public static void Convert(string xpsFilename) { if (String.IsNullOrEmpty(xpsFilename)) { throw new ArgumentNullException("xpsFilename"); } if (!File.Exists(xpsFilename)) { throw new FileNotFoundException("File not found.", xpsFilename); } string pdfFilename = xpsFilename; if (IOPath.HasExtension(pdfFilename)) { pdfFilename = pdfFilename.Substring(0, pdfFilename.LastIndexOf('.')); } pdfFilename += ".pdf"; Convert(xpsFilename, pdfFilename, 0); }
private void appendFileToList(string path) { FileList list = (FileList)FindResource("FileListData"); if (Path.HasExtension(path) == false || list.Count >= 15) { return; } string filename = Path.GetFileNameWithoutExtension(path); string ext = System.IO.Path.GetExtension(path); string basename = filename.ToUpper().PadRight(8).Substring(0, 8) + ext.ToUpper().PadRight(4).Substring(1, 3); FileInfo info = new FileInfo(path); if (totalBytesUsed + info.Length >= 1464320) { return; } list.Add(new FileObject(basename, (int)info.Length, path)); totalBytesUsed += (int)info.Length; updateStorage(); }
public bool ChangeName(string fileName) { BuildExceptions.NotNullNotEmpty(fileName, "fileName"); if (this.IsValid) { if (IoPath.HasExtension(fileName)) { _path = IoPath.Combine(IoPath.GetDirectoryName(_path), fileName); } else { string extension = IoPath.GetExtension(_path); _path = IoPath.Combine(IoPath.GetDirectoryName(_path), fileName + extension); } return(true); } return(false); }
/// <summary> /// Determines whether or not a file path contains an extension. /// </summary> /// <param name="path">Path to check for an extension.</param> public static bool HasExtension(string path) { return(Path.HasExtension(path)); }
public static void Convert(string xpsFilename, string pdfFilename, int docIndex, bool createComparisonDocument) { if (String.IsNullOrEmpty(xpsFilename)) { throw new ArgumentNullException("xpsFilename"); } if (String.IsNullOrEmpty(pdfFilename)) { pdfFilename = xpsFilename; if (IOPath.HasExtension(pdfFilename)) { pdfFilename = pdfFilename.Substring(0, pdfFilename.LastIndexOf('.')); } pdfFilename += ".pdf"; } using (var xpsDocument = new XpsDocument(xpsFilename, FileAccess.Read)) { Convert(xpsDocument, pdfFilename, docIndex); } if (!createComparisonDocument) { return; } try { using (var xpsDoc = new XpsDocument(xpsFilename, FileAccess.Read)) { var docSeq = xpsDoc.GetFixedDocumentSequence(); if (docSeq == null) { throw new InvalidOperationException("docSeq"); } XPdfForm form = XPdfForm.FromFile(pdfFilename); PdfDocument pdfComparisonDocument = new PdfDocument(); var pageIndex = 0; var refs = docSeq.References; var docs = refs.Select(r => r.GetDocument(false)); foreach (var doc in docs) { foreach (var page in doc.Pages) { Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); PdfPage pdfPage = pdfComparisonDocument.AddPage(); double width = page.Width; double height = page.Height; pdfPage.Width = page.Width * 2; pdfPage.Height = page.Height; DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageIndex); //byte[] png = PngFromPage(docPage, 96); BitmapSource bmsource = BitmapSourceFromPage(docPage, 96 * 2); XImage image = XImage.FromBitmapSource(bmsource); XGraphics gfx = XGraphics.FromPdfPage(pdfPage); form.PageIndex = pageIndex; gfx.DrawImage(form, 0, 0, width, height); gfx.DrawImage(image, width, 0, width, height); //renderer.RenderPage(pdfPage, page); pageIndex++; } } string pdfComparisonFilename = pdfFilename; if (IOPath.HasExtension(pdfComparisonFilename)) { pdfComparisonFilename = pdfComparisonFilename.Substring(0, pdfComparisonFilename.LastIndexOf('.')); } pdfComparisonFilename += "-comparison.pdf"; pdfComparisonDocument.ViewerPreferences.FitWindow = true; //pdfComparisonDocument.PageMode = PdfPageMode. pdfComparisonDocument.PageLayout = PdfPageLayout.SinglePage; pdfComparisonDocument.Save(pdfComparisonFilename); } } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } }
/// <summary> /// Implements the PDF file to XPS file conversion. /// </summary> public static void Convert(string xpsFilename, string pdfFilename, int docIndex, bool createComparisonDocument) { if (String.IsNullOrEmpty(xpsFilename)) { throw new ArgumentNullException("xpsFilename"); } if (String.IsNullOrEmpty(pdfFilename)) { pdfFilename = xpsFilename; if (IOPath.HasExtension(pdfFilename)) { pdfFilename = pdfFilename.Substring(0, pdfFilename.LastIndexOf('.')); } pdfFilename += ".pdf"; } XpsDocument xpsDocument = null; try { xpsDocument = XpsDocument.Open(xpsFilename); FixedDocument fixedDocument = xpsDocument.GetDocument(); PdfDocument pdfDocument = new PdfDocument(); PdfRenderer renderer = new PdfRenderer(); int pageIndex = 0; foreach (FixedPage page in fixedDocument.Pages) { if (page == null) { continue; } Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); PdfPage pdfPage = renderer.CreatePage(pdfDocument, page); renderer.RenderPage(pdfPage, page); pageIndex++; #if DEBUG // stop at page... if (pageIndex == 50) { break; } #endif } pdfDocument.Save(pdfFilename); xpsDocument.Close(); xpsDocument = null; if (createComparisonDocument) { System.Windows.Xps.Packaging.XpsDocument xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFilename, FileAccess.Read); System.Windows.Documents.FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence(); if (docSeq == null) { throw new InvalidOperationException("docSeq"); } XPdfForm form = XPdfForm.FromFile(pdfFilename); PdfDocument pdfComparisonDocument = new PdfDocument(); pageIndex = 0; foreach (PdfPage page in pdfDocument.Pages) { if (page == null) { continue; } Debug.WriteLine(String.Format(" doc={0}, page={1}", docIndex, pageIndex)); PdfPage pdfPage = /*renderer.CreatePage(pdfComparisonDocument, page);*/ pdfComparisonDocument.AddPage(); double width = page.Width; double height = page.Height; pdfPage.Width = page.Width * 2; pdfPage.Height = page.Height; DocumentPage docPage = docSeq.DocumentPaginator.GetPage(pageIndex); //byte[] png = PngFromPage(docPage, 96); BitmapSource bmsource = BitmapSourceFromPage(docPage, 96 * 2); XImage image = XImage.FromBitmapSource(bmsource); XGraphics gfx = XGraphics.FromPdfPage(pdfPage); form.PageIndex = pageIndex; gfx.DrawImage(form, 0, 0, width, height); gfx.DrawImage(image, width, 0, width, height); //renderer.RenderPage(pdfPage, page); pageIndex++; #if DEBUG // stop at page... if (pageIndex == 50) { break; } #endif } string pdfComparisonFilename = pdfFilename; if (IOPath.HasExtension(pdfComparisonFilename)) { pdfComparisonFilename = pdfComparisonFilename.Substring(0, pdfComparisonFilename.LastIndexOf('.')); } pdfComparisonFilename += "-comparison.pdf"; pdfComparisonDocument.ViewerPreferences.FitWindow = true; //pdfComparisonDocument.PageMode = PdfPageMode. pdfComparisonDocument.PageLayout = PdfPageLayout.SinglePage; pdfComparisonDocument.Save(pdfComparisonFilename); } } catch (Exception ex) { Debug.WriteLine(ex.Message); if (xpsDocument != null) { xpsDocument.Close(); } throw; } finally { if (xpsDocument != null) { xpsDocument.Close(); } } }
protected T ReadAsset <T>(string assetName, Action <IDisposable> recordDisposableObject) { if (string.IsNullOrEmpty(assetName)) { throw new ArgumentNullException(); } if (disposed) { throw new ObjectDisposedException("ContentManager"); } string originalAssetName = assetName; object result = null; if (this.graphicsDeviceService == null) { this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService; if (this.graphicsDeviceService == null) { throw new InvalidOperationException("No Graphics Device Service"); } } // Replace Windows path separators with local path separators assetName = Path.Combine(_rootDirectory, assetName.Replace('\\', Path.DirectorySeparatorChar)); // Get the real file name if ((typeof(T) == typeof(Texture2D))) { assetName = Texture2DReader.Normalize(assetName); } else if ((typeof(T) == typeof(SpriteFont))) { assetName = SpriteFontReader.Normalize(assetName); } else if ((typeof(T) == typeof(Effect))) { assetName = Effect.Normalize(assetName); } else if ((typeof(T) == typeof(Song))) { assetName = SongReader.Normalize(assetName); } else if ((typeof(T) == typeof(SoundEffect))) { assetName = SoundEffectReader.Normalize(assetName); } else if ((typeof(T) == typeof(Video))) { assetName = Video.Normalize(assetName); } else { throw new NotSupportedException("Format not supported"); } if (string.IsNullOrEmpty(assetName)) { throw new ContentLoadException("Could not load " + originalAssetName + " asset!"); } if (!Path.HasExtension(assetName)) { assetName = string.Format("{0}.xnb", assetName); } if (Path.GetExtension(assetName).ToUpper() == ".XNB") { // Load a XNB file //Loads from Assets directory + /assetName Stream stream = OpenStream(assetName); BinaryReader xnbReader = new BinaryReader(stream); // The first 4 bytes should be the "XNB" header. i use that to detect an invalid file byte[] headerBuffer = new byte[3]; xnbReader.Read(headerBuffer, 0, 3); string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 3); byte platform = xnbReader.ReadByte(); if (string.Compare(headerString, "XNB") != 0 || !(platform == 'w' || platform == 'x' || platform == 'm')) { throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?"); } ushort version = xnbReader.ReadUInt16(); int graphicsProfile = version & 0x7f00; version &= 0x80ff; bool compressed = false; if (version == 0x8005 || version == 0x8004) { compressed = true; } else if (version != 5 && version != 4) { throw new ContentLoadException("Invalid XNB version"); } // The next int32 is the length of the XNB file int xnbLength = xnbReader.ReadInt32(); ContentReader reader; if (compressed) { //decompress the xnb //thanks to ShinAli (https://bitbucket.org/alisci01/xnbdecompressor) int compressedSize = xnbLength - 14; int decompressedSize = xnbReader.ReadInt32(); int newFileSize = decompressedSize + 10; MemoryStream decompressedStream = new MemoryStream(decompressedSize); LzxDecoder dec = new LzxDecoder(16); int decodedBytes = 0; int pos = 0; while (pos < compressedSize) { // let's seek to the correct position stream.Seek(pos + 14, SeekOrigin.Begin); int hi = stream.ReadByte(); int lo = stream.ReadByte(); int block_size = (hi << 8) | lo; int frame_size = 0x8000; if (hi == 0xFF) { hi = lo; lo = (byte)stream.ReadByte(); frame_size = (hi << 8) | lo; hi = (byte)stream.ReadByte(); lo = (byte)stream.ReadByte(); block_size = (hi << 8) | lo; pos += 5; } else { pos += 2; } if (block_size == 0 || frame_size == 0) { break; } int lzxRet = dec.Decompress(stream, block_size, decompressedStream, frame_size); pos += block_size; decodedBytes += frame_size; } if (decompressedStream.Position != decompressedSize) { throw new ContentLoadException("Decompression of " + originalAssetName + "failed. " + " Try decompressing with nativeDecompressXnb first."); } decompressedStream.Seek(0, SeekOrigin.Begin); reader = new ContentReader(this, decompressedStream, this.graphicsDeviceService.GraphicsDevice); } else { 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(); } else { if ((typeof(T) == typeof(Texture2D))) { //Basically the same as Texture2D.FromFile but loading from the assets instead of a filePath Stream assetStream = OpenStream(assetName); Bitmap image = BitmapFactory.DecodeStream(assetStream); ESImage theTexture = new ESImage(image, graphicsDeviceService.GraphicsDevice.PreferedFilter); result = new Texture2D(theTexture) { Name = Path.GetFileNameWithoutExtension(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 * //Loads from Assets directory + /assetName * Stream assetStream = OpenStream(assetName); * * 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 * 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(); * assetStream.Close(); * }*/ if (result == null) { throw new ContentLoadException("Could not load " + originalAssetName + " asset!"); } // Store references to the asset for later use T asset = (T)result; if (asset is IDisposable && recordDisposableObject != null) { recordDisposableObject(asset as IDisposable); } else { disposableAssets.Add(asset as IDisposable); } loadedAssets.Add(originalAssetName, asset); return((T)result); }
protected T ReadAsset <T>(string assetName, Action <IDisposable> recordDisposableObject, int lod = 0) { if (string.IsNullOrEmpty(assetName)) { throw new ArgumentNullException("assetName"); } if (disposed) { throw new ObjectDisposedException("ContentManager"); } //GC.GetTotalMemory(true); //Process currentProcess = System.Diagnostics.Process.GetCurrentProcess(); //long memstart = currentProcess.WorkingSet64; 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"); } } // Replace Windows path separators with local path separators assetName = GetRealFilename <T>(assetName); if (string.IsNullOrEmpty(assetName)) { throw new ContentLoadException("Could not load " + originalAssetName + " asset!"); } if (!Path.HasExtension(assetName)) { assetName = string.Format("{0}.xnb", assetName); } if (Path.GetExtension(assetName).ToLower() == ".xnb") { // Load a XNB file using (Stream stream = OpenStream(assetName)) { using (BinaryReader xnbReader = new BinaryReader(stream)) { // The first 4 bytes should be the "XNB" header. i use that to detect an invalid file byte[] headerBuffer = new byte[3]; xnbReader.Read(headerBuffer, 0, 3); string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 3); byte platform = xnbReader.ReadByte(); if (string.Compare(headerString, "XNB") != 0 || !(platform == 'w' || platform == 'x' || platform == 'm')) { throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?"); } ushort version = xnbReader.ReadUInt16(); int graphicsProfile = version & 0x7f00; version &= 0x80ff; bool compressed = false; if (version == 0x8005 || version == 0x8004) { compressed = true; } else if (version != 5 && version != 4) { throw new ContentLoadException("Invalid XNB version"); } // The next int32 is the length of the XNB file int xnbLength = xnbReader.ReadInt32(); ContentReader reader; if (compressed) { //decompress the xnb //thanks to ShinAli (https://bitbucket.org/alisci01/xnbdecompressor) int compressedSize = xnbLength - 14; int decompressedSize = xnbReader.ReadInt32(); int newFileSize = decompressedSize + 10; MemoryStream decompressedStream = new MemoryStream(decompressedSize); LzxDecoder dec = new LzxDecoder(16); int decodedBytes = 0; int pos = 0; while (pos < compressedSize) { // let's seek to the correct position stream.Seek(pos + 14, SeekOrigin.Begin); int hi = stream.ReadByte(); int lo = stream.ReadByte(); int block_size = (hi << 8) | lo; int frame_size = 0x8000; if (hi == 0xFF) { hi = lo; lo = (byte)stream.ReadByte(); frame_size = (hi << 8) | lo; hi = (byte)stream.ReadByte(); lo = (byte)stream.ReadByte(); block_size = (hi << 8) | lo; pos += 5; } else { pos += 2; } if (block_size == 0 || frame_size == 0) { break; } int lzxRet = dec.Decompress(stream, block_size, decompressedStream, frame_size); pos += block_size; decodedBytes += frame_size; } if (decompressedStream.Position != decompressedSize) { throw new ContentLoadException("Decompression of " + originalAssetName + "failed. " + " Try decompressing with nativeDecompressXnb first."); } decompressedStream.Seek(0, SeekOrigin.Begin); reader = new ContentReader(this, decompressedStream, this.graphicsDeviceService.GraphicsDevice); } else { reader = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice); } using (reader) { 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); } } } } else { if ((typeof(T) == typeof(Texture2D))) { using (Stream assetStream = OpenStream(assetName)) { Texture2D texture = Texture2D.FromFile(graphicsDeviceService.GraphicsDevice, assetStream, lod); texture.Name = originalAssetName; result = texture; } } else if ((typeof(T) == typeof(SpriteFont))) { //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null); throw new NotImplementedException(); } else if ((typeof(T) == typeof(Song))) { result = new Song(assetName); } else if ((typeof(T) == typeof(SoundEffect))) { result = new SoundEffect(assetName); } else if ((typeof(T) == typeof(Video))) { result = new Video(assetName); } else if ((typeof(T) == typeof(Effect))) { result = new Effect(graphicsDeviceService.GraphicsDevice, assetName); } } if (result == null) { throw new ContentLoadException("Could not load " + originalAssetName + " asset!"); } // Store references to the asset for later use T asset = (T)result; if (asset is IDisposable) { if (recordDisposableObject != null) { recordDisposableObject(asset as IDisposable); } else { disposableAssets.Add(asset as IDisposable); } } loadedAssets.Add(originalAssetName, asset); //GC.GetTotalMemory(true); //var memend = currentProcess.WorkingSet64; //Console.WriteLine("mem: " + assetName + ", " + (memend -memstart).ToString()); return((T)result); }
private void ExecuteBtn_Click(object sender, RoutedEventArgs e) { var ShowError = new Action <string>((errMsg) => MessageBox.Show(errMsg, "Error", MessageBoxButton.OK, MessageBoxImage.Error)); var inputDir = InputDirectoryTxt.Text; var outputDir = OutputDirectoryTxt.Text; if (!Directory.Exists(inputDir)) { ShowError("Input directory does not exist"); return; } if (!Directory.Exists(outputDir)) { ShowError("Output directory does not exist"); return; } var isIncludeExtension = IsIncludeFileTypeCB.IsChecked.GetValueOrDefault(); var isIgnoreExtensionCheck = IsIgnoreExtensionCheck.IsChecked.GetValueOrDefault(); var inputFiles = Directory.GetFiles(inputDir); var outputFiles = new List <string>(); foreach (var file in inputFiles) { var filename = isIncludeExtension ? Path.GetFileName(file) : Path.GetFileNameWithoutExtension(file); var outputName = BuildFilename(filename); var outputFile = $"{outputDir}/{outputName}" + (isIncludeExtension ? "" : Path.GetExtension(file)); if (isIncludeExtension && !isIgnoreExtensionCheck) { //verify output file got extension if (!Path.HasExtension(outputFile)) { ShowError($"Resulting output filename does not have extension.\nOutput: {outputFile} for InputFile: {filename}"); } } outputFiles.Add(outputFile); } var previewForm = new PreviewOutputForm(inputFiles, outputFiles); previewForm.ShowDialog(); if (!previewForm.IsOk) { return; } var outputEnum = outputFiles.GetEnumerator(); var actionList = inputFiles.Select((s) => { var outputfile = outputEnum.Current; outputEnum.MoveNext(); return(new { input = s, output = outputEnum.Current }); }); if (IsMoveOperationCB.IsChecked.GetValueOrDefault()) { foreach (var action in actionList) { File.Move(action.input, action.output); } } else { foreach (var action in actionList) { File.Copy(action.input, action.output); } } }
protected void ReloadAsset(string originalAssetName, object currentAsset) { if (string.IsNullOrEmpty(originalAssetName)) { 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"); } } // Replace Windows path separators with local path separators var assetName = GetFilename(originalAssetName); // Get the real file name if ((currentAsset is Curve)) { assetName = CurveReader.Normalize(assetName); } else if ((currentAsset is Texture2D)) { assetName = Texture2DReader.Normalize(assetName); } else if ((currentAsset is SpriteFont)) { assetName = SpriteFontReader.Normalize(assetName); } else if ((currentAsset is Effect)) { assetName = Effect.Normalize(assetName); } else if ((currentAsset is Song)) { assetName = SongReader.Normalize(assetName); } else if ((currentAsset is SoundEffect)) { assetName = SoundEffectReader.Normalize(assetName); } else if ((currentAsset is Video)) { assetName = Video.Normalize(assetName); } if (string.IsNullOrEmpty(assetName)) { throw new ContentLoadException("Could not load " + originalAssetName + " asset!"); } if (!Path.HasExtension(assetName)) assetName = string.Format("{0}.xnb", assetName); if (Path.GetExtension(assetName).ToLower() == ".xnb") { } else { if ((currentAsset is Texture2D)) { using (Stream assetStream = OpenStream(assetName)) { var asset = currentAsset as Texture2D; asset.Reload(assetStream); } } else if ((currentAsset is SpriteFont)) { } else if ((currentAsset is Song)) { } else if ((currentAsset is SoundEffect)) { } else if ((currentAsset is Video)) { } else if ((currentAsset is Effect)) { } } }
protected T ReadAsset<T>(string assetName, Action<IDisposable> recordDisposableObject) { if (string.IsNullOrEmpty(assetName)) { throw new ArgumentNullException("assetName"); } if (disposed) { throw new ObjectDisposedException("ContentManager"); } string originalAssetName = assetName; object result = null; if (this.graphicsDeviceService == null) { this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService; if (this.graphicsDeviceService == null) { throw new InvalidOperationException("No Graphics Device Service"); } } // Replace Windows path separators with local path separators assetName = GetFilename(assetName); // Get the real file name if ((typeof(T) == typeof(Curve))) { assetName = CurveReader.Normalize(assetName); } else if ((typeof(T) == typeof(Texture2D))) { assetName = Texture2DReader.Normalize(assetName); } else if ((typeof(T) == typeof(SpriteFont))) { assetName = SpriteFontReader.Normalize(assetName); } else if ((typeof(T) == typeof(Effect))) { assetName = Effect.Normalize(assetName); } else if ((typeof(T) == typeof(Song))) { assetName = SongReader.Normalize(assetName); } else if ((typeof(T) == typeof(SoundEffect))) { assetName = SoundEffectReader.Normalize(assetName); } else if ((typeof(T) == typeof(Video))) { assetName = Video.Normalize(assetName); } if (string.IsNullOrEmpty(assetName)) { throw new ContentLoadException("Could not load " + originalAssetName + " asset!"); } if (!Path.HasExtension(assetName)) assetName = string.Format("{0}.xnb", assetName); if (Path.GetExtension(assetName).ToLower() == ".xnb") { // Load a XNB file Stream stream = OpenStream(assetName); try { using (BinaryReader xnbReader = new BinaryReader(stream)) { // The first 4 bytes should be the "XNB" header. i use that to detect an invalid file byte x = xnbReader.ReadByte(); byte n = xnbReader.ReadByte(); byte b = xnbReader.ReadByte(); byte platform = xnbReader.ReadByte(); if (x != 'X' || n != 'N' || b != 'B' || !(platform == 'w' || platform == 'x' || platform == 'm')) { throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?"); } byte version = xnbReader.ReadByte(); byte flags = xnbReader.ReadByte(); bool compressed = (flags & 0x80) != 0; if (version != 5 && version != 4) { throw new ContentLoadException("Invalid XNB version"); } // The next int32 is the length of the XNB file int xnbLength = xnbReader.ReadInt32(); ContentReader reader; if (compressed) { LzxDecoder dec = new LzxDecoder(16); //decompress the xnb //thanks to ShinAli (https://bitbucket.org/alisci01/xnbdecompressor) int compressedSize = xnbLength - 14; int decompressedSize = xnbReader.ReadInt32(); int newFileSize = decompressedSize + 10; MemoryStream decompressedStream = new MemoryStream(decompressedSize); int decodedBytes = 0; int pos = 0; #if ANDROID // Android native stream does not support the Position property. LzxDecoder.Decompress also uses // Seek. So we read the entirity of the stream into a memory stream and replace stream with the // memory stream. MemoryStream memStream = new MemoryStream(); stream.CopyTo(memStream); memStream.Seek(0, SeekOrigin.Begin); stream.Dispose(); stream = memStream; pos = -14; #endif while (pos < compressedSize) { // let's seek to the correct position // The stream should already be in the correct position, and seeking can be slow stream.Seek(pos + 14, SeekOrigin.Begin); int hi = stream.ReadByte(); int lo = stream.ReadByte(); int block_size = (hi << 8) | lo; int frame_size = 0x8000; if (hi == 0xFF) { hi = lo; lo = (byte)stream.ReadByte(); frame_size = (hi << 8) | lo; hi = (byte)stream.ReadByte(); lo = (byte)stream.ReadByte(); block_size = (hi << 8) | lo; pos += 5; } else pos += 2; if (block_size == 0 || frame_size == 0) break; int lzxRet = dec.Decompress(stream, block_size, decompressedStream, frame_size); pos += block_size; decodedBytes += frame_size; } if (decompressedStream.Position != decompressedSize) { throw new ContentLoadException("Decompression of " + originalAssetName + "failed. " + " Try decompressing with nativeDecompressXnb first."); } decompressedStream.Seek(0, SeekOrigin.Begin); reader = new ContentReader(this, decompressedStream, this.graphicsDeviceService.GraphicsDevice, originalAssetName); } else { reader = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice, originalAssetName); } using (reader) { result = reader.ReadAsset<T>(); } } } finally { if (stream != null) { stream.Dispose(); } } } else { if ((typeof(T) == typeof(Texture2D))) { #if IPHONE Texture2D texture = Texture2D.FromFile(graphicsDeviceService.GraphicsDevice, assetName); texture.Name = originalAssetName; result = texture; #else using (Stream assetStream = OpenStream(assetName)) { Texture2D texture = Texture2D.FromFile(graphicsDeviceService.GraphicsDevice, assetStream); texture.Name = originalAssetName; result = texture; } #endif } else if ((typeof(T) == typeof(SpriteFont))) { //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null); throw new NotImplementedException(); } else if ((typeof(T) == typeof(Song))) { result = new Song(assetName); } else if ((typeof(T) == typeof(SoundEffect))) { result = new SoundEffect(assetName); } else if ((typeof(T) == typeof(Video))) { result = new Video(assetName); } else if ((typeof(T) == typeof(Effect))) { result = new Effect(graphicsDeviceService.GraphicsDevice, assetName); } } if (result == null) { throw new ContentLoadException("Could not load " + originalAssetName + " asset!"); } if ( recordDisposableObject != null && result is IDisposable ) recordDisposableObject(result as IDisposable); return (T)result; }
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"); } } // Check for windows-style directory separator character //Lowercase assetName (monodroid specification all assests are lowercase) assetName = Path.Combine(_rootDirectory, assetName.Replace('\\', Path.DirectorySeparatorChar)).ToLower(); // Get the real file name if ((typeof(T) == typeof(Texture2D))) { assetName = Texture2DReader.Normalize(assetName); } else if ((typeof(T) == typeof(SpriteFont))) { assetName = SpriteFontReader.Normalize(assetName); } else if ((typeof(T) == typeof(Effect))) { assetName = Effect.Normalize(assetName); } else if ((typeof(T) == typeof(Song))) { assetName = SongReader.Normalize(assetName); } else if ((typeof(T) == typeof(SoundEffect))) { assetName = SoundEffectReader.Normalize(assetName); } else if ((typeof(T) == typeof(Video))) { assetName = Video.Normalize(assetName); } else { throw new NotSupportedException("Format not supported"); } if (string.IsNullOrEmpty(assetName)) { throw new ContentLoadException("Could not load " + originalAssetName + " asset!"); } if (!Path.HasExtension(assetName)) { assetName = string.Format("{0}.xnb", assetName); } if (Path.GetExtension(assetName).ToUpper() != ".XNB") { if ((typeof(T) == typeof(Texture2D))) { //Basically the same as Texture2D.FromFile but loading from the assets instead of a filePath using (Stream assetStream = File.Open(assetName, FileMode.Open, FileAccess.Read)) { Bitmap image = (Bitmap)Bitmap.FromStream(assetStream); ESImage theTexture = new ESImage(image, graphicsDeviceService.GraphicsDevice.PreferedFilter); result = new Texture2D(theTexture) { Name = Path.GetFileNameWithoutExtension(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(Effect)) { result = new Effect(graphicsDeviceService.GraphicsDevice, assetName); } 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 //Loads from Assets directory + /assetName Stream assetStream = File.Open(assetName, FileMode.Open, FileAccess.Read); 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 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(); assetStream.Close(); } if (result == null) { throw new ContentLoadException("Could not load " + originalAssetName + " asset!"); } return((T)result); }