private void loadCharmapToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Test BMP Image Class
            BMPImage bm = new BMPImage("courier.bmp");


            /* PNG CHARMAP CONVERT TO BMP
             *
             * //Opening PNG file
             * //Image im = Image.FromFile("courier_charmap.png");
             * //MemoryStream ms = new MemoryStream();
             * //im.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
             *
             */

            //Testing some inits
            mainfont.initFromImage(bm);
            mainfont.tex     = bm.GLid;
            mainfont.program = shader_program;

            //Set default settings
            mainfont.space  = 0.14f;
            mainfont.width  = 0.14f;
            mainfont.height = 0.14f;

            //Add some text for rendering
            tobs.Add(mainfont.renderText("Life Sucks :(", new Vector2(0.2f, 0.2f), 2.0f));
        }
Beispiel #2
0
        public void Initialize()
        {
            FileStream input = new FileStream("../../../pictures/picture.bmp", FileMode.Open, FileAccess.Read);

            ResultImage = new BMPImage(input);
            input.Close();
        }
    // 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);
    }
    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);
    }
Beispiel #5
0
            public static List <Color32> ReadPalette(BinaryReader aReader, BMPImage aBmp, bool aReadAlpha)
            {
                uint count = aBmp.info.nPaletteColors;

                if (count == 0u)
                {
                    count = 1u << aBmp.info.nBitsPerPixel;
                }
                var palette = new List <Color32>((int)count);

                for (int i = 0; i < count; i++)
                {
                    byte b = aReader.ReadByte();
                    byte g = aReader.ReadByte();
                    byte r = aReader.ReadByte();
                    byte a = aReader.ReadByte();
                    if (!aReadAlpha)
                    {
                        a = 255;
                    }
                    palette.Add(new Color32(r, g, b, a));
                }

                return(palette);
            }
Beispiel #6
0
        public void ApplyGrayscaleTest()
        {
            Filters.ApplyGrayscale(ResultImage);
            TargetImage = new BMPImage(new FileStream("../../../pictures/picture_grayscale.bmp", FileMode.Open, FileAccess.Read));

            Assert.IsTrue(AreEqual(ResultImage, TargetImage));
        }
        private static Texture2D GetTextureFromBMP(byte[] bmpData)
        {
            BMPLoader bmpLoader = new BMPLoader();
            BMPImage  bmpImage  = bmpLoader.LoadBMP(bmpData);

            return(bmpImage.ToTexture2D());
        }
Beispiel #8
0
    // 텍스처 파일 .bmp 로드
    void LoadBMP(string path)
    {
        BMPLoader loader = new BMPLoader();
        BMPImage  bmpㅑmg = loader.LoadBMP(path);

        texture = bmpㅑmg.ToTexture2D();
    }
Beispiel #9
0
            private static void Read32BitImage(BinaryReader aReader, BMPImage bmp)
            {
                int w = Mathf.Abs(bmp.info.width);
                int h = Mathf.Abs(bmp.info.height);

                Color32[] data = bmp.imageData = new Color32[w * h];
                if (aReader.BaseStream.Position + w * h * 4 > aReader.BaseStream.Length)
                {
                    Debug.LogError("Unexpected end of file.");
                    return;
                }

                int  shiftR = GetShiftCount(bmp.rMask);
                int  shiftG = GetShiftCount(bmp.gMask);
                int  shiftB = GetShiftCount(bmp.bMask);
                int  shiftA = GetShiftCount(bmp.aMask);
                byte a      = 255;

                for (int i = 0; i < data.Length; i++)
                {
                    uint v = aReader.ReadUInt32();
                    byte r = (byte)((v & bmp.rMask) >> shiftR);
                    byte g = (byte)((v & bmp.gMask) >> shiftG);
                    byte b = (byte)((v & bmp.bMask) >> shiftB);
                    if (bmp.bMask != 0)
                    {
                        a = (byte)((v & bmp.aMask) >> shiftA);
                    }
                    data[i] = new Color32(r, g, b, a);
                }
            }
        public void TestReadWriteFile()
        {
            BMPImage image = new BMPImage("../../../TestFiles/input24.bmp");

            image.WriteToFile("../../../TestFiles/output.bmp");
            FileAssert.AreEqual("../../../TestFiles/input24.bmp", "../../../TestFiles/output.bmp");
            Assert.Pass();
        }
        public void TestSobelYFilter24()
        {
            BMPImage image = new BMPImage("../../../TestFiles/input24.bmp");

            KernelFilters.SobelY(image);
            image.WriteToFile("../../../TestFiles/output.bmp");
            FileAssert.AreEqual("../../../TestFiles/output.bmp", "../../../TestFiles/SobelY24.bmp");
            Assert.Pass();
        }
        public void TestGaussFilter32()
        {
            BMPImage image = new BMPImage("../../../TestFiles/input32.bmp");

            KernelFilters.Gauss(image);
            image.WriteToFile("../../../TestFiles/output.bmp");
            FileAssert.AreEqual("../../../TestFiles/output.bmp", "../../../TestFiles/Gauss32.bmp");
            Assert.Pass();
        }
        public void TestGrayFilter24()
        {
            BMPImage image = new BMPImage("../../../TestFiles/input24.bmp");

            GrayFilter.Gray(image);
            image.WriteToFile("../../../TestFiles/output.bmp");
            FileAssert.AreEqual("../../../TestFiles/output.bmp", "../../../TestFiles/Gray24.bmp");
            Assert.Pass();
        }
        public void TestMedianFilter32()
        {
            BMPImage image = new BMPImage("../../../TestFiles/input32.bmp");

            MedianFilter.Median(image);
            image.WriteToFile("../../../TestFiles/output.bmp");
            FileAssert.AreEqual("../../../TestFiles/output.bmp", "../../../TestFiles/Median32.bmp");
            Assert.Pass();
        }
        public void TestGetPixel()
        {
            BMPImage image  = new BMPImage("../../../TestFiles/input24.bmp");
            Pixel    result = image.GetPixel(128, 128);

            Assert.AreEqual(new Pixel(15, 3, 1).Red, result.Red);
            Assert.AreEqual(new Pixel(15, 3, 1).Green, result.Green);
            Assert.AreEqual(new Pixel(15, 3, 1).Blue, result.Blue);
            Assert.Pass();
        }
Beispiel #16
0
        private void glControl1_Load(object sender, EventArgs e)
        {
            GL.Viewport(0, 0, glControl1.ClientSize.Width, glControl1.ClientSize.Height);
            GL.ClearColor(System.Drawing.Color.Black);
            GL.Enable(EnableCap.DepthTest);
            //glControl1.SwapBuffers();
            //glControl1.Invalidate();
            Debug.WriteLine("GL Cleared");
            Debug.WriteLine(GL.GetError());

            this.glloaded = true;

            //Generate Geometry VBOs
            GL.GenBuffers(1, out quad_vbo);
            GL.GenBuffers(1, out quad_ebo);

            //Bind Geometry Buffers
            int arraysize = sizeof(float) * 4 * 3;

            //Upload vertex buffer
            GL.BindBuffer(BufferTarget.ArrayBuffer, quad_vbo);
            //Allocate to NULL
            GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(arraysize), (IntPtr)null, BufferUsageHint.StaticDraw);
            //Add verts data
            GL.BufferSubData(BufferTarget.ArrayBuffer, (IntPtr)0, (IntPtr)arraysize, quadverts);

            //Upload index buffer
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, quad_ebo);
            GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(sizeof(Int32) * 6), quadindices, BufferUsageHint.StaticDraw);


            //Compile Shaders
            string vvs, ffs;
            int    vertex_shader_ob, fragment_shader_ob;

            vvs = GLSL_Preprocessor.Parser("Shaders/Text_VS.glsl");
            ffs = GLSL_Preprocessor.Parser("Shaders/Text_FS.glsl");
            //Compile Texture Shaders
            GLShaderHelper.CreateShaders(vvs, ffs, out vertex_shader_ob,
                                         out fragment_shader_ob, out shader_program);


            //Setup default program
            GL.UseProgram(shader_program);


            //Load Sample texture
            //Test BMP Image Class
            BMPImage bm = new BMPImage("courier.bmp");

            sampleTex = bm.GLid;


            glControl1.Invalidate();
        }
Beispiel #17
0
            private static void ReadIndexedImageRLE8(BinaryReader aReader, BMPImage bmp)
            {
                int w = Mathf.Abs(bmp.info.width);
                int h = Mathf.Abs(bmp.info.height);

                Color32[] data    = bmp.imageData = new Color32[w * h];
                int       x       = 0;
                int       y       = 0;
                int       yOffset = 0;

                while (aReader.BaseStream.Position < aReader.BaseStream.Length - 1)
                {
                    int  count = (int)aReader.ReadByte();
                    byte d     = aReader.ReadByte();
                    if (count > 0)
                    {
                        for (int i = count; i > 0; i--)
                        {
                            data[x++ + yOffset] = bmp.palette[d];
                        }
                    }
                    else
                    {
                        if (d == 0)
                        {
                            x       = 0;
                            y      += 1;
                            yOffset = y * w;
                        }
                        else if (d == 1)
                        {
                            break;
                        }
                        else if (d == 2)
                        {
                            x      += aReader.ReadByte();
                            y      += aReader.ReadByte();
                            yOffset = y * w;
                        }
                        else
                        {
                            for (int i = d; i > 0; i--)
                            {
                                data[x++ + yOffset] = bmp.palette[aReader.ReadByte()];
                            }

                            if ((d & 0x01) > 0)
                            {
                                aReader.ReadByte(); // padding (word alignment)
                            }
                        }
                    }
                }
            }
Beispiel #18
0
        public static void Test()
        {
            BMPImage  bmp    = new BMPImage();
            IImageImp winImp = new WinImg();

            bmp.setImageImg(winImp);
            bmp.Method("BMP begin to paint");
            IImageImp unixImp = new UnixImg();

            bmp.setImageImg(unixImp);
            bmp.Method("BMP begin to paint");
        }
Beispiel #19
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);
    }
Beispiel #20
0
            private static void Read16BitImage(BinaryReader aReader, BMPImage bmp)
            {
                int w         = Mathf.Abs(bmp.info.width);
                int h         = Mathf.Abs(bmp.info.height);
                int rowLength = ((16 * w + 31) / 32) * 4;
                int count     = rowLength * h;
                int pad       = rowLength - w * 2;

                Color32[] data = bmp.imageData = new Color32[w * h];
                if (aReader.BaseStream.Position + count > aReader.BaseStream.Length)
                {
                    Debug.LogError("Unexpected end of file. (Have " + (aReader.BaseStream.Position + count) +
                                   " bytes, expected " + aReader.BaseStream.Length + " bytes)");
                    return;
                }

                int  shiftR = GetShiftCount(bmp.rMask);
                int  shiftG = GetShiftCount(bmp.gMask);
                int  shiftB = GetShiftCount(bmp.bMask);
                int  shiftA = GetShiftCount(bmp.aMask);
                byte a      = 255;

                for (int y = 0; y < h; y++)
                {
                    for (int x = 0; x < w; x++)
                    {
                        uint v = aReader.ReadByte() | ((uint)aReader.ReadByte() << 8);
                        byte r = (byte)((v & bmp.rMask) >> shiftR);
                        byte g = (byte)((v & bmp.gMask) >> shiftG);
                        byte b = (byte)((v & bmp.bMask) >> shiftB);
                        if (bmp.aMask != 0)
                        {
                            a = (byte)((v & bmp.aMask) >> shiftA);
                        }
                        data[x + y * w] = new Color32(r, g, b, a);
                    }

                    for (int i = 0; i < pad; i++)
                    {
                        aReader.ReadByte();
                    }
                }
            }
Beispiel #21
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();
    }
Beispiel #22
0
            private static void ReadIndexedImage(BinaryReader aReader, BMPImage bmp)
            {
                int w         = Mathf.Abs(bmp.info.width);
                int h         = Mathf.Abs(bmp.info.height);
                int bitCount  = bmp.info.nBitsPerPixel;
                int rowLength = ((bitCount * w + 31) / 32) * 4;
                int count     = rowLength * h;
                int pad       = rowLength - (w * bitCount + 7) / 8;

                Color32[] data = bmp.imageData = new Color32[w * h];
                if (aReader.BaseStream.Position + count > aReader.BaseStream.Length)
                {
                    Debug.LogError("Unexpected end of file. (Have " + (aReader.BaseStream.Position + count) +
                                   " bytes, expected " + aReader.BaseStream.Length + " bytes)");
                    return;
                }

                BitStreamReader bitReader = new BitStreamReader(aReader);

                for (int y = 0; y < h; y++)
                {
                    for (int x = 0; x < w; x++)
                    {
                        int v = (int)bitReader.ReadBits(bitCount);
                        if (v >= bmp.palette.Count)
                        {
                            Debug.LogError("Indexed bitmap has indices greater than it's color palette");
                            return;
                        }

                        data[x + y * w] = bmp.palette[v];
                    }

                    bitReader.Flush();
                    for (int i = 0; i < pad; i++)
                    {
                        aReader.ReadByte();
                    }
                }
            }
    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);
    }
Beispiel #24
0
        private static bool AreEqual(BMPImage ResultImage, BMPImage TargetImage)
        {
            if (ResultImage.Height != TargetImage.Height || ResultImage.Width != TargetImage.Width)
            {
                return(false);
            }

            for (int i = 0; i < ResultImage.Height; i++)
            {
                for (int j = 0; j < ResultImage.Width; j++)
                {
                    for (int c = 0; c < ResultImage.Channels; c++)
                    {
                        if (ResultImage.Bytes[i][j][c] != ResultImage.Bytes[i][j][c])
                        {
                            return(false);
                        }
                    }
                }
            }

            return(true);
        }
Beispiel #25
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");
        }
    }
        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);
        }
Beispiel #27
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");
    }
        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();
        }
Beispiel #29
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);
            }
        }
Beispiel #30
0
        public static Texture2D LoadTexture(string name, bool useColorKey, bool alphaFromGrayscale = false, bool ignoreCachedTexture = false)
        {
            Texture2D tex = null;

            if (name == null)
            {
                return(null);
            }

            var modMapName = GameAPI.instance.fileSystem.GetPath(Path.Combine("maps", name));

            if (cachedTextures.ContainsKey(modMapName) && ignoreCachedTexture == false &&
                cachedTextures[modMapName] != null)
            {
                tex = cachedTextures[modMapName];
            }
            else
            {
                BMPImage image = null;

                bmp.useTransparencyKey = useColorKey;

                try
                {
                    image = bmp.LoadBMP(GameAPI.instance.fileSystem.GetStreamFromPath(Path.Combine("maps", name)));
                }
                catch
                {
                    Debug.LogWarningFormat("Image {0} couldn't be loaded!", name);
                }

                if (image != null)
                {
                    tex      = image.ToTexture2D();
                    tex.name = name;


                    if (alphaFromGrayscale)
                    {
                        var data = tex.GetPixels();

                        for (int i = 0; i < data.Length; i++)
                        {
                            var p = data[i];
                            data[i].a = p.grayscale;
                        }

                        tex.SetPixels(data, 0);
                        tex.Apply();
                    }
                }

                if (ignoreCachedTexture == false)
                {
                    if (cachedTextures.ContainsKey(modMapName))
                    {
                        cachedTextures.Remove(modMapName);
                    }

                    cachedTextures.Add(modMapName, tex);
                }

                bmp.useTransparencyKey = false;
            }

            return(tex);
        }