public static Dictionary <string, ImageSource> RefreshFromMods(ImageType source) { Dictionary <string, ImageSource> list = new Dictionary <string, ImageSource>(); string rightFolder; switch (source) { case ImageType.Goal: rightFolder = GFX_GOAL_FOLDER; break; case ImageType.Event: rightFolder = GFX_EVENT_FOLDER; break; default: throw new ArgumentOutOfRangeException(nameof(source), source, null); } //For each file in add mod folders ProjectModel model = new ViewModelLocator().Main.Project; if (model?.ListModFolders == null) { return(list); } { foreach (string modpath in model.ListModFolders) { string fullpath = modpath + rightFolder; if (!Directory.Exists(fullpath)) { continue; } foreach (string filename in Directory.GetFiles(fullpath, "*" + GFX_EXTENTION, SearchOption.TopDirectoryOnly)) { if (IMAGE_DO_NOT_LOAD.Any(filename.Contains)) { continue; } try { string imageName = Path.GetFileNameWithoutExtension(filename); //try to replace potential broken links because of typos in the file names. imageName = Array.IndexOf(ARRAY_ASSOCIATED_TYPO, imageName) != -1 ? ARRAY_FILE_NAME[Array.IndexOf(ARRAY_ASSOCIATED_TYPO, imageName)] : imageName; ImageSource result = ImageSourceForBitmap(DDS.LoadImage(filename)); result.Freeze(); list[imageName] = result; } catch (Exception) { // ignored, we don't want to kill the whole process for one missing image } } } } return(list); }
static private ObservableCollection <Texture> LoadTextures(string dir) { string[] paths = Directory.GetFiles(dir, "*.dds", SearchOption.AllDirectories); var textures = new ObservableCollection <Texture>(); foreach (var file in paths) { if (IsIgnored(file)) { continue; } Bitmap bitmap = null; try { bitmap = DDS.LoadImage(file); } catch (Exception e) { Console.WriteLine($"\n[ERROR] Failed to load texture.\n{file}\n{e.Message}\n\n"); continue; } textures.Add(new Texture(bitmap, file)); bitmap.Dispose(); } return(textures); }
public void DXT3Supported() { byte[] data = File.ReadAllBytes(@"Data\sample_dxt3.dds"); Bitmap bmp = DDS.LoadImage(data); Assert.IsNotNull(bmp); }
public void DXT5Supported() { Stream stream = File.Open(@"Data\sample_dxt5.dds", FileMode.Open); Bitmap bmp = DDS.LoadImage(stream); Assert.IsNotNull(bmp); }
public override void LoadTextureStream(Texture t, System.IO.Stream data) { Bitmap bmp; string s = t.Name.Substring(t.Name.Length - 3); if (s == "dds" || s == "DDS") { try { bmp = DDS.LoadImage(t.Name); } catch (Exception) { t.Failed = true; return; } } else { try{ bmp = new Bitmap(t.Name); } catch (Exception) { t.Failed = true; return; } } LoadTextureInternal(t, bmp); bmp.Dispose(); }
public Texture2D LoadTexture(DirEntry entry) { Texture2D texture; if (_textures.TryGetValue(entry.Name, out texture)) { return(texture); } var data = LoadData(entry); if (data[0] != 'D' || data[1] != 'D' || data[2] != 'S' || data[3] != ' ') { // Compressed data = FalcomDecompressor.Decompress(data); } using (var stream = new MemoryStream(data)) { var image = DDS.LoadImage(stream); texture = new Texture2D(GraphicsDevice, image.Width, image.Height); texture.SetData(image.Data); } _textures[entry.Name] = texture; return(texture); }
public static MemoryStream DDSToImage(byte[] dds) { MemoryStream ms = new MemoryStream(); DDS.LoadImage(dds).Save(ms, ImageFormat.Png); return(ms); }
public ImagePreview(PackedFile packedFile) { InitializeComponent(); if (packedFile.Name.EndsWith(".dds")) { var image = DDS.LoadImage(packedFile.Data); Image1.Source = Convert(image); } else if (packedFile.Name.EndsWith(".png")) { Image1.Source = Convert(packedFile.Data); } Title = "Preview: " + packedFile.FullPath; }
private void toolStripButton1_Click(object sender, EventArgs e) { string file = "screenshot.dds"; if (File.Exists(file)) { File.Delete(file); } Debugger.MakeScreenshot(file); if (File.Exists(file)) { pb1.Image = DDS.LoadImage(file); File.Delete(file); } GC.Collect(); }
private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (listBox1.SelectedItem.GetType() != typeof(NTX.TextureFile)) { return; } var textureFile = listBox1.SelectedItem as NTX.TextureFile; if (textureFile == null) { return; } OpenedFile = textureFile; pictureBox1.Image = DDS.LoadImage(textureFile.Texture); }
//Handles the open image button private void btn_select_radar_image(object sender, RoutedEventArgs e) { //file dialogue OpenFileDialog openf = new OpenFileDialog(); openf.Filter = "Image files (*.jpg, *.jpeg, *.png, *.dds) | *.jpg; *.jpeg; *.png; *.dds"; if (openf.ShowDialog() == true) { target_selected_radar_filename.Content = Path.GetFileName(openf.FileName); Bitmap loadimage = new Bitmap(1,1);//Create temp bitmap before assigning it if(Path.GetExtension(openf.FileName) == ".dds")//If its a dds image, convert that loadimage = DDS.LoadImage(openf.FileName, false); //Loads the bitmap imag from a dds source else loadimage = new Bitmap(openf.FileName); //If it is a valid image file then load that target_displayimage.Source = loadimage.toBitMapImage(); //Display the image //Add reference of bitmap to the mapData insmap.image_radar = loadimage; } }
private void SaveImage(Texture2D tex, string dir) { Bitmap original = null; if (tex.IsDDS) { original = DDS.LoadImage(tex.Image, _alpha); if (_flip) { original.RotateFlip(RotateFlipType.RotateNoneFlipY); } } else { // Assumimg it is TGA, alpha?? var tga = new TargaImage(new MemoryStream(tex.Image)); original = tga.Image; if (!_flip) // tga already flipped { original.RotateFlip(RotateFlipType.RotateNoneFlipY); } } original.Save(Path.Combine(dir, tex.Name + ".png")); }
/// <summary> /// Loads the tiles in the sprite. Sets IsLoaded to true. /// </summary> /// <param name="filePath">Path to the image.</param> public void Load(string filePath) { Bitmap texture; Unload(); if (File.Exists(filePath)) { texture = DDS.LoadImage(filePath); } else { throw new FileLoadException("Unable to find texture file", filePath); } if (texture == null) { throw new FileLoadException("Texture file is empty.", filePath); } Size size = new Size(texture.Width / FrameCount, texture.Height); for (int indexFrame = 0; indexFrame < FrameCount; indexFrame++) { Bitmap tile = new Bitmap(size.Width, size.Height); Graphics g = Graphics.FromImage(tile); Rectangle drawArea = new Rectangle(indexFrame * size.Width, 0, size.Width, size.Height); g.DrawImage(texture, 0, 0, drawArea, GraphicsUnit.Pixel); Tiles.Add(tile); g.Dispose(); } texture.Dispose(); IsLoaded = true; }
/// <summary> /// Gets the Texture as Image /// </summary> /// <returns>Texture</returns> public Image GetImage() { return(DDS.LoadImage(Texture)); }
public void BMPNotSupported() { Bitmap bmp = DDS.LoadImage(@"Data\sample.bmp"); Assert.IsNull(bmp); }
public static mapData UnpackBSP(string sourceFolder, string outputPath) { //Find the bsp file string[] found = Directory.GetFiles(sourceFolder, "*.bsp"); if (found.Count() == 0) { throw new ArgumentException("Could not find BSP file in folder", "outputFolder"); } else { string bsp = Directory.GetFiles(sourceFolder, "*.bsp")[0]; //Find the bsp file //Setup extraction arguments string extractarg = "-extract \"" + Path.GetFullPath(bsp) + "\" \"" + sourceFolder + "/extracted" + "\""; //Run the process Process bspzip = new Process(); bspzip.StartInfo = new ProcessStartInfo { FileName = Environment.CurrentDirectory + "/bspzip.exe", Arguments = extractarg, CreateNoWindow = true, //Make sure to create no window since its gui now UseShellExecute = false, }; bspzip.Start(); bspzip.WaitForExit(); paths overview = new paths(); //Extract the zip file's overview components using (var zip = ZipFile.OpenRead(sourceFolder + "/extracted.zip")) { foreach (var entry in zip.Entries.ToList()) { //Uncommon error fix where path would contain drive letter if (entry.FullName.ToLower().Contains("overviews") && !entry.FullName.Contains(":")) { //Setup target dir string targetdir = sourceFolder + "/files/" + Path.GetDirectoryName(entry.FullName); Directory.CreateDirectory(targetdir); //Extract to target dir string targetfile = sourceFolder + "/files/" + entry.FullName; entry.ExtractToFile(targetfile, true); Debug.Success("Extracted " + entry.FullName); //File name sorting for the paths struct string purefilename = Path.GetFileName(entry.FullName); if (purefilename.Contains("radar_spectate")) { overview.path_radar_spectate = targetfile; } else if (purefilename.Contains("_radar")) { overview.path_radar = targetfile; } else if (purefilename.Contains(".txt")) { overview.path_radar_txt = targetfile; } } } } mapData toSave = new mapData(); if (overview.path_radar != null) { toSave.image_radar = DDS.LoadImage(overview.path_radar, false); } if (overview.path_radar_spectate != null) { toSave.image_radar_spectate = DDS.LoadImage(overview.path_radar_spectate, false); } if (overview.path_radar_txt != null) { toSave.radar = new Radar(overview.path_radar_txt); } serialwrite.Binary.WriteToBinaryFile <mapData>(Path.ChangeExtension(outputPath, ".maprad"), toSave); return(toSave); } }
static void Main(string[] args) { var game = SC3Game.ChaosChild; var charset = new CharacterSet(game, ""); const int outlinePadding = 4; const int cellWidth = 32; const int cellHeight = 32; const int outlineCellWidth = 38; const int outlineCellHeight = 38; const double scaleFactor = 1.5; const int colCount = 64; var fontA = DDS.LoadImage(Assets.FONT_A); var fontB = DDS.LoadImage(Assets.FONT_B); var fontOutlineA = DDS.LoadImage(Assets.font_outline_A); var fontOutlineB = DDS.LoadImage(Assets.font_outline_B); var font = new Bitmap(fontA.Width, fontA.Height + fontB.Height); var fontOutline = new Bitmap(fontOutlineA.Width, fontOutlineA.Height + fontOutlineB.Height); var fontGraphics = Graphics.FromImage(font); fontGraphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; fontGraphics.DrawImage(fontA, new Point(0, 0)); fontGraphics.DrawImage(fontB, new Point(0, fontA.Height)); var fontOutlineGraphics = Graphics.FromImage(fontOutline); fontOutlineGraphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; fontOutlineGraphics.DrawImage(fontOutlineA, new Point(0, 0)); fontOutlineGraphics.DrawImage(fontOutlineB, new Point(0, fontOutlineA.Height)); float[][] blackColorMatrixElements = { new float[] { 0, 0, 0, 0, 0 }, new float[] { 0, 0, 0, 0, 0 }, new float[] { 0, 0, 0, 0, 0 }, new float[] { 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 1 } }; ColorMatrix blackColorMatrix = new ColorMatrix(blackColorMatrixElements); float[][] tipColorMatrixElements = { new float[] { 144.0f / 255.0f, 0, 0, 0, 0 }, new float[] { 0, 1, 0, 0, 0 }, new float[] { 0, 0, 1, 0, 0 }, new float[] { 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 1 } }; ColorMatrix tipColorMatrix = new ColorMatrix(tipColorMatrixElements); var outlineAttrs = new ImageAttributes(); var normalFontAttrs = new ImageAttributes(); var tipFontAttrs = new ImageAttributes(); outlineAttrs.SetColorMatrix( blackColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); tipFontAttrs.SetColorMatrix( tipColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap ); int lineId = 0; string line; StreamReader reader = new StreamReader("input.txt"); while ((line = reader.ReadLine()) != null) { int totalWidth = 32; int totalHeight = 72; int curX = 16; int curY = 10; bool isTipMode = false; foreach (char c in line) { if (c == '|') { continue; } ushort charId = (ushort)(charset.EncodeCharacter(c) & 0x7FFF); totalWidth += (int)Math.Round(Assets.widths[charId] * scaleFactor); } var output = new Bitmap(totalWidth, totalHeight); var outputGraphics = Graphics.FromImage(output); outputGraphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; foreach (char c in line) { if (c == '|') { isTipMode = !isTipMode; continue; } ushort charId = (ushort)(charset.EncodeCharacter(c) & 0x7FFF); int row = charId / colCount; int col = charId % colCount; int glyphWidth = (int)Math.Round(Assets.widths[charId] * scaleFactor); var outlineDestRect = new Rectangle( curX - outlinePadding, curY - outlinePadding, (int)(outlineCellWidth * scaleFactor), (int)(outlineCellHeight * scaleFactor)); var destRect = new Rectangle( curX, curY, (int)(cellWidth * scaleFactor), (int)(cellHeight * scaleFactor)); outputGraphics.DrawImage( fontOutline, outlineDestRect, (int)(col * outlineCellWidth * scaleFactor), (int)(row * outlineCellHeight * scaleFactor), (int)(outlineCellWidth * scaleFactor), (int)(outlineCellHeight * scaleFactor), GraphicsUnit.Pixel, outlineAttrs); outputGraphics.DrawImage( font, destRect, (int)(col * cellWidth * scaleFactor), (int)(row * cellHeight * scaleFactor), (int)(cellWidth * scaleFactor), (int)(cellHeight * scaleFactor), GraphicsUnit.Pixel, isTipMode ? tipFontAttrs : normalFontAttrs); curX += glyphWidth; } output.Save(string.Format("line{0}.png", lineId)); lineId++; } }
public void DXT1Supported() { Bitmap bmp = DDS.LoadImage(@"Data\sample_dxt1.dds"); Assert.IsNotNull(bmp); }
public mapdata(string path) { string mapname = Path.GetFileNameWithoutExtension(path); string serverfolder = "files/" + mapname; string extractzip = Path.GetFullPath(serverfolder) + "/" + mapname + ".zip"; string extractarg = "-extract \"" + Path.GetFullPath(path) + "\" \"" + extractzip + "\""; #region servercheck if (Directory.Exists(serverfolder)) { Debug.Warn("Working directory already exists"); } Debug.Info("Adding files"); Directory.CreateDirectory(serverfolder); File.Copy(path, serverfolder + "/" + Path.GetFileName(path), true); path = serverfolder + "/" + Path.GetFileName(path); #endregion servercheck Process bspzip = new Process(); bspzip.StartInfo = new ProcessStartInfo { FileName = Environment.CurrentDirectory + "/bspzip.exe", Arguments = extractarg, UseShellExecute = false, }; bspzip.Start(); bspzip.WaitForExit(); using (var zip = ZipFile.OpenRead(extractzip)) { foreach (var entry in zip.Entries.ToList()) { if (entry.FullName.ToLower().Contains("overviews")) { Directory.CreateDirectory(Path.GetFullPath(serverfolder) + "/" + Path.GetDirectoryName(entry.FullName)); entry.ExtractToFile(Path.GetFullPath(serverfolder) + "/" + entry.FullName, true); Debug.Success("Extracted " + entry.FullName); } } } Radar radar = new Radar(serverfolder + "/resource/overviews/" + mapname + ".txt"); radarDetails = radar; Debug.Success("Radar file parsed"); string ddsRadar = Directory.GetFiles(serverfolder + "/resource/overviews/", "*.dds")[0]; Bitmap convert = DDS.LoadImage(ddsRadar, false); string imgLoc = serverfolder + "/resource/overviews/" + Path.GetFileNameWithoutExtension(ddsRadar) + ".png"; convert.Save(imgLoc); using (var imageFactory = new ImageFactory()) { imageFactory.Load(imgLoc) .Saturation(-100) .Contrast(-60) .Brightness(-35) .Contrast(-20) .Brightness(-20) .Save(imgLoc); } radarImage = new Bitmap(imgLoc); Debug.Success("Radar file exported"); }
public static void DoMakeObjFile(string outputDir, string inputFile, string gradient, string emissive) { byte[] gradientColors = gradient.Split(new char[] { '[', ']', ',' }, StringSplitOptions.RemoveEmptyEntries).Select(cur => byte.Parse(cur.Trim())).ToArray(); SColor[] gradientObj = new SColor[] { new SColor { R = gradientColors[0], B = gradientColors[1], G = gradientColors[2] }, new SColor { R = gradientColors[3], B = gradientColors[4], G = gradientColors[5] }, new SColor { R = gradientColors[6], B = gradientColors[7], G = gradientColors[8] }, }; byte[] emissiveColors = emissive.Split(new char[] { '[', ']', ',' }, StringSplitOptions.RemoveEmptyEntries).Select(cur => byte.Parse(cur.Trim())).ToArray(); SColor emissiveObj = new SColor { R = emissiveColors[0], B = emissiveColors[1], G = emissiveColors[2] }; string inputOrg = inputFile; bool isJson = inputFile.EndsWith(".json", StringComparison.OrdinalIgnoreCase); bool isMsgpack = inputFile.EndsWith(".msgpack", StringComparison.OrdinalIgnoreCase); if (!File.Exists(inputFile) || (!isMsgpack && !isJson)) { throw new Exception("Input file must be .msgpack or .json"); } if (!Directory.Exists(outputDir)) { throw new Exception("Output directory does not exist!"); } if (isMsgpack) { Parser.DoParse(outputDir, inputFile); inputFile = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(inputFile)}.json"); } string materialName = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(inputFile)); string materialFile = $"{materialName}.mtl"; string materialFilePath = Path.Combine(outputDir, materialFile); JObject root = JObject.Parse(File.ReadAllText(inputFile)); Dictionary <string, Dictionary <string, string> > materialLookup = new Dictionary <string, Dictionary <string, string> >(); foreach (var curNode in root["nodes"].Value <JObject>()) { if (!curNode.Value.Value <JObject>().ContainsKey("geometryinstances")) { continue; } foreach (var curGeom in curNode.Value["geometryinstances"].Value <JObject>()) { string geometry = curGeom.Value["geometry"].Value <string>(); string surface = curGeom.Value["surface"].Value <string>(); string material = curGeom.Value["material"].Value <string>(); if (!materialLookup.TryGetValue(geometry, out Dictionary <string, string> curGeomLookup)) { curGeomLookup = new Dictionary <string, string>(); materialLookup.Add(geometry, curGeomLookup); } curGeomLookup[surface] = material; } } bool failMat = false; string outputFile = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(inputFile)}.obj"); using (StreamWriter sw = new StreamWriter(outputFile)) { sw.WriteLine($"mtllib {materialFile}"); int vOffset = 0; int vtOffset = 0; int vnOffset = 0; foreach (var curGeom in root["geometries"].Value <JObject>()) { // TODO: handle TANGENT and BINORMAL. Anymore? //if (curGeom.Value["inputs"].Count() != 3) //{ // throw new Exception("Invalid source input count..."); //} double[][] vertLocs = ReadShit <double>(curGeom.Value, "POSITION", out int vertOffset); foreach (double[] curVert in vertLocs) { sw.WriteLine($"v {curVert[0]} {curVert[1]} {curVert[2]}"); } double[][] texCoords = ReadShit <double>(curGeom.Value, "TEXCOORD0", out int texOffset); foreach (double[] curTex in texCoords) { sw.WriteLine($"vt {curTex[0]} {1-curTex[1]}"); } double[][] normals = ReadShit <double>(curGeom.Value, "NORMAL", out int normOffset); foreach (double[] curNorm in normals) { sw.WriteLine($"vn {curNorm[0]} {curNorm[1]} {curNorm[2]}"); } foreach (var curSurf in curGeom.Value["surfaces"].Value <JObject>()) { sw.WriteLine($"g {curSurf.Key}"); try { sw.WriteLine($"usemtl {materialLookup[curGeom.Key][curSurf.Key]}"); } catch { failMat = true; sw.WriteLine($"usemtl failMat"); Console.WriteLine("material not found..."); } var blarg = curSurf.Value["triangles"].Select(cur => cur.Value <int>()); int numPrimitives = curSurf.Value["numPrimitives"].Value <int>(); if ((blarg.Count() % numPrimitives) != 0) { throw new Exception("Invalid stride"); } int stride = blarg.Count() / numPrimitives; if ((stride % 3) != 0) { throw new Exception("Invalid stride"); } int pointLength = stride / 3; int[][] triangles = FuckinReadIt(blarg, stride); foreach (int[] curTri in triangles) { if (pointLength >= 1) { if ((curTri[pointLength * 0 + 0] >= vertLocs.Length) || (curTri[pointLength * 1 + 0] >= vertLocs.Length) || (curTri[pointLength * 2 + 0] >= vertLocs.Length)) { Console.WriteLine("vert index out of range"); continue; } } if (pointLength >= 2) { if ((curTri[pointLength * 0 + 1] >= texCoords.Length) || (curTri[pointLength * 1 + 1] >= texCoords.Length) || (curTri[pointLength * 2 + 1] >= texCoords.Length)) { Console.WriteLine("tex index out of range"); continue; } } if (pointLength >= 3) { if ((curTri[pointLength * 0 + 2] >= normals.Length) || (curTri[pointLength * 1 + 2] >= normals.Length) || (curTri[pointLength * 2 + 2] >= normals.Length)) { Console.WriteLine("norm index out of range"); continue; } } sw.Write("f"); for (int i = 0; i < 3; ++i) { sw.Write(" "); if (pointLength >= 1) { sw.Write($"{curTri[pointLength * i + 0] + 1 + vOffset}"); } if (pointLength >= 2) { sw.Write($"/{curTri[pointLength * i + 1] + 1 + vtOffset}"); } if (pointLength >= 3) { sw.Write($"/{curTri[pointLength * i + 2] + 1 + vnOffset}"); } } sw.WriteLine(); } } vOffset += vertLocs.Length; vtOffset += texCoords.Length; vnOffset += normals.Length; } sw.Flush(); sw.Close(); sw.Dispose(); } string rootDir = inputOrg; while (Path.GetFileName(rootDir) != "assets") { rootDir = Path.GetDirectoryName(rootDir); } using (StreamWriter sw = new StreamWriter(materialFilePath)) { foreach (var curMat in root["materials"].Value <JObject>()) { sw.WriteLine($"newmtl {curMat.Key}"); var material = curMat.Value.Value <JObject>(); int usedTextures = 0; if (material["parameters"].Value <JObject>().ContainsKey("diffuse") || material["parameters"].Value <JObject>().ContainsKey("gradient_mask")) { string diffuse; FastBitmap diffuseTexture; if (material["parameters"].Value <JObject>().ContainsKey("diffuse")) { ++usedTextures; diffuse = material["parameters"]["diffuse"].Value <string>().Replace('/', '\\'); try { diffuseTexture = DDS.LoadImage(Path.Combine(rootDir, diffuse)).FastLock(); } catch { diffuseTexture = null; Console.WriteLine("Error loading texture"); } } else { diffuse = material["parameters"]["gradient_mask"].Value <string>().Replace('/', '\\'); diffuseTexture = null; } if (material["parameters"].Value <JObject>().ContainsKey("gradient_mask")) { ++usedTextures; string gradient_mask = material["parameters"]["gradient_mask"].Value <string>().Replace('/', '\\'); FastBitmap gradient_maskTexture = null; bool fail = false; try { gradient_maskTexture = DDS.LoadImage(Path.Combine(rootDir, gradient_mask)).FastLock(); } catch { fail = true; Console.WriteLine("Error loading texture"); } if (!fail) { if (diffuseTexture == null) { diffuseTexture = new Bitmap(gradient_maskTexture.Width, gradient_maskTexture.Height, PixelFormat.Format32bppArgb).FastLock(); } ApplyGradientToDiffuse(diffuseTexture, gradient_maskTexture, gradientObj); gradient_maskTexture.Unlock(); gradient_maskTexture.Bitmap.Dispose(); gradient_maskTexture.Dispose(); } } if (diffuseTexture == null) { diffuseTexture = new Bitmap(512, 512, PixelFormat.Format32bppArgb).FastLock(); SetFlatColor(diffuseTexture, new SColor { R = 255, G = 0, B = 255 }); } diffuseTexture.Unlock(); string saveFilePath = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(diffuse)}.png"); sw.WriteLine($"map_Kd {Path.GetFileName(saveFilePath)}"); try { diffuseTexture.Bitmap.Save(saveFilePath, ImageFormat.Png); } catch (Exception ex) { Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}"); } diffuseTexture.Bitmap.Dispose(); diffuseTexture.Dispose(); } if (material["parameters"].Value <JObject>().ContainsKey("normal")) { ++usedTextures; string normal = material["parameters"]["normal"].Value <string>().Replace('/', '\\'); FastBitmap normalTexture = null; bool fail = false; try { normalTexture = DDS.LoadImage(Path.Combine(rootDir, normal)).FastLock(); } catch { fail = true; Console.WriteLine("Error loading texture"); } if (!fail) { normalTexture.Unlock(); string saveFilePath = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(normal)}.png"); sw.WriteLine($"map_Bump {Path.GetFileName(saveFilePath)}"); try { normalTexture.Bitmap.Save(saveFilePath, ImageFormat.Png); } catch (Exception ex) { Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}"); } normalTexture.Bitmap.Dispose(); normalTexture.Dispose(); } } if (material["parameters"].Value <JObject>().ContainsKey("specular_emissive")) { ++usedTextures; string specular_emissive = material["parameters"]["specular_emissive"].Value <string>().Replace('/', '\\'); FastBitmap specular_emissiveTexture = null; bool fail = false; try { specular_emissiveTexture = DDS.LoadImage(Path.Combine(rootDir, specular_emissive)).FastLock(); } catch { fail = true; Console.WriteLine("Error loading texture"); } if (!fail) { ApplyEmissiveColor(specular_emissiveTexture, emissiveObj); specular_emissiveTexture.Unlock(); string saveFilePath = Path.Combine(outputDir, $"{Path.GetFileNameWithoutExtension(specular_emissive)}.png"); sw.WriteLine($"map_Ke {Path.GetFileName(saveFilePath)}"); try { specular_emissiveTexture.Bitmap.Save(saveFilePath, ImageFormat.Png); } catch (Exception ex) { Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}"); } specular_emissiveTexture.Bitmap.Dispose(); specular_emissiveTexture.Dispose(); } } if (material["parameters"].Value <JObject>().Count != usedTextures) { Console.WriteLine($"Warning, unused texture(s) on {curMat.Key}..."); } } if (failMat) { FastBitmap failTexture = new Bitmap(512, 512, PixelFormat.Format32bppArgb).FastLock(); SetFlatColor(failTexture, new SColor { R = 255, G = 0, B = 255 }); sw.WriteLine($"newmtl failMat"); failTexture.Unlock(); string saveFilePath = Path.Combine(outputDir, $"failMat.png"); sw.WriteLine($"map_Kd {Path.GetFileName(saveFilePath)}"); try { failTexture.Bitmap.Save(saveFilePath, ImageFormat.Png); } catch (Exception ex) { Console.WriteLine($"Failed to save image {saveFilePath}\r\n{ex.Message}"); } failTexture.Bitmap.Dispose(); failTexture.Dispose(); } sw.Flush(); sw.Close(); sw.Dispose(); } Console.WriteLine("Done Done!!!"); }
private SortedList <string, Point> loadSurfaces() { string sourceFilename = Path.GetDirectoryName(Application.ExecutablePath) + "\\resources\\surfaces\\iconset\\iconlist_ivtrm.png"; string extension = Path.GetExtension(sourceFilename); if (extension == ".dds") { DDSReader.Utils.PixelFormat st = (DDSReader.Utils.PixelFormat)DDSFORMAT; Bitmap bmp = DDS.LoadImage(sourceFilename, true, st); if (bmp != null) { sourceBitmap = bmp; } else { MessageBox.Show("Unable to load thumbnails..."); //sourceBitmap = (Bitmap)Image.FromFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\resources\\surfaces\\iconset\\iconlist_ivtrm.png"); } } else { sourceBitmap = (Bitmap)Image.FromFile(sourceFilename); } if (sourceBitmap == null) { MessageBox.Show("Unable to load dds image..."); sourceBitmap = (Bitmap)Image.FromFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\resources\\surfaces\\iconset\\iconlist_ivtrm.png"); } database.sourceBitmap = sourceBitmap; SortedList <string, Bitmap> results = new SortedList <string, Bitmap>(); List <Bitmap> zxczxc = new List <Bitmap>(); List <string> fileNames = new List <string>(); imagesx = new SortedList <int, string>(); int w = 0; int h = 0; int counter = 0; string line; string iconlist_ivtrm = Path.GetDirectoryName(Application.ExecutablePath) + "\\resources\\surfaces\\iconset\\iconlist_ivtrm.txt"; Encoding enc = Encoding.GetEncoding("GBK"); StreamReader file = null; string extension2 = Path.GetExtension(iconlist_ivtrm); file = new StreamReader(iconlist_ivtrm, enc); while ((line = file.ReadLine()) != null) { switch (counter) { case 0: w = int.Parse(line); break; case 1: h = int.Parse(line); break; case 2: rows = int.Parse(line); database.rows = rows; break; case 3: cols = int.Parse(line); database.cols = cols; break; default: fileNames.Add(line); break; } counter++; } file.Close(); imageposition = new SortedList <string, Point>(); int x, y = 0; for (int a = 0; a < fileNames.Count; a++) { Application.DoEvents(); y = a / cols; x = a - y * cols; x = x * w; y = y * h; try { imagesx.Add(a, fileNames[a]); imageposition.Add(fileNames[a], new Point(x, y)); } catch (Exception) { } } database.imagesx = imagesx; database.imageposition = imageposition; return(imageposition); }
private void handle(WADEntry entry, string namePath) { if (namePath.ToLower().EndsWith(".dds")) { if (mode == 0) { mode = 1; _viewPort.Visibility = Visibility.Collapsed; _previewImage.Visibility = Visibility.Visible; _previewTextureComboBox.IsEnabled = false; _previewMeshesComboBox.IsEnabled = false; } _previewTypeLabel.Content = "Type: DirectDraw Surface"; _previewNameLabel.Content = "Name: " + namePath.Split('/').Last(); var stream = new MemoryStream(); var image = DDS.LoadImage(entry.GetContent(true)); image.Save(stream, ImageFormat.Png); var imageSource = new BitmapImage(); imageSource.CacheOption = BitmapCacheOption.OnLoad; imageSource.BeginInit(); imageSource.StreamSource = stream; imageSource.EndInit(); imageSource.Freeze(); _previewImage.Dispatcher.BeginInvoke(new Action(() => { _previewImage.Source = imageSource; _previewImage.Width = image.Width; _previewImage.Height = image.Height; })); return; } if (mode == 1) { mode = 0; _previewImage.Visibility = Visibility.Collapsed; _viewPort.Visibility = Visibility.Visible; } clearUp(); _previewTextureComboBox.IsEnabled = true; _previewMeshesComboBox.IsEnabled = true; if (!_previewExpander.IsExpanded) { _previewExpander.IsExpanded = true; } if (namePath.ToLower().EndsWith(".scb")) { _previewMeshesComboBox.IsEnabled = false; var model = applyMesh(new SCBFile(new MemoryStream(entry.GetContent(true)))); _previewTypeLabel.Content = "Type: Static Object Binary"; _previewNameLabel.Content = "Name: " + namePath.Split('/').Last(); if (PreSelect != null) { foreach (var wadEntry in window.Wad.Entries) { if (wadEntry.XXHash == PreSelect.Item2) { applyMaterial(wadEntry, PreSelect.Item1, model); break; } } PreSelect = null; } else { applyMaterial(model); } return; } if (namePath.ToLower().EndsWith(".sco")) { _previewMeshesComboBox.IsEnabled = false; var model = applyMesh(new SCOFile(new MemoryStream(entry.GetContent(true)))); _previewTypeLabel.Content = "Type: Static Object Mesh"; _previewNameLabel.Content = "Name: " + namePath.Split('/').Last(); if (PreSelect != null) { foreach (var wadEntry in window.Wad.Entries) { if (wadEntry.XXHash == PreSelect.Item2) { applyMaterial(wadEntry, PreSelect.Item1, model); break; } } PreSelect = null; } else { applyMaterial(model); } return; } var result = generateInfoHolder(namePath); if (result == null) { return; } var skn = new SKNFile(new MemoryStream(result.sknPath.GetContent(true))); foreach (var subMesh in skn.Submeshes) { var model = applyMesh(subMesh); _previewNameLabel.Content = "Name: " + namePath.Split('/').Last(); _previewTypeLabel.Content = "Type: Simple Skin Mesh"; if (PreSelect != null) { foreach (var wadEntry in window.Wad.Entries) { if (wadEntry.XXHash == PreSelect.Item2) { applyMaterial(wadEntry, PreSelect.Item1, model); break; } } } else { if (result.textures.Count > 0) { applyMaterial(result.textures.First().Value, result.textures.First().Key, model); } else { applyMaterial(model); } } } PreSelect = null; }
public void SampleTest() { Bitmap bmp = DDS.LoadImage(@"Data\error.dds"); Assert.IsNotNull(bmp); }
private void SaveImages(Texture2D tex, ArtCard match) { var cardId = match.Id; var card = CardDb.All[cardId]; var cardName = card.Name; var cardSet = card.Set; var filename = cardId; var subDir = ""; if (tex.Image.Length <= 0) { Logger.Log(LogLevel.WARN, $"Texture {tex.Name} has an empty image"); return; } if (_opts.AddCardName) { filename = StringUtils.SafeString(cardName) + "-" + filename; } if (_opts.GroupBySet) { if (CardEnumConverter.FriendlySetName.ContainsKey(cardSet)) { subDir = CardEnumConverter.FriendlySetName[cardSet]; } else { subDir = "Other"; } if (!_opts.BarArtOnly) { Directory.CreateDirectory(Path.Combine(_dirFull, subDir)); } } if (_opts.ImageType?.ToLower() == "dds" && !_opts.BarArtOnly) { tex.Save(Path.Combine(_dirFull, subDir), filename); return; } Bitmap original = null; if (tex.IsDDS) { original = DDS.LoadImage(tex.Image, _opts.PreserveAlphaChannel); } else { // TODO: tga alpha channel? // Assumimg it is TGA var tga = new TargaImage(new MemoryStream(tex.Image)); original = tga.Image; // Flip original on y, so like dds original.RotateFlip(RotateFlipType.RotateNoneFlipY); } // save full size image to disk Bitmap full = new Bitmap(original); if (_opts.Height > 0) { full = new Bitmap(original, _opts.Height, _opts.Height); } // flip "right" way up if (_opts.FlipY) { full.RotateFlip(RotateFlipType.RotateNoneFlipY); } full.Save(Path.Combine(_dirFull, subDir, filename + "." + _opts.ImageType.ToLower())); }