/// <summary> /// loads jpg and bmp images into a texture and returns it /// </summary> /// <param name="path"></param> /// <returns></returns> public static Texture2D LoadTexture(string path) { int lastDot = path.LastIndexOf('.'); string ext = path.Substring(lastDot + 1); if (ext == "jpg") { using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { byte[] bytes = new byte[fs.Length]; fs.Read(bytes, 0, bytes.Length); var tex = new Texture2D(1, 1); tex.LoadImage(bytes); //this can only do jpg, png, exr and tga (last two unsure) return(tex); } } else if (ext == "bmp") { var bmp = bmpLoader.LoadBMP(path); return(bmp.ToTexture2D()); } return(null); }
void ConvertSpritesToPNG(bool removeBlackBackground) { string separator = Path.DirectorySeparatorChar.ToString(); string dataPath = Path.GetFullPath("Assets" + separator + "Maisemore"); foreach (string file in Directory.GetFiles(dataPath, "*.bmp")) { string fileName = Path.GetFileName(file); byte[] data = File.ReadAllBytes(file); BMPLoader bmpLoader = new BMPLoader(); BMPImage bmpImg = bmpLoader.LoadBMP(data); if (bmpImg == null) { continue; } Texture2D tex = bmpImg.ToTexture2D(); if (removeBlackBackground) { RemoveBlackBackground(tex); } SaveTextureAsPNG(tex, dataPath + separator + fileName.Substring(0, fileName.IndexOf('.')) + ".png"); } }
public static Texture2D LoadTexture(string path) { if (Path.GetExtension(path).ToLower() == ".tga") { return(TGALoader.LoadTGA(path)); } var bmp = new BMPLoader(); bmp.ForceAlphaReadWhenPossible = false; var img = bmp.LoadBMP(path); if (img == null) { throw new Exception("Failed to load: " + path); } var colors = (Color32[])img.imageData.Clone(); var width = img.info.width; var height = img.info.height; //magic pink conversion and transparent color expansion for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var count = 0; var r = 0; var g = 0; var b = 0; if (x + y * width >= colors.Length) { Debug.LogWarning($"For some reason looking out of bounds on color table on texture {path} w{width} h{height} position {x} {y} ({x + y * width}"); } var color = colors[x + y * width]; //Debug.Log(color); if (color.r < 254 || color.g != 0 || color.b < 254) { continue; } //Debug.Log("OHWOW: " + color); for (var y2 = -1; y2 <= 1; y2++) { for (var x2 = -1; x2 <= 1; x2++) { if (y + y2 < 0 || y + y2 >= height) { continue; } if (x + x2 < 0 || x + x2 >= width) { continue; } var color2 = colors[x + x2 + (y + y2) * width]; if (color2.r >= 254 && color2.g == 0 && color2.b >= 254) { continue; } count++; r += color2.r; g += color2.g; b += color2.b; } } if (count > 0) { var r2 = (byte)Mathf.Clamp(r / count, 0, 255); var g2 = (byte)Mathf.Clamp(g / count, 0, 255); var b2 = (byte)Mathf.Clamp(b / count, 0, 255); //Debug.Log($"{x},{y} - change {color} to {r2},{g2},{b2}"); img.imageData[x + y * width] = new Color32(r2, g2, b2, 0); } else { img.imageData[x + y * width] = new Color32(0, 0, 0, 0); } } } return(img.ToTexture2D()); }
public void ImportHeightmap() { var extensions = new[] { new ExtensionFilter("Heightmap", new string[] { "raw", "r16", "bmp" }) //new ExtensionFilter("Stratum mask", "raw, bmp") }; var paths = StandaloneFileBrowser.OpenFilePanel("Import stratum mask", EnvPaths.GetMapsPath() + MapLuaParser.Current.FolderName, extensions, false); if (paths == null || paths.Length == 0 || string.IsNullOrEmpty(paths[0])) { return; } int h = ScmapEditor.Current.Teren.terrainData.heightmapHeight; int w = ScmapEditor.Current.Teren.terrainData.heightmapWidth; ScmapEditor.GetAllHeights(ref beginHeights); MapLuaParser.Current.History.RegisterTerrainHeightmapChange(beginHeights); float[,] data = new float[h, w]; //float[,] old = ScmapEditor.Current.Teren.terrainData.GetHeights(0, 0, w, h); if (paths[0].ToLower().EndsWith("bmp")) { BMPLoader loader = new BMPLoader(); BMPImage img = loader.LoadBMP(paths[0]); Debug.Log(img.info.compressionMethod + ", " + img.info.nBitsPerPixel + ", " + img.rMask + ", " + img.imageData[0].r); Texture2D ImportedImage = img.ToTexture2D(); if (ImportedImage.width != h || ImportedImage.height != w) { Debug.Log("Wrong size"); TextureScale.Bilinear(ImportedImage, h, w); ImportedImage.Apply(false); } Color[] ImportedColors = ImportedImage.GetPixels(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { data[y, x] = (float)ImportedColors[x + y * w].r / 0.567f; // 0.58 } } } else { using (var file = System.IO.File.OpenRead(paths[0])) using (var reader = new System.IO.BinaryReader(file)) { for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float v = (float)reader.ReadUInt16() / (float)HeightConversion; data[h - (y + 1), x] = v; } } } } //ScmapEditor.Current.Teren.terrainData.SetHeights(0, 0, data); ScmapEditor.SetAllHeights(data); RegenerateMaps(); OnTerrainChanged(); }
public void ImportHeightmap() { var extensions = new[] { new ExtensionFilter("Heightmap", new string[] { "raw", "r16", "bmp" }) }; var paths = StandaloneFileBrowser.OpenFilePanel("Import heightmap", DefaultPath, extensions, false); if (paths == null || paths.Length == 0 || string.IsNullOrEmpty(paths[0])) { return; } int h = ScmapEditor.Current.Teren.terrainData.heightmapResolution; int w = ScmapEditor.Current.Teren.terrainData.heightmapResolution; ScmapEditor.GetAllHeights(ref beginHeights); Undo.RegisterUndo(new UndoHistory.HistoryTerrainHeight(), new UndoHistory.HistoryTerrainHeight.TerrainHeightHistoryParameter(beginHeights)); float[,] data = new float[h, w]; //float[,] old = ScmapEditor.Current.Teren.terrainData.GetHeights(0, 0, w, h); if (paths[0].ToLower().EndsWith("bmp")) { BMPLoader loader = new BMPLoader(); BMPImage img = loader.LoadBMP(paths[0]); Debug.Log(img.info.compressionMethod + ", " + img.info.nBitsPerPixel + ", " + img.rMask + ", " + img.imageData[0].r); Texture2D ImportedImage = img.ToTexture2D(); if (ImportedImage.width != h || ImportedImage.height != w) { Debug.Log("Wrong size"); TextureScale.Bilinear(ImportedImage, h, w); ImportedImage.Apply(false); } Color[] ImportedColors = ImportedImage.GetPixels(); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { data[y, x] = (float)ImportedColors[x + y * w].r / 0.567f; // 0.58 } } } else { using (var file = System.IO.File.OpenRead(paths[0])) using (var reader = new System.IO.BinaryReader(file)) { long CheckValue = 2; CheckValue *= (long)(w); CheckValue *= (long)(h); long FileLength = file.Length; if (FileLength != CheckValue) { reader.Dispose(); file.Dispose(); GenericPopup.ShowPopup(GenericPopup.PopupTypes.Error, "Error", "Selected heightmap is in wrong size.\nIs: " + FileLength + "B, should be: " + CheckValue + "B", "OK", null); return; } for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { float v = (float)(reader.ReadUInt16() / ScmapEditor.HeightResize); data[h - (y + 1), x] = v; } } } } //ScmapEditor.Current.Teren.terrainData.SetHeights(0, 0, data); ScmapEditor.SetAllHeights(data); RegenerateMaps(); OnTerrainChanged(); EnvPaths.SetLastPath(ExportPathKey, Path.GetDirectoryName(paths[0])); GenericInfoPopup.ShowInfo("Heightmap import success!\n" + Path.GetFileName(paths[0])); if (ScmapEditor.IsOverMinMaxDistance()) { GenericPopup.ShowPopup(GenericPopup.PopupTypes.TriButton, "Importing heightmap", "Distance between lowest and highest point is higher than 50.\nClamp it?", "Clamp Top", ClampTop, "Clamp Bottom", ClampBottom, "Ignore", null); } }
Mesh GenerateMesh(MafiaFormats.Mesh mafiaMesh, GameObject ent, MafiaFormats.LOD firstMafiaLOD, MafiaFormats.Model model, out Material[] materials) { var mesh = new Mesh(); var bmp = new BMPLoader(); List <Material> mats = new List <Material>(); List <Vector3> unityVerts = new List <Vector3>(); List <Vector3> unityNormals = new List <Vector3>(); List <Vector2> unityUV = new List <Vector2>(); foreach (var vert in firstMafiaLOD.vertices) { unityVerts.Add(vert.pos); unityNormals.Add(vert.normal); unityUV.Add(new Vector2(vert.uv.x, -1 * vert.uv.y)); } mesh.name = mafiaMesh.meshName; mesh.SetVertices(unityVerts); mesh.SetUVs(0, unityUV); mesh.SetNormals(unityNormals); mesh.subMeshCount = firstMafiaLOD.faceGroups.Count; var faceGroupId = 0; foreach (var faceGroup in firstMafiaLOD.faceGroups) { List <int> unityIndices = new List <int>(); foreach (var face in faceGroup.faces) { unityIndices.Add(face.a); unityIndices.Add(face.b); unityIndices.Add(face.c); } mesh.SetTriangles(unityIndices.ToArray(), faceGroupId); var matId = (int)Mathf.Max(0, Mathf.Min(model.materials.Count - 1, faceGroup.materialID - 1)); if (model.materials.Count > 0) { var mafiaMat = model.materials[matId]; Material mat; if ((mafiaMat.flags & MafiaFormats.MaterialFlag.Colorkey) != 0) { mat = new Material(Shader.Find("Standard")); mat.SetFloat("_Mode", 1f); // Set rendering mode to Cutout mat.SetFloat("_Glossiness", 0f); mat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); mat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); mat.SetInt("_ZWrite", 1); mat.DisableKeyword("_ALPHATEST_ON"); mat.EnableKeyword("_ALPHABLEND_ON"); mat.DisableKeyword("_ALPHAPREMULTIPLY_ON"); mat.renderQueue = 3000; } else if (mafiaMat.transparency < 1) { mat = new Material(Shader.Find("Standard")); mat.SetFloat("_Mode", 3f); // Set rendering mode to Transparent mat.SetFloat("_Glossiness", 0f); mat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); mat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); mat.SetInt("_ZWrite", 1); mat.DisableKeyword("_ALPHATEST_ON"); mat.EnableKeyword("_ALPHABLEND_ON"); mat.DisableKeyword("_ALPHAPREMULTIPLY_ON"); mat.renderQueue = 3000; } else { mat = new Material(Shader.Find("Standard")); mat.SetFloat("_Glossiness", 0f); } //if (matId > 0) { // TODO support more types as well as transparency if (mafiaMat.diffuseMapName != null || mafiaMat.alphaMapName != null) { if ((mafiaMat.flags & MafiaFormats.MaterialFlag.Colorkey) != 0) { BMPLoader.useTransparencyKey = true; } BMPImage image = null; if ((mafiaMat.flags & MafiaFormats.MaterialFlag.Textured_Diffuse) != 0) { image = bmp.LoadBMP(GameManager.instance.fileSystem.GetPath(Path.Combine("maps", mafiaMat.diffuseMapName))); } else if (mafiaMat.alphaMapName != null) { image = bmp.LoadBMP(GameManager.instance.fileSystem.GetPath(Path.Combine("maps", mafiaMat.alphaMapName))); } BMPLoader.useTransparencyKey = false; if (image != null) { Texture2D tex = image.ToTexture2D(); if ((mafiaMat.flags & MafiaFormats.MaterialFlag.Textured_Diffuse) != 0) { tex.name = mafiaMat.diffuseMapName; } else if (mafiaMat.alphaMapName != null) { tex.name = mafiaMat.alphaMapName; } mat.SetTexture("_MainTex", tex); if (GameManager.instance.cvarManager.Get("filterMode", "1") == "0") { tex.filterMode = FilterMode.Point; } } if (mafiaMat.transparency < 1) { mat.SetColor("_Color", new Color32(255, 255, 255, (byte)(mafiaMat.transparency * 255))); } if ((mafiaMat.flags & (MafiaFormats.MaterialFlag.Animated_Texture_Diffuse | MafiaFormats.MaterialFlag.Animated_Texture_Alpha)) != 0) { List <Texture2D> frames = new List <Texture2D>(); string fileName = null; if ((mafiaMat.flags & MafiaFormats.MaterialFlag.Animated_Texture_Diffuse) != 0) { fileName = mafiaMat.diffuseMapName; } else { fileName = mafiaMat.alphaMapName; } if ((mafiaMat.flags & MafiaFormats.MaterialFlag.Colorkey) != 0) { BMPLoader.useTransparencyKey = true; } if (fileName != null) { var path = fileName.Split('.'); string baseName = path[0]; string ext = path[1]; baseName = baseName.Substring(0, baseName.Length - 2); for (int k = 0; k < mafiaMat.animSequenceLength; k++) { try { var animPath = Path.Combine("maps", baseName + k.ToString("D2") + "." + ext); var frameImage = bmp.LoadBMP(GameManager.instance.fileSystem.GetPath(animPath)); if (frameImage == null) { continue; } var frame = frameImage.ToTexture2D(); frames.Add(frame); } catch (Exception ex) { Debug.LogError(ex.ToString()); } } var framePlayer = ent.AddComponent <TextureAnimationPlayer>(); framePlayer.frames = frames; framePlayer.framePeriod = mafiaMat.framePeriod; framePlayer.material = mat; } BMPLoader.useTransparencyKey = false; } } } mats.Add(mat); } faceGroupId++; } materials = mats.ToArray(); return(mesh); }
//[MenuItem("Ragnarok/Test Import Texture")] //static void TestImportTexture() //{ // //var file = EditorUtility.OpenFilePanel("Load Image", ) // var tex = LoadTexture(@"G:\Projects2\Ragnarok\Resources\data\texture\기타마을\sage_bar01.bmp"); // var png = tex.EncodeToPNG(); // File.WriteAllBytes(@"G:\Projects2\test.png", png); //} private static Texture2D LoadTexture(string path) { var bmp = new BMPLoader(); bmp.ForceAlphaReadWhenPossible = false; var img = bmp.LoadBMP(path); var colors = (Color32[])img.imageData.Clone(); var width = img.info.width; var height = img.info.height; //magic pink conversion and transparent color expansion for (var y = 0; y < width; y++) { for (var x = 0; x < height; x++) { var count = 0; var r = 0; var g = 0; var b = 0; var color = colors[x + y * width]; if (color.r != 255 || color.g != 0 || color.b != 255) { continue; } //Debug.Log("OHWOW: " + color); for (var y2 = -1; y2 <= 1; y2++) { for (var x2 = -1; x2 <= 1; x2++) { if (y + y2 < 0 || y + y2 >= width) { continue; } if (x + x2 < 0 || x + x2 >= height) { continue; } var color2 = colors[x + x2 + (y + y2) * width]; if (color2.r == 255 && color2.g == 0 && color2.b == 255) { continue; } count++; r += color2.r; g += color2.g; b += color2.b; } } if (count > 0) { var r2 = (byte)Mathf.Clamp(r / count, 0, 255); var g2 = (byte)Mathf.Clamp(g / count, 0, 255); var b2 = (byte)Mathf.Clamp(b / count, 0, 255); //Debug.Log($"{x},{y} - change {color} to {r2},{g2},{b2}"); img.imageData[x + y * width] = new Color32(r2, g2, b2, 0); } else { img.imageData[x + y * width] = new Color32(0, 0, 0, 0); } } } return(img.ToTexture2D()); }
void GenerateSpritesAndAnimations(bool createSprites, bool createAnimations) { string separator = Path.DirectorySeparatorChar.ToString(); string dataPath = Path.GetFullPath("Assets" + separator + "BinaryFiles" + separator + "Data"); string spritePath = Path.GetFullPath("Assets" + separator + "Resources" + separator + "Sprites"); string compiledFilesPath = Path.GetFullPath("Assets" + separator + "CompiledFiles"); string animationsPath = "Assets" + separator + "Resources" + separator + "Animations" + separator; List <AnimationFrameReferences> animationFrames = new List <AnimationFrameReferences>(); foreach (string file in Directory.GetFiles(dataPath, "*.adf")) { string fileName = Path.GetFileName(file); byte[] bytes = File.ReadAllBytes(file); BinaryReader reader = new BinaryReader(new MemoryStream(bytes)); StreamWriter writer = new StreamWriter(compiledFilesPath + separator + Path.GetFileName(file) + "-header.txt"); byte fileType = reader.ReadByte(); int extraLength = reader.ReadInt32() + 1; writer.WriteLine("Type: {0}, Extra Length: {1}", fileType, extraLength); writer.Write("Extra Bytes: "); for (int i = 0; i < extraLength - 1; i++) { writer.Write("{0,4}", reader.ReadByte()); // Not sure if offset is needed here } byte offset = reader.ReadByte(); writer.WriteLine(); int numberOfFrames = ApplyOffset(reader.ReadInt32(), offset); writer.WriteLine("NumberOfFrames: {0}", numberOfFrames); ChildSpriteCoordinates[] childSprites = new ChildSpriteCoordinates[numberOfFrames]; int totalSprites = 0; for (int i = 0; i < numberOfFrames; i++) { int id = ApplyOffset(reader.ReadInt32(), offset); byte animationLength = ApplyOffsetByte(reader.ReadByte(), offset); if (animationLength == 1) { int imageId = id; int x = ApplyOffset(reader.ReadInt32(), offset); int y = ApplyOffset(reader.ReadInt32(), offset); int width = ApplyOffset(reader.ReadInt32(), offset); int height = ApplyOffset(reader.ReadInt32(), offset); childSprites[totalSprites++] = new ChildSpriteCoordinates(imageId, x, y, width, height); writer.WriteLine("Id: {0,4} X: {1,4} Y: {2,4} W: {3,4} H: {4,4}", imageId, x, y, width, height); } else { int animationId = id; AnimationFrameReferences animReference = new AnimationFrameReferences(animationId); writer.Write("Animation Id: {0,6} Frame Ids:", animationId); for (int j = 0; j < animationLength; ++j) { int frameId = ApplyOffset(reader.ReadInt32(), offset); animReference.AddFrame(frameId); writer.Write(" {0,6}", frameId); } byte delimiter = ApplyOffsetByte(reader.ReadByte(), offset); animationFrames.Add(animReference); writer.WriteLine(" Delimiter: {0}", delimiter); } } if (numberOfFrames != totalSprites) { Debug.Log(fileName + " Frames: " + numberOfFrames + " Sprites: " + totalSprites); } if (offset != bytes[bytes.Length - 2]) { Debug.Log(fileName + " Offset: " + offset + " SecondLastByte: " + bytes[bytes.Length - 2]); } int unknown = ApplyOffset(reader.ReadInt32(), offset); writer.WriteLine("U: {0}", unknown); writer.Close(); if (createSprites) { int length = (int)(reader.BaseStream.Length - reader.BaseStream.Position); byte[] buffer = reader.ReadBytes(length); byte[] data = new byte[RealSize(buffer.Length, 0x315)]; for (int k = 0; k < buffer.Length; k++) { data[k - (k / 790)] = ApplyOffsetByte(buffer[k], offset); } string compiledFileNamePath = compiledFilesPath + separator + fileName.Substring(0, fileName.IndexOf('.')); if (unknown == 36) { File.WriteAllBytes(compiledFileNamePath + ".wav", data); continue; } BMPLoader bmpLoader = new BMPLoader(); BMPImage bmpImg = bmpLoader.LoadBMP(data); if (bmpImg == null) { continue; } Texture2D tex = bmpImg.ToTexture2D(); RemoveBlackBackground(tex); SaveTextureAsPNG(tex, compiledFileNamePath + ".png"); for (int i = 0; i < totalSprites; ++i) { tex = GetChildSprite(bmpImg.ToTexture2D(), childSprites[i]); RemoveBlackBackground(tex); SaveTextureAsPNG(tex, spritePath + separator + childSprites[i].frameId + ".png"); } } } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); if (createAnimations) { foreach (AnimationFrameReferences animReference in animationFrames) { Sprite[] animSprites = new Sprite[animReference.frameList.Count]; int spriteIndex = 0; foreach (int frameId in animReference.frameList) { animSprites[spriteIndex++] = Resources.Load <Sprite>("Sprites" + separator + frameId); //atlas.GetSprite(spriteId); } CreateAnimation(animationsPath, animReference.animationId.ToString(), animSprites, 8, true); } } Debug.Log("End"); }
private IEnumerator OutputRoutine(string url) { url = url.Replace('\\', '/'); // should be PNG or JPEG using (UnityWebRequest loader = UnityWebRequestTexture.GetTexture(url)) { yield return(loader.SendWebRequest()); byte[] ba = ((DownloadHandlerTexture)loader.downloadHandler).data; char[] data = System.Text.Encoding.UTF8.GetChars(ba); if (data[0] == 'B' && data[1] == 'M') { // BMP file detected BMPLoader bmp_loader = new BMPLoader(); // can be uncomment to read alpha (sometimes breaks) //bmp_loader.ForceAlphaReadWhenPossible = true; //load the image data BMPImage bmp_img = bmp_loader.LoadBMP(ba); // Convert the Color32 array into a Texture2D input_image.texture = bmp_img.ToTexture2D(); } else { // assign directly to input texture input_image.texture = ((DownloadHandlerTexture)loader.downloadHandler).texture as Texture2D; } } // store filename without extension for later use ImageUtilities.filename = Path.GetFileNameWithoutExtension(url); // fix html encoded spaces if (ImageUtilities.filename.IndexOf("%20") > -1) { ImageUtilities.filename = ImageUtilities.filename.Replace("%20", " "); } // tell unity to load palette data on next frame update //byte[] b = ((DownloadHandlerTexture)loader.downloadHandler).GetData(); //ImageUtilities.input_palette = ImageUtilities.LoadImagePalette(((DownloadHandlerTexture)loader.downloadHandler).texture.GetRawTextureData<Color32>(), true); ImageUtilities.output_palette.Clear(); ImageUtilities.input_palette = ImageUtilities.LoadImagePalette((input_image.mainTexture as Texture2D).GetPixels32(0)); // try to do recolor work from input to output ImageUtilities.SetOutputImage(); // get image size float wide = input_image.texture.width; float high = input_image.texture.height; // fix aspect ratio to retain original proportions input_image.rectTransform.sizeDelta = new Vector2(wide, high); output_image.rectTransform.sizeDelta = new Vector2(wide, high); // set preview images to origin input_image.rectTransform.localPosition = new Vector3(0, 0, 1); output_image.rectTransform.localPosition = new Vector3(0, 0, 1); // set Texture.filterMode to point to stop the weird filtered look input_image.texture.filterMode = FilterMode.Point; output_image.texture.filterMode = FilterMode.Point; // set zoom level to default ImageUtilities.ZoomReset(); }