예제 #1
0
        private static Texture2D GetTextureFromBMP(byte[] bmpData)
        {
            BMPLoader bmpLoader = new BMPLoader();
            BMPImage  bmpImage  = bmpLoader.LoadBMP(bmpData);

            return(bmpImage.ToTexture2D());
        }
    // https://stackoverflow.com/questions/51975990/how-can-i-use-a-bmp-file-and-create-a-texture-in-unity-at-runtime
    public static Texture2D LoadTextureBMP(string filePath)
    {
        Texture2D tex;

        byte[] fileData;

        if (File.Exists(filePath) && Path.GetExtension(filePath) == ".bmp")
        {
            fileData = File.ReadAllBytes(filePath);

            BMPLoader bmpLoader = new BMPLoader();
            //bmpLoader.ForceAlphaReadWhenPossible = true; //Uncomment to read alpha too

            //Load the BMP data
            BMPImage bmpImg = bmpLoader.LoadBMP(fileData);

            //Convert the Color32 array into a Texture2D
            tex = bmpImg.ToTexture2D();
            tex.Apply();
        }
        else
        {
            throw new Exception("File not found or not in specified format");
        }

        return(tex);
    }
예제 #3
0
    Sprite LoadSpriteBmp(string folder, string filename)
    {
        var bits = Util.LoadBinary(folder, filename);

        if (bits == null)
        {
            return(null);
        }
        var bmpload = new BMPLoader();

        if (bmpload == null)
        {
            return(null);
        }
        var bmp = bmpload.LoadBMP(bits);

        if (bmp == null)
        {
            return(null);
        }
        var transparency = Color.green; // pure green is transparent

        for (int i = 0; i < bmp.imageData.Length; ++i)
        {
            if (bmp.imageData[i] == transparency)
            {
                bmp.imageData[i] = Color.clear;
            }
        }
        var tex = bmp.ToTexture2D();

        return(Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.zero));
    }
예제 #4
0
    //画像ファイルを外部から読み込む
    private Sprite getSprite(string filename)
    {
        string tmpFileName = filename.ToLower();

        byte[] bytes = LoadBytes(filename);

        Texture2D tex = new Texture2D(0, 0);;

        if (tmpFileName.Contains(".bmp"))
        {
            BMPLoader loader   = new BMPLoader();
            var       bmpImage = loader.LoadBMP(bytes);
            tex = bmpImage.ToTexture2D();
        }
        else
        {
            tex.LoadImage(bytes);
        }


        Sprite s = Sprite.Create(
            tex,
            new Rect(0f, 0f, tex.width, tex.height),
            new Vector2(0.5f, 0.5f)
            );

        return(s);
    }
예제 #5
0
    // 텍스처 파일 .bmp 로드
    void LoadBMP(string path)
    {
        BMPLoader loader = new BMPLoader();
        BMPImage  bmpㅑmg = loader.LoadBMP(path);

        texture = bmpㅑmg.ToTexture2D();
    }
예제 #6
0
    public static Texture2D LoadTexture(string filePath)
    {
        Texture2D tex = null;

        byte[] fileData;

        Debug.Log(filePath);

        try
        {
            if (File.Exists(filePath))
            {
                fileData = File.ReadAllBytes(filePath);

                BMPLoader bmpLoader = new BMPLoader();
                //bmpLoader.ForceAlphaReadWhenPossible = true; //Uncomment to read alpha too

                //Load the BMP data
                BMPImage bmpImg = bmpLoader.LoadBMP(fileData);

                //Convert the Color32 array into a Texture2D
                tex = bmpImg.ToTexture2D();
            }
            else
            {
                Debug.Log("File doesn't exist");
            }
        }
        catch (Exception e)
        {
            Debug.Log("Couldn't convert image: " + e);
        }
        return(tex);
    }
예제 #7
0
    Maze ReadMaze(string bitmap, string brick)
    {
        var cubePrefab = Resources.Load(brick) as GameObject;
        var loaded     = new BMPLoader();
        var bmp        = loaded.LoadBMP(bitmap);
        var texture    = bmp.ToTexture2D();
        var width      = texture.width;
        var height     = texture.height;
        var row        = 0;
        var objects    = new List <GameObject>();

        for (var i = 0; i < bmp.imageData.Length; i += width)
        {
            row += 1;
            for (int j = 0; j < width; j++)
            {
                var color = bmp.imageData[i + j];
                if (color.r == 0 && color.g == 0 && color.b == 0)
                {
                    var cube     = Instantiate(cubePrefab) as GameObject;
                    var collider = cube.GetComponent <Collider>();
                    var bounds   = collider.bounds;
                    var position = new Vector3(j * bounds.size.x, row * bounds.size.y, 0);
                    cube.transform.position = position;
                    objects.Add(cube);
                }
            }
        }
        return(new Maze(width, height, objects));
    }
예제 #8
0
        public static Texture2D Load(byte[] data, string fileName)
        {
            var tex = new Texture2D(2, 2);

            if (Regex.IsMatch(Path.GetExtension(fileName), @"\.bmp$", RegexOptions.IgnoreCase))
            {
                // bmp
                var bmpLoader = new BMPLoader();
                tex = bmpLoader.LoadBMP(data).ToTexture2D();
            }
            else
            {
                // png, jpg
                tex.LoadImage(data);
            }
            return(tex);
        }
예제 #9
0
    public static Texture2D LoadTexture(string filePath)
    {
        Texture2D tex = null;

        if (File.Exists(filePath))
        {
            BMPLoader bmpLoader = new BMPLoader();
            bmpLoader.ForceAlphaReadWhenPossible = true;     //Uncomment to read alpha too

            //Load the BMP data
            BMPImage bmpImg = bmpLoader.LoadBMP(filePath);

            //Convert the Color32 array into a Texture2D
            tex = bmpImg.ToTexture2D();
        }
        return(tex);
    }
예제 #10
0
    private IEnumerator OutputRoutine(string url)
    {
        url = url.Replace('\\', '/');

        using (var 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
                ImageUtilities.output_palette.Clear();
                ImageUtilities.output_palette.AddRange(ImageUtilities.LoadImagePalette(bmp_img.imageData));
            }
            else
            {
                // save output palette list
                ImageUtilities.output_palette.Clear();
                ImageUtilities.output_palette.AddRange(ImageUtilities.LoadImagePalette(((DownloadHandlerTexture)loader.downloadHandler).texture.GetPixels32(0)));
            }
        }


        // auto-magically find nearest color neighbor using CIE2000 color distance algorithm
        ImageUtilities.FindClosest();

        // try to do recolor work from input to output
        ImageUtilities.SetOutputImage();
    }
예제 #11
0
    public void CreateCustomMap()
    {
        int i, j;

        if (this.filePath == "none")
        {
            this.filePath = FileBrowser.OpenSingleFile("bmp");
        }
        Texture2D texture = null;

        byte[] fileData = File.ReadAllBytes(this.filePath);

        BMPLoader bmpLoader = new BMPLoader();

        //Load the BMP data
        BMPImage bmpImg = bmpLoader.LoadBMP(fileData);

        //Convert the Color32 array into a Texture2D
        texture = bmpImg.ToTexture2D();

        for (i = 0; i < texture.width; i++)
        {
            for (j = 0; j < texture.height; j++)
            {
                if (texture.GetPixel(i, j).r == 0)
                {
                    this.map[i, j] = (int)Definition.pointEnum.WALL;
                }
                else
                {
                    this.map[i, j] = (int)Definition.pointEnum.EMPTY;
                }
            }
        }

        //Draw the map using mesh
        envMeshHandler = GetComponent <EnvironmentMeshHandler>();
        envMeshHandler.GenerateMeshWall(map, 1);
    }
예제 #12
0
    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");
        }
    }
예제 #13
0
        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();
        }
예제 #14
0
        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());
        }
예제 #15
0
        /// <summary>
        /// Loads a texture from a file
        /// </summary>
        /// <param name="fn"></param>
        /// <param name="normalMap"></param>
        /// <returns></returns>
        public static Texture2D LoadTexture(string fn)
        {
            if (!File.Exists(fn))
            {
                return(null);
            }

            var       textureBytes = File.ReadAllBytes(fn);
            string    ext          = Path.GetExtension(fn).ToLower();
            string    name         = Path.GetFileName(fn);
            Texture2D returnTex    = null;

            switch (ext)
            {
            case ".png":
            case ".jpg":
            case ".jpeg":
                returnTex = new Texture2D(1, 1);
                returnTex.LoadImage(textureBytes);
                returnTex = ImageLoaderHelper.VerifyFormat(returnTex);
                break;

            case ".dds":
                returnTex = DDSLoader.Load(textureBytes);
                break;

            case ".tga":
                returnTex = TGALoader.Load(textureBytes);
                break;

            case ".bmp":
                returnTex = new BMPLoader().LoadBMP(textureBytes).ToTexture2D();
                break;

            case ".crn":
                byte[] crnBytes = textureBytes;
                ushort crnWidth = System.BitConverter.ToUInt16(new byte[2] {
                    crnBytes[13], crnBytes[12]
                }, 0);
                ushort crnHeight = System.BitConverter.ToUInt16(new byte[2] {
                    crnBytes[15], crnBytes[14]
                }, 0);
                byte crnFormatByte = crnBytes[18];

                var crnTextureFormat = UnityEngine.TextureFormat.RGB24;
                if (crnFormatByte == 0)
                {
                    crnTextureFormat = UnityEngine.TextureFormat.DXT1Crunched;
                }
                else if (crnFormatByte == 2)
                {
                    crnTextureFormat = UnityEngine.TextureFormat.DXT5Crunched;
                }
                else if (crnFormatByte == 12)
                {
                    crnTextureFormat = UnityEngine.TextureFormat.ETC2_RGBA8Crunched;
                }
                else
                {
                    Debug.LogError("Could not load crunched texture " + name + " because its format is not supported (" + crnFormatByte + "): " + fn);
                    break;
                }

                returnTex = new Texture2D(crnWidth, crnHeight, crnTextureFormat, true);
                returnTex.LoadRawTextureData(crnBytes);
                returnTex.Apply(true);

                break;

            default:
                Debug.LogError("Could not load texture " + name + " because its format is not supported : " + fn);
                break;
            }

            if (returnTex != null)
            {
                returnTex.name = Path.GetFileNameWithoutExtension(fn);
            }

            return(returnTex);
        }
예제 #16
0
        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);
            }
        }
예제 #17
0
 private void Start()
 {
     bmpLoader = new BMPLoader();
     character = (RedCharacter)(GameManager.Instance.MainCharacter);
 }
예제 #18
0
        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());
        }
예제 #20
0
    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");
    }
예제 #21
0
    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();
    }