void OnGUI()
    {
        textureFormat = (TextureImporterFormat)EditorGUILayout.EnumPopup( "Texture Format", textureFormat );
        filterMode = (FilterMode)EditorGUILayout.EnumPopup( "Filter Mode", filterMode );
        maxTextureSize = EditorGUILayout.IntField( "Max Texture Size", maxTextureSize );
        textureType = (TextureImporterType)EditorGUILayout.EnumPopup( "Texture Type", textureType );

        GUILayout.Space( 25 );

        if( GUILayout.Button( "Reset to Defaults" ) )
        {
            EditorPrefs.DeleteKey( _filterModeKey );
            EditorPrefs.DeleteKey( _textureFormatKey );
            EditorPrefs.DeleteKey( _textureTypeKey );
            EditorPrefs.DeleteKey( _maxTextureSizeKey );

            textureFormat = getTextureImportFormat();
            filterMode = getFilterMode();
            maxTextureSize = getMaxTextureSize();
            textureType = getTextureImportType();
        }

        GUILayout.Space( 15 );

        if( GUILayout.Button( "Save" ) )
        {
            if( !Mathf.IsPowerOfTwo( maxTextureSize ) )
            {
                EditorUtility.DisplayDialog( "SpriteKit Max Texture Size Error", "Max texture size should be a power of 2", "OK" );
                return;
            }

            EditorPrefs.SetInt( _textureFormatKey, (int)textureFormat );
            EditorPrefs.SetInt( _filterModeKey, (int)filterMode );
            EditorPrefs.SetInt( _maxTextureSizeKey, maxTextureSize );
            EditorPrefs.SetInt( _textureTypeKey, (int)textureType );
            Close();
        }
    }
    private bool getPixelsFromTexture(ref Texture2D texture, out Color[] pixels)
    {
        //Make texture readable
        TextureImporter im = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter;

        if (!im)
        {
            pixels = new Color[1];
            return(false);
        }
        bool readable = im.isReadable;

#if UNITY_5_4
        TextureImporterFormat format = im.textureFormat;
#else
        TextureImporterCompression format = im.textureCompression;
#endif
        TextureImporterType type = im.textureType;
        bool isConvertedBump     = im.convertToNormalmap;

        if (!readable)
        {
            im.isReadable = true;
        }
#if UNITY_5_4
        if (type != TextureImporterType.Image)
        {
            im.textureType = TextureImporterType.Image;
        }
        im.textureFormat = TextureImporterFormat.ARGB32;
#else
        if (type != TextureImporterType.Default)
        {
            im.textureType = TextureImporterType.Default;
        }

        im.textureCompression = TextureImporterCompression.Uncompressed;
#endif
        im.SaveAndReimport();

        pixels = texture.GetPixels();

        if (!readable)
        {
            im.isReadable = false;
        }
#if UNITY_5_4
        if (type != TextureImporterType.Image)
        {
            im.textureType = type;
        }
#else
        if (type != TextureImporterType.Default)
        {
            im.textureType = type;
        }
#endif
        if (isConvertedBump)
        {
            im.convertToNormalmap = true;
        }

#if UNITY_5_4
        im.textureFormat = format;
#else
        im.textureCompression = format;
#endif

        im.SaveAndReimport();

        return(true);
    }
		private static extern void Internal_ApplyTextureType(TextureImporterSettings s, TextureImporterType type, bool applyAll);
Esempio n. 4
0
    void OnGUI()
    {
        int i, j;
        ResetManager();//Remakes game objects require to operate.
        e = Event.current; //Gets current event (mouse move, repaint, keyboard press, etc)

        if(renameId != -1 && (e.keyCode == KeyCode.Return || e.keyCode == KeyCode.KeypadEnter))
        {
            renameId = -1;
        }

        if(cmTileSets == null) //Check to make certain there is actually a tileset in the resources/tileset folder.
        {
            EditorGUILayout.LabelField("No tilesets found. Retrying.");
            OnEnable();
        }else{
            string[] names = new string[cmTileSets.Length]; //Gets the name of the tilesets into a useable list
            for(i = 0; i < cmTileSets.Length; i++)
            {
                try
                {
                    names[i] = cmTileSets[i].name;
                }
                catch(System.Exception ex)
                {
                    Debug.Log ("There was an error getting the names of the files. We'll try to reload the tilesets. If this continues to show, please close the script and try remimporting and check your images.");
                    Debug.Log ("Full system error: " + ex.Message);
                    OnEnable();
                }
            }

            //Mode variable to swith between major features.
            string[] mode = {"Tile Painter", "Help Video"};//, "Pad Tileset"};// Pad tileset not finished yet, removed to allow for earlier release. You can try it out if you want, but is has issues with larger images and places tiles in the wrong order.
            curMode = GUILayout.Toolbar(curMode, mode);

            if(curMode == 0)
            {
                //If in standard paint mode, display the proper gui elements for the user to use.
                EditorGUILayout.BeginHorizontal();
                int tmpInt = EditorGUILayout.Popup("Tileset", cmSelectedTileSet, names);
                if(GUILayout.Button("Reload"))
                {
                    OnEnable();
                }
                EditorGUILayout.EndHorizontal();

                string[] tools = {"Paint", "Erase", "Box Paint"};
                //curTool = EditorGUILayout.Popup("Tool", curTool, tools);

                EditorGUILayout.BeginHorizontal(GUILayout.Width(position.width));
                //Causes an error on editor load if the window is visible.
                //This seems to be a problem with how the gui is drawn the first
                //loop of the script. It only happens the once, and I can't figure
                //out why. I've been trying for literally weeks and still can't
                //find an answer. This is the only known bug, but it doesn't
                //stop the functionality of the script in any way, and only serves
                //as an annoying message on unity load or this script being
                //recompiled. Sorry for this bug. I am looking for a way to remove
                //this error, but I really am stummped as to why it's happening
                //and I just can not find an answer online.

                EditorGUILayout.LabelField("Tool",GUILayout.Width(50));
                GUILayout.FlexibleSpace();
                curTool = GUILayout.Toolbar(curTool, tools);
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Paint With Collider",GUILayout.Width(150));
                makeCollider = EditorGUILayout.Toggle(makeCollider);
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Highlight Current Layer",GUILayout.Width(150));
                highlightLayer = EditorGUILayout.Toggle(highlightLayer, GUILayout.Width(25));
                highlightColor = EditorGUILayout.ColorField(highlightColor);
                EditorGUILayout.EndHorizontal();

                if(tmpInt != cmSelectedTileSet) //Forces selection of first tileset if none are selected.
                {
                    LoadTileset(tmpInt);
                }

                cmSelectedTileSet = tmpInt; //sets the selected tileset value

                i = 0;
            int columnCount = Mathf.RoundToInt((position.width)/38)-2; //figures out how many columns are required for the tileset
                j = 0;
                int current = 0;

            tileScrollPosition = EditorGUILayout.BeginScrollView(tileScrollPosition,false,true,GUILayout.Width(position.width));
                //creates scrollbox area for tiles inside of the current tileset.

                GUILayout.BeginHorizontal(); //Initializing first row

                for(int q = 0; q < cmSprites.Length; q++)
                {
                    Sprite child = cmSprites[q];
                    //for every tile inside the currently selected tileset, add a tile
                    try
                    {
                    if(child.texture.name == names[cmSelectedTileSet] && child.name != names[cmSelectedTileSet])
                    {
                        //if it's the tiles inside the image, not the entire image

                        Rect newRect = new Rect(
                                            child.rect.x/child.texture.width,
                                            child.rect.y/child.texture.height,
                                            child.rect.width/child.texture.width,
                                            child.rect.height/child.texture.height
                                           );//gets the x and y position in pixels of where the image is. Used later for display.

                        if(GUILayout.Button("", GUILayout.Width(34), GUILayout.Height(34)))
                        {
                            //draw a clickable button
                            if (cmSelectedTile != null && !e.control)
                            {
                                //empty the selected tile list if control isn't held. Allows multiselect of tiles.
                                cmSelectedTile.Clear();
                                cmCurSprite.Clear();
                            }
                            cmSelectedTile.Add(current); //Adds clicked on tile to list of selected tiles.
                            cmCurSprite.Add(cmCurSprites[current]);
                        }

                        GUI.DrawTextureWithTexCoords(new Rect(5+(j*38), 4+(i*37), 32, 32), child.texture, newRect ,true); //draws tile base on pixels gotten at the beginning of the loop
                        if(cmSelectedTile != null && cmSelectedTile.Contains(current))
                        {
                            //if the current tile is inside of the list of selected tiles, draw a highlight indicator over the button.
                            if(cmSelectedColor == null)
                            {
                                cmSelectedColor = new Texture2D(1,1);
                                cmSelectedColor.alphaIsTransparency = true;
                                cmSelectedColor.filterMode = FilterMode.Point;
                                cmSelectedColor.SetPixel(0,0, new Color(.5f,.5f,1f,.5f));
                                cmSelectedColor.Apply();
                            }
                            GUI.DrawTexture(new Rect(5+(j*38), 4+(i*37), 32, 32), cmSelectedColor,ScaleMode.ScaleToFit,true);
                        }

                        if(j < columnCount)
                        {
                            j++;
                        }else{
                            // if we have enough columns to fill the scroll area, reset the column count and start a new line of buttons
                            j = 0;
                            i++;
                            GUILayout.EndHorizontal();
                            GUILayout.BeginHorizontal();
                        }
                        current++;
                    }
                    }catch(System.Exception ex){
                        if(ex.Message.StartsWith("IndexOutOfRangeException"))
                        {
                            Debug.Log("Tileset index was out of bounds, reloading and trying again.");
                            OnEnable();
                            return;
                        }
                    }
                }
                GUILayout.EndHorizontal(); //finish the drawing of tiles
                EditorGUILayout.EndScrollView();
                //Display all of the layers. May be put into a foldout for if there are too many layers. Haven't decided yet.
                GUILayout.Label("Layers:");

                if(GUILayout.Button("Add Layer"))
                {
                    AddLayer();
                }
                String[] minusPlus = {"-", "+", "x", "r"};

                ResetLayers();
                layers = ResortLayers(layers);//Sort the layers based on their sorting order instead of name
                int destroyFlag = -1;
                for(i = 0; i < layers.Count; i++)
                {
                    //iterates through layers and displays gui for options.
                    EditorGUILayout.BeginHorizontal();

                    RectOffset tmpPadding = GUI.skin.button.padding;
                    GUI.skin.button.padding = new RectOffset(3,3,3,3);

                    if(layers[i].gameObject.activeSelf)
                    {
                        if(GUILayout.Button(texVisible,GUILayout.Width(15), GUILayout.Height(15)))
                        {
                            layers[i].gameObject.SetActive(false);
                        }
                    }else{
                        if(GUILayout.Button(texHidden,GUILayout.Width(15), GUILayout.Height(15)))
                        {
                            layers[i].gameObject.SetActive(true);
                        }
                    }
                    GUI.skin.button.padding = tmpPadding;

                    if(i == selectedLayer)
                    {
                        //if selected layer, draw checked checkbox to show it's selected
                        if(i != renameId)
                        {
                            EditorGUILayout.ToggleLeft(layers[i].name + " - " + layers[i].GetComponent<SpriteRenderer>().sortingOrder,true);
                        }else{
                            layers[i].name = EditorGUILayout.TextField(layers[i].name);
                        }
                    }else{
                        //if not the selected layer, and is clicked, set it as the selected layer
                        if(i != renameId)
                        {
                            if(EditorGUILayout.ToggleLeft(layers[i].name + " - " + layers[i].GetComponent<SpriteRenderer>().sortingOrder,false))
                            {
                                selectedLayer = i;
                            }
                        }else{
                            layers[i].name = EditorGUILayout.TextField(layers[i].name);
                        }
                    }

                    //sets pressed value to -1 if nothing is pressed.
                    int pressed = GUILayout.Toolbar(-1, minusPlus);

                    switch(pressed)
                    {
                    case 0:
                        if(i > 0)
                        {
                            //moves layer and all tiles in it to move away from the camera, and moves the layer above it toward the camera.
                            layers[i-1].GetComponent<SpriteRenderer>().sortingOrder += 1;
                            int upLayer = layers[i-1].GetComponent<SpriteRenderer>().sortingOrder;

                            foreach(SpriteRenderer sr in layers[i-1].GetComponentsInChildren<SpriteRenderer>())
                            {
                                sr.sortingOrder = upLayer;
                            }

                            //layers[i].GetComponent<SpriteRenderer>().sortingOrder -= 1;
                            int downLayer = layers[i].GetComponent<SpriteRenderer>().sortingOrder -= 1;

                            foreach(SpriteRenderer sr in layers[i].GetComponentsInChildren<SpriteRenderer>())
                            {
                                sr.sortingOrder = downLayer;
                            }
                            selectedLayer = i-1;
                        }
                        layers = ResortLayers(layers);
                        break;
                    case 1:
                        if(i < layers.Count-1)
                        {
                            //moves layer and all tiles in it to move toward the camera, and moves the layer above it away from the camera.
                            layers[i+1].GetComponent<SpriteRenderer>().sortingOrder -= 1;
                            int upLayer = layers[i+1].GetComponent<SpriteRenderer>().sortingOrder;

                            foreach(SpriteRenderer sr in layers[i+1].GetComponentsInChildren<SpriteRenderer>())
                            {
                                sr.sortingOrder = upLayer;
                            }

                            //layers[i].GetComponent<SpriteRenderer>().sortingOrder += 1;
                            int downLayer = layers[i].GetComponent<SpriteRenderer>().sortingOrder += 1;

                            foreach(SpriteRenderer sr in layers[i].GetComponentsInChildren<SpriteRenderer>())
                            {
                                sr.sortingOrder = downLayer;
                            }
                            selectedLayer = i+1;
                        }
                        layers = ResortLayers(layers);
                        break;
                    case 2:
                        //deletes the layer game object, which also deletes all the children
                        destroyFlag = i;
                        break;
                    case 3:
                        if(renameId == -1)
                        {
                            renameId = i;
                        }else{
                            renameId = -1;
                        }
                        break;
                    default:
                        //do nothing if a button wasn't pressed (required or I get errors T_T)
                        break;
                    }
                    EditorGUILayout.EndHorizontal(); //end the layer gui
                }
                if(selectedLayer <= layers.Count-1 && selectedLayer > 0)
                {
                    //double check to make certain a layer of some sort is selected and is in valid range
                    curLayer = layers[selectedLayer].gameObject;
                }

                if(selectedLayer <= layers.Count-1 && layers[selectedLayer] != null)
                {
                    ResetHighlight(layers[selectedLayer].gameObject, highlightLayer);
                    curLayer = layers[selectedLayer].gameObject;
                }else{
                    if(layers.Count-1 > 0 && layers[selectedLayer] != null)
                    {
                        curLayer = layers[selectedLayer].gameObject;
                    }else{

                    }
                }
                if(destroyFlag != -1)
                {
                    DestroyImmediate(layers[destroyFlag].gameObject);
                    return; //Breaks method to not have errors down the line. Forces reload of tilesets to keep inside the bounds of the array.
                }
                destroyFlag = -1;
            }else if(curMode == 1){
                curMode = 0;
                Application.OpenURL("https://www.youtube.com/watch?v=mxy9HdNM-is");
                return;
            }else if(curMode == 2){
                int tmpInt = EditorGUILayout.Popup("Tileset", cmSelectedTileSet, names);
                if(tmpInt != cmSelectedTileSet) //Forces selection of first tileset if none are selected.
                {
                    LoadTileset(tmpInt);
                }

                cmSelectedTileSet = tmpInt; //sets the selected tileset value

                GUILayout.BeginHorizontal();
                GUILayout.Label("Grid Size X", GUILayout.Width(200));
                gridSizeX = EditorGUILayout.IntField(gridSizeX);
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Grid Size Y", GUILayout.Width(200));
                gridSizeY = EditorGUILayout.IntField(gridSizeY);
                GUILayout.EndHorizontal();

                /*GUILayout.BeginHorizontal();
                GUILayout.Label("Pad Size X", GUILayout.Width(200));
                padSizeX = EditorGUILayout.IntField(padSizeX);
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Pad Size Y", GUILayout.Width(200));
                padSizeY = EditorGUILayout.IntField(padSizeY);
                GUILayout.EndHorizontal();*/

                if(GUILayout.Button("Generate New Texture"))
                {
                    List<Rect> listOfNewSlices = new List<Rect>();
                    Texture2D curTileSet = Resources.Load<Texture2D>("Tilesets/" + cmTileSets[cmSelectedTileSet].name);//cmTileSets[cmSelectedTileSet];
                    int newWidth = (int)(curTileSet.width+(padSizeX*2*(curTileSet.width/gridSizeX)));
                    int newHeight = (int)(curTileSet.height+(((curTileSet.height/gridSizeY))*(padSizeY*2)));

                    Texture2D newTileSet = new Texture2D(newWidth,newHeight);

                    Debug.Log("Generated new tile image with a size of " + newTileSet.width + ", " + newTileSet.height);
        //					Debug.Log("Tilecount: " + (int)(curTileSet.width/gridSizeX) + ", " + (int)(curTileSet.height/gridSizeY));
                    for(j = 0; j < (int)(curTileSet.width/gridSizeX); j++)
                    {
                        for(i = 0 ; i < (int)(curTileSet.height/gridSizeY); i++)
                        {
                            //Copies old image tiles to new image with padding.
                            try{
                            newTileSet.SetPixels(
                                ((j*gridSizeX)+(j*padSizeX*2))+padSizeX,
                                ((i*gridSizeY)+(i*padSizeY*2))+padSizeY,
                                gridSizeX,
                                gridSizeY,
                                curTileSet.GetPixels(
                                    j*gridSizeX,
                                    i*gridSizeY,
                                    gridSizeX,
                                    gridSizeY));
                                Debug.Log(i*32);

                            //LeftSide
                            /*newTileSet.SetPixels(
                                (j*gridSizeX)+(j*padSizeX*2)+padSizeX-1,
                                (i*gridSizeY)+(i*padSizeY*2),
                                1,
                                gridSizeY,
                                curTileSet.GetPixels(
                                j*gridSizeX,
                                i*gridSizeY,
                                1,
                                gridSizeY));

                            //RightSide
                            newTileSet.SetPixels(
                                (j*gridSizeX)+(j*padSizeX*2)+padSizeX + gridSizeX,
                                (i*gridSizeY)+(i*padSizeY*2),
                                1,
                                gridSizeY,
                                curTileSet.GetPixels(
                                (j*gridSizeX)+gridSizeX-1,
                                i*gridSizeY,
                                1,
                                gridSizeY));

                            //BottomSide
                            newTileSet.SetPixels(
                                (j*gridSizeX)+(j*padSizeX*2)+padSizeX,
                                (i*gridSizeY)+(i*padSizeY*2)-1,
                                gridSizeX,
                                1,
                                curTileSet.GetPixels(
                                j*gridSizeX,
                                i*gridSizeY,
                                gridSizeX,
                                1));

                            //TopSide
                            newTileSet.SetPixels(
                                (j*gridSizeX)+(j*padSizeX*2)+padSizeX,
                                (i*gridSizeY)+(i*padSizeY*2)+gridSizeY,
                                gridSizeX,
                                1,
                                curTileSet.GetPixels(
                                (j*gridSizeX),
                                (i*gridSizeY)+gridSizeY-1,
                                gridSizeX,
                                1));*/
                                listOfNewSlices.Add(new Rect(
                                                            ((i*gridSizeY)+(i*padSizeY*2))+padSizeY,
                                                            ((j*gridSizeX)+(j*padSizeX*2))+padSizeX,
                                                            gridSizeX,
                                                            gridSizeY));

                            //Debug.Log("Drawing tile " + i + ", " + j + " at " + ((i*padSizeX)+(i*gridSizeX)) + ", " + ((j*padSizeY)+(j*gridSizeY)) + " from " + i*gridSizeX + ", " + j*gridSizeY);
                            }catch(System.Exception ex)
                            {
                                Debug.Log("ERROR: " + ex.Message);
                                if(0==0)
                                {

                                }
                            }
                        }
                    }
                    newTileSet.Apply();
                    //listOfNewSlices.Add(new Rect(0,newTileSet.height-gridSizeX,100,100));
                    Debug.Log("Image generation completed, generating slices.");

                    /*FileStream fs = new FileStream(Application.dataPath + "/Resources/Tilesets/" + curTileSet.name + "_padded.png", FileMode.Append);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(newTileSet.EncodeToPNG());
                    bw.Close();
                    fs.Close();*/

                    //AssetDatabase.CreateAsset(newTileSet.EncodeToPNG(), "Assets/Resources/Tilesets/" + curTileSet.name + "_padded.png");
                    bool isWriting = true;
                    while(isWriting)
                    {
                        File.WriteAllBytes(Application.dataPath + "/Resources/Tilesets/" + curTileSet.name + "_padded.png", newTileSet.EncodeToPNG());
                        isWriting = false;
                    }
                    AssetDatabase.Refresh();
                    TextureImporter ti = new TextureImporter();
                    ti = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(Resources.Load<Texture>("Tilesets/" + curTileSet.name + "_padded")));
                    TextureImporterType type = new TextureImporterType();
                    type = TextureImporterType.Sprite;
                    ti.textureType = type;
                    ti.spritePixelsPerUnit = gridSizeX;
                    ti.spriteImportMode = SpriteImportMode.Multiple;
                    ti.filterMode = FilterMode.Point;

                    List<SpriteMetaData> spriteData = new List<SpriteMetaData>();//[listOfNewSlices.Count+1];
                    //listOfNewSlices.Reverse();

                    for(i = 0; i < listOfNewSlices.Count; i++)
                    {
                        float alpha = 0;
                        foreach(Color pixel in newTileSet.GetPixels((int)listOfNewSlices[i].x, (int)listOfNewSlices[i].y, (int)listOfNewSlices[i].width, (int)listOfNewSlices[i].height))
                        {
                            alpha += pixel.a;
                        }
                        if(alpha > 0)
                        {
                            listOfNewSlices[i] = new Rect(listOfNewSlices[i].x, listOfNewSlices[i].y, listOfNewSlices[i].width, listOfNewSlices[i].height);
                            SpriteMetaData tmpSpriteData = new SpriteMetaData();
                            tmpSpriteData.rect = listOfNewSlices[i];
                            tmpSpriteData.name = curTileSet.name + "_padded_" + i;// ti.spritesheet.GetLength(0);
                            tmpSpriteData.alignment = 0;
                            tmpSpriteData.pivot = new Vector2(gridSizeX/2,gridSizeY/2);
                            spriteData.Add(tmpSpriteData);
                        }else{
                            listOfNewSlices.RemoveAt(i);
                            //spriteData.RemoveAt(i);
                            i--;
                        }
                    }

                    ti.spritesheet = spriteData.ToArray();

                    Debug.Log("Finished generating new padded tileset. Pausing thread to update file.");
                    System.Threading.Thread.Sleep(4000);//Added to allow for saving and reimporting image in unity. Required to run without error.
                    OnEnable();
                }
                if(GUILayout.Button("Regenerate to Original File"))
                {

                }
            }
        }
    }
    /// <summary>
    /// 设置图片格式
    /// </summary>
    /// <param name="path"></param>
    /// <param name="mTextureImporterType"></param>
    /// <param name="mTextureImporterFormat"></param>
    /// <param name="readEnable"></param>
    static void TextureSetting(string path, TextureImporterType mTextureImporterType = TextureImporterType.Default, TextureImporterFormat mTextureImporterFormat = TextureImporterFormat.RGBA32, bool readEnable = false)
    {
        TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
        if (textureImporter == null) return;
        textureImporter.textureType = mTextureImporterType;
        if (textureImporter.textureType == TextureImporterType.Default)
        {
            textureImporter.spriteImportMode = SpriteImportMode.None;
            textureImporter.mipmapEnabled = false;
            textureImporter.isReadable = readEnable;
            textureImporter.alphaIsTransparency = false;
        }
        else if (textureImporter.textureType == TextureImporterType.Sprite)
        {
            textureImporter.mipmapEnabled = false;
        }
        textureImporter.SetPlatformTextureSettings("Android", 2048, mTextureImporterFormat);
        textureImporter.SetPlatformTextureSettings("Windows", 2048, mTextureImporterFormat);
        textureImporter.SetPlatformTextureSettings("iPhone", 2048, TextureImporterFormat.PVRTC_RGB4);
        textureImporter.SetAllowsAlphaSplitting(false);

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
Esempio n. 6
0
 private static extern void Internal_ApplyTextureType([Out][NotNull] TextureImporterSettings self, TextureImporterType type);
Esempio n. 7
0
        void SaveTexture(TextureImporterType type)
        {
            if (sprite != null)
            {
                SaveSpriteTexture();
                return;
            }
            if (texture != null)
            {
                if (texture.width != canvasTexture.width || texture.height != canvasTexture.width)
                {
                    texture.Resize(canvasTexture.width, canvasTexture.height);
                }
                // convert to linear
                if (texture.IsLinear())
                {
                    Color[] linearColors = new Color[colors.Length];
                    for (int k = 0; k < colors.Length; k++)
                    {
                        linearColors[k] = colors[k].linear;
                    }
                    texture.SetPixels(linearColors);
                }
                else
                {
                    texture.SetPixels(colors);
                }
                texture.Apply();
                UpdateTextureContentsOnDisk(texture);
                return;
            }
            string basePath = GetExportsPath("Textures");
            string path     = basePath + "/texture.png";
            int    counter  = 2;

            while (File.Exists(path))
            {
                path = basePath + "/texture" + counter + ".png";
                counter++;
            }
            byte[] contents = canvasTexture.EncodeToPNG();
            File.WriteAllBytes(path, contents);
            AssetDatabase.ImportAsset(path);
            TextureImporter imp = (TextureImporter)AssetImporter.GetAtPath(path) as TextureImporter;

            imp.textureType         = type;
            imp.filterMode          = FilterMode.Point;
            imp.alphaIsTransparency = true;
            imp.isReadable          = true;
            imp.textureCompression  = TextureImporterCompression.Uncompressed;
            imp.SaveAndReimport();

            if (type == TextureImporterType.Default)
            {
                texture = AssetDatabase.LoadAssetAtPath <Texture2D>(path) as Texture2D;
                EditorGUIUtility.PingObject(texture);
                sprite = null;
            }
            else
            {
                sprite = AssetDatabase.LoadAssetAtPath <Sprite>(path) as Sprite;
                EditorGUIUtility.PingObject(sprite);
                texture = null;
            }
        }
Esempio n. 8
0
        public virtual void ShowImportSettings(Editor baseEditor, TextureImportPlatformSettings platformSettings)
        {
            TextureImporterInspector editor = baseEditor as TextureImporterInspector;

            // Max texture size
            EditorGUI.BeginChangeCheck();
            EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.maxTextureSizeIsDifferent;
            int maxTextureSize = EditorGUILayout.IntPopup(maxSize.text, platformSettings.maxTextureSize, kMaxTextureSizeStrings, kMaxTextureSizeValues);

            EditorGUI.showMixedValue = false;
            if (EditorGUI.EndChangeCheck())
            {
                platformSettings.SetMaxTextureSizeForAll(maxTextureSize);
            }

            // Resize Algorithm
            EditorGUI.BeginChangeCheck();
            EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.resizeAlgorithmIsDifferent;
            int resizeAlgorithmVal = EditorGUILayout.IntPopup(resizeAlgorithm.text, (int)platformSettings.resizeAlgorithm, kResizeAlgorithmStrings, kResizeAlgorithmValues);

            EditorGUI.showMixedValue = false;
            if (EditorGUI.EndChangeCheck())
            {
                platformSettings.SetResizeAlgorithmForAll((TextureResizeAlgorithm)resizeAlgorithmVal);
            }

            // Texture Compression
            using (new EditorGUI.DisabledScope(platformSettings.overridden && !platformSettings.isDefault))
            {
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.textureCompressionIsDifferent || (platformSettings.overridden && !platformSettings.isDefault);
                TextureImporterCompression textureCompression = (TextureImporterCompression)EditorGUILayout.IntPopup(kTextureCompression, (int)platformSettings.textureCompression, kTextureCompressionOptions, kTextureCompressionValues);
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    platformSettings.SetTextureCompressionForAll(textureCompression);
                }
            }

            // Texture format
            int[]    formatValuesForAll        = null;
            string[] formatStringsForAll       = null;
            bool     formatOptionsAreDifferent = false;

            int formatForAll = 0;


            for (int i = 0; i < editor.targets.Length; i++)
            {
                TextureImporter         imp                = editor.targets[i] as TextureImporter;
                TextureImporterSettings settings           = platformSettings.GetSettings(imp);
                TextureImporterType     textureTypeForThis = editor.textureTypeHasMultipleDifferentValues ? settings.textureType : editor.textureType;
                int format = (int)platformSettings.format;

                int[]    formatValues  = null;
                string[] formatStrings = null;

                if (platformSettings.isDefault)
                {
                    format        = (int)TextureImporterFormat.Automatic;
                    formatValues  = new int[] { (int)TextureImporterFormat.Automatic };
                    formatStrings = new string[] { "Auto" };
                }
                else
                {
                    // If not overriden, show what the auto format is going to be
                    if (!platformSettings.overridden)
                    {
                        format = (int)TextureImporter.FormatFromTextureParameters(settings,
                                                                                  platformSettings.platformTextureSettings,
                                                                                  editor.assetTarget && imp.DoesSourceTextureHaveAlpha(),
                                                                                  editor.assetTarget && imp.IsSourceTextureHDR(),
                                                                                  platformSettings.m_Target);

                        formatValues  = new int[] { format };
                        formatStrings = new string[] { TextureUtil.GetTextureFormatString((TextureFormat)format) };
                    }
                    // else show the format choice filtered by platform.
                    else
                    {
                        // Single channel format is the same for all platform at the moment
                        if (textureTypeForThis == TextureImporterType.Cookie || textureTypeForThis == TextureImporterType.SingleChannel)
                        {
                            formatValues  = TextureImportPlatformSettings.kTextureFormatsValueSingleChannel;
                            formatStrings = TextureImporterInspector.s_TextureFormatStringsSingleChannel;
                        }
                        else
                        {
                            // on gles targets we use rgb normal maps so no need to split formats
                            if (TextureImporterInspector.IsGLESMobileTargetPlatform(platformSettings.m_Target))
                            {
                                if (platformSettings.m_Target == BuildTarget.iOS || platformSettings.m_Target == BuildTarget.tvOS)
                                {
                                    formatValues  = TextureImportPlatformSettings.kTextureFormatsValueApplePVR;
                                    formatStrings = TextureImporterInspector.s_TextureFormatStringsApplePVR;
                                }
                                else
                                {
                                    formatValues  = TextureImportPlatformSettings.kTextureFormatsValueAndroid;
                                    formatStrings = TextureImporterInspector.s_TextureFormatStringsAndroid;
                                }
                            }
                            else if (textureTypeForThis == TextureImporterType.NormalMap)
                            {
                                formatValues  = TextureImportPlatformSettings.kNormalFormatsValueDefault;
                                formatStrings = TextureImporterInspector.s_NormalFormatStringsDefault;
                            }
                            else
                            {
                                if (platformSettings.m_Target == BuildTarget.WebGL)
                                {
                                    formatValues  = TextureImportPlatformSettings.kTextureFormatsValueWebGL;
                                    formatStrings = TextureImporterInspector.s_TextureFormatStringsWebGL;
                                }
                                else if (platformSettings.m_Target == BuildTarget.PSP2)
                                {
                                    formatValues  = TextureImportPlatformSettings.kTextureFormatsValuePSP2;
                                    formatStrings = TextureImporterInspector.s_TextureFormatStringsPSP2;
                                }
                                else if (platformSettings.m_Target == BuildTarget.Switch)
                                {
                                    formatValues  = TextureImportPlatformSettings.kTextureFormatsValueSwitch;
                                    formatStrings = TextureImporterInspector.s_TextureFormatStringsSwitch;
                                }
                                else
                                {
                                    formatValues  = TextureImportPlatformSettings.kTextureFormatsValueDefault;
                                    formatStrings = TextureImporterInspector.s_TextureFormatStringsDefault;
                                }
                            }
                        }
                    }
                }

                // Check if values are the same
                if (i == 0)
                {
                    formatValuesForAll  = formatValues;
                    formatStringsForAll = formatStrings;
                    formatForAll        = format;
                }
                else
                {
                    if (!formatValues.SequenceEqual(formatValuesForAll) || !formatStrings.SequenceEqual(formatStringsForAll))
                    {
                        formatOptionsAreDifferent = true;
                        break;
                    }
                }
            }

            using (new EditorGUI.DisabledScope(formatOptionsAreDifferent || formatStringsForAll.Length == 1))
            {
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = formatOptionsAreDifferent || platformSettings.textureFormatIsDifferent;
                formatForAll             = EditorGUILayout.IntPopup(TextureImporterInspector.s_Styles.textureFormat, formatForAll, EditorGUIUtility.TempContent(formatStringsForAll), formatValuesForAll);
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    platformSettings.SetTextureFormatForAll((TextureImporterFormat)formatForAll);
                }

                // In case the platform is overriden, the chosen format can become invalid when changing texture type (example: Switching from "Default" overridden with RGBAHalf to "Single Channel" where only Alpha8 is available)
                if (Array.IndexOf(formatValuesForAll, formatForAll) == -1)
                {
                    platformSettings.SetTextureFormatForAll((TextureImporterFormat)formatValuesForAll[0]);
                }
            }

            if (platformSettings.isDefault && platformSettings.textureCompression != TextureImporterCompression.Uncompressed)
            {
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.crunchedCompressionIsDifferent;
                bool crunchedCompression = EditorGUILayout.Toggle(TextureImporterInspector.s_Styles.crunchedCompression, platformSettings.crunchedCompression);
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    platformSettings.SetCrunchedCompressionForAll(crunchedCompression);
                }
            }

            // compression quality
            bool isCrunchedFormat = false ||
                                    (TextureImporterFormat)formatForAll == TextureImporterFormat.DXT1Crunched ||
                                    (TextureImporterFormat)formatForAll == TextureImporterFormat.DXT5Crunched ||
                                    (TextureImporterFormat)formatForAll == TextureImporterFormat.ETC_RGB4Crunched ||
                                    (TextureImporterFormat)formatForAll == TextureImporterFormat.ETC2_RGBA8Crunched
            ;

            if (
                (platformSettings.isDefault && platformSettings.textureCompression != TextureImporterCompression.Uncompressed && platformSettings.crunchedCompression) ||
                (!platformSettings.isDefault && isCrunchedFormat) ||
                (!platformSettings.textureFormatIsDifferent && ArrayUtility.Contains <TextureImporterFormat>(TextureImporterInspector.kFormatsWithCompressionSettings, (TextureImporterFormat)formatForAll)))
            {
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.compressionQualityIsDifferent;
                int compressionQuality = EditCompressionQuality(platformSettings.m_Target, platformSettings.compressionQuality, isCrunchedFormat);
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    platformSettings.SetCompressionQualityForAll(compressionQuality);
                    //SyncPlatformSettings ();
                }
            }

            // show the ETC1 split option only for sprites on platforms supporting ETC.
            bool isETCPlatform       = TextureImporter.IsETC1SupportedByBuildTarget(BuildPipeline.GetBuildTargetByName(platformSettings.name));
            bool isDealingWithSprite = (editor.spriteImportMode != SpriteImportMode.None);
            bool isETCFormatSelected = TextureImporter.IsTextureFormatETC1Compression((TextureFormat)formatForAll);

            if (isETCPlatform && isDealingWithSprite && isETCFormatSelected)
            {
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.allowsAlphaSplitIsDifferent;
                bool allowsAlphaSplit = GUILayout.Toggle(platformSettings.allowsAlphaSplitting, TextureImporterInspector.s_Styles.etc1Compression);
                if (EditorGUI.EndChangeCheck())
                {
                    platformSettings.SetAllowsAlphaSplitForAll(allowsAlphaSplit);
                }
            }
        }
Esempio n. 9
0
        private void OnGUI()
        {
            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField("Path:");
                currenTextureImportData.AssetPath = EditorGUILayout.TextField(currenTextureImportData.AssetPath);
                EditorGUILayout.LabelField("NameFilter:", GUILayout.MinWidth(200));
                currenTextureImportData.FileFilter = EditorGUILayout.TextField(currenTextureImportData.FileFilter);
                if (GUILayout.Button("Save", GUILayout.MinWidth(100)))
                {
                    SetSelectIndexDataInfo();
                }
                if (GUILayout.Button("Delete", GUILayout.MinWidth(100)))
                {
                    TextureImportManager.ImportRule.Delete(currentSelectIndex);
                }
                if (GUILayout.Button("New Data", GUILayout.MinWidth(100)))
                {
                    if (string.IsNullOrEmpty(currenTextureImportData.AssetPath) ||
                        string.IsNullOrEmpty(currenTextureImportData.FileFilter))
                    {
                        return;
                    }
                    TextureImportManager.TextureImportRule.TextureImportData data = GetNextTextureImportData();
                    data.AssetPath  = currenTextureImportData.AssetPath;
                    data.FileFilter = currenTextureImportData.FileFilter;
                    TextureImportManager.ImportRule.Add(data);
                    currenTextureImportData = data;
                    currentSelectIndex      = data.Index;
                    GetSelectIndexDataInfo(data);
                }
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space();
            EditorGUILayout.BeginHorizontal();
            {
                textureType = (TextureImporterType)EditorGUILayout.EnumPopup("Texture类型", textureType);
                SetTextureTypeInfo();
                alphaSourceType = (TextureImporterAlphaSource)EditorGUILayout.EnumPopup("AlphaSource", alphaSourceType);
                SetAlphaSourceInfo();
                androidFormatType        = (TextureImporterFormat)EditorGUILayout.EnumPopup("AndroidFormat", androidFormatType);
                androidFormatCompression = (TextureImporterCompression)EditorGUILayout.EnumPopup("AndroidCompression", androidFormatCompression);
                SetAndroidFormatInfo();
                iPhoneFormatType        = (TextureImporterFormat)EditorGUILayout.EnumPopup("iPhoneFormat", iPhoneFormatType);
                iPhoneFormatCompression = (TextureImporterCompression)EditorGUILayout.EnumPopup("iPhoneCompression", iPhoneFormatCompression);
                SetiPhoneFormatInfo();
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space();
            EditorGUILayout.BeginHorizontal();
            {
                currenTextureImportData.IsMinMap =
                    EditorGUILayout.ToggleLeft("是否开启Mipmap", currenTextureImportData.IsMinMap);
                currenTextureImportData.IsReadWriteEnable =
                    EditorGUILayout.ToggleLeft("是否开启ReadWrite", currenTextureImportData.IsReadWriteEnable);
                currenTextureImportData.Index          = EditorGUILayout.IntField("Rule Index", currenTextureImportData.Index);
                currenTextureImportData.MaxTextureSize =
                    EditorGUILayout.IntField("纹理MaxSize", currenTextureImportData.MaxTextureSize);
            }
            EditorGUILayout.EndHorizontal();
            GUILayout.Space(25);
            int height = (TextureImportManager.ImportRule.TextureImportDatas.Count + 1) * 20;

            TextureImportManager.TextureImportRule.TextureImportData rule =
                TextureImportManager.ImportRule.GetRule(currentSelectIndex);
            string[] guids = null;
            if (null != rule)
            {
                guids   = AssetDatabase.FindAssets("t:Texture", new string[] { rule.AssetPath });
                height += (guids.Length + 1) * 20;
            }

            scrollPosition = GUI.BeginScrollView(new Rect(0, 30, position.width, position.height - 30), scrollPosition,
                                                 new Rect(0, 0, 1250, height));
            EditorGUILayout.BeginHorizontal();
            {
                GUILayout.Label("AssetPath", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("FileFilter", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("Index", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("AlphaSource", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("TextureType", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("Mipmap", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("R/W", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("MaxSize", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("Android", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("AndroidCompression", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("iPhone", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("iPhoneCompression", EditorStyles.label, GUILayout.MinWidth(100));
                GUILayout.Label("Apply", EditorStyles.label, GUILayout.MinWidth(100));
            }
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.Space();
            GUIStyle style = GUI.skin.textField;

            for (int i = 0; i < TextureImportManager.ImportRule.TextureImportDatas.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();
                TextureImportManager.TextureImportRule.TextureImportData data =
                    TextureImportManager.ImportRule.TextureImportDatas[i];

                GUI.color = data.Index == currentSelectIndex ? Color.green : new Color(0.8f, 0.8f, 0.8f, 1);

                if (GUILayout.Button(data.AssetPath, style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button(data.FileFilter, style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button(data.Index.ToString(), style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button(data.AlphaSource.ToString(), style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button(data.TextureImporterType.ToString(), style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button(data.IsMinMap.ToString(), style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button(data.IsReadWriteEnable.ToString(), style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button(data.MaxTextureSize.ToString(), style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button(data.AndroidImporterFormat.ToString(), style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button(data.AndroidImporterCompression.ToString(), style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button(data.IphoneImporterFormat.ToString(), style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button(data.IphoneImporterCompression.ToString(), style, GUILayout.MinWidth(100)))
                {
                    currentSelectIndex = data.Index;
                    GetSelectIndexDataInfo(data);
                }
                if (GUILayout.Button("Apply", GUILayout.MinWidth(100)))
                {
                    TextureImportManager.ReImportTextures(data);
                }
                EditorGUILayout.EndHorizontal();
            }
            if (null != guids)
            {
                int count = 0;
                for (int i = 0; i < guids.Length; i++)
                {
                    string path = AssetDatabase.GUIDToAssetPath(guids[i]);
                    if (string.IsNullOrEmpty(path))
                    {
                        continue;
                    }
                    string dir = path.Remove(path.LastIndexOf('/'));
                    if (!dir.Equals(currenTextureImportData.AssetPath))
                    {
                        continue;
                    }
                    string fileName = path.Substring(path.LastIndexOf('/') + 1);
                    if (!currenTextureImportData.IsMatch(fileName))
                    {
                        continue;
                    }
                    TextureImporter ai = AssetImporter.GetAtPath(path) as TextureImporter;
                    if (null != ai)
                    {
                        EditorGUILayout.BeginHorizontal();
                        {
                            GUILayout.Label(fileName, EditorStyles.label, GUILayout.MinWidth(120));
                            GUILayout.Label("", EditorStyles.label, GUILayout.MinWidth(100));
                            GUILayout.Label((++count).ToString(), EditorStyles.label, GUILayout.MinWidth(100));
                            GUILayout.Label(ai.alphaSource.ToString(), EditorStyles.label, GUILayout.MinWidth(120));
                            GUILayout.Label(ai.textureType.ToString(), EditorStyles.label, GUILayout.MinWidth(120));
                            GUILayout.Label(ai.mipmapEnabled.ToString(), EditorStyles.label, GUILayout.MinWidth(100));
                            GUILayout.Label(ai.isReadable.ToString(), EditorStyles.label, GUILayout.MinWidth(100));
                            TextureImporterPlatformSettings settingAndroid = ai.GetPlatformTextureSettings("Android");
                            TextureImporterPlatformSettings settingiPhone  = ai.GetPlatformTextureSettings("iPhone");
                            GUILayout.Label(settingAndroid.maxTextureSize.ToString(), EditorStyles.label,
                                            GUILayout.MinWidth(100));
                            GUILayout.Label(settingAndroid.format.ToString(), EditorStyles.label,
                                            GUILayout.MinWidth(100));
                            GUILayout.Label(settingAndroid.textureCompression.ToString(), EditorStyles.label,
                                            GUILayout.MinWidth(100));
                            GUILayout.Label(settingiPhone.format.ToString(), EditorStyles.label,
                                            GUILayout.MinWidth(100));
                            GUILayout.Label(settingiPhone.textureCompression.ToString(), EditorStyles.label,
                                            GUILayout.MinWidth(100));
                            GUILayout.Label("", EditorStyles.label, GUILayout.MinWidth(100));
                        }
                        EditorGUILayout.EndHorizontal();
                    }
                }
            }
            GUI.EndScrollView();
            if (EditorUtility.IsDirty(TextureImportManager.ImportRule))
            {
                EditorUtility.SetDirty(TextureImportManager.ImportRule);
                AssetDatabase.Refresh();
            }
        }
        static void SelectedChangeTextureTypeSettings(TextureImporterType newType)
        {

            var textures = GetSelectedTextures();
            Selection.objects = new Object[0];
            foreach (var o in textures)
            {
                var texture = (Texture2D) o;
                var path = AssetDatabase.GetAssetPath(texture);
                //Debug.Log("path: " + path);
                var textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
                Debug.Assert(textureImporter != null, "textureImporter != null");
                textureImporter.textureType = newType;
                AssetDatabase.ImportAsset(path);
            }
        }
Esempio n. 11
0
    private void DisplaySingle()
    {
        // make sure the list is not empty
        // if so add null sprite
        if (sprites.Count == 0)
        {
            sprites.Add(null);
        }


        EditorGUILayout.BeginHorizontal();

        // begin left column for variables and properties
        EditorGUILayout.BeginVertical(GUILayout.Width(position.width / 2));
        // start horizontal row
        EditorGUILayout.BeginHorizontal();
        // label for sprite
        EditorGUILayout.LabelField("Sprite", GUILayout.Width(130));
        // display the sprite object for the 0 index
        sprites[0] = (Texture2D)EditorGUILayout.ObjectField(sprites[0], typeof(Texture2D), true);
        if (sprites[0])
        {
            if (GUILayout.Button("Focus", GUILayout.Width(60)))
            {
                Selection.activeObject = sprites[0];
            }
        }
        // end horizontal row
        EditorGUILayout.EndHorizontal();

        if (!sprites[0])
        {
            return;
        }

        TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(AssetDatabase.GetAssetPath(sprites[0]));

        // start horizontal row
        EditorGUILayout.BeginHorizontal();
        // label for sprite
        EditorGUILayout.LabelField("Show Checkers", GUILayout.Width(130));
        // toggle for power of 4
        showBackground = EditorGUILayout.Toggle(showBackground, GUILayout.Width(40));
        // end horizontal row
        EditorGUILayout.EndHorizontal();

        if (sprites[0].width % 4 == 0 && sprites[0].height % 4 == 0)
        {
            alreadyPower4 = true;
        }
        else
        {
            alreadyPower4 = false;
        }

        if (!alreadyPower4)
        {
            // start horizontal row
            EditorGUILayout.BeginHorizontal();
            // label for sprite
            EditorGUILayout.LabelField("Power of 4", GUILayout.Width(130));
            // toggle for power of 4
            powerOf4 = EditorGUILayout.Toggle(powerOf4, GUILayout.Width(40));
            if (powerOf4)
            {
                EditorGUILayout.LabelField("Adds white space to make both width and height divisible by 4");
                if (GUILayout.Button("Apply"))
                {
                    MakePowerOf4(sprites[0]);
                }
            }
            // end horizontal row
            EditorGUILayout.EndHorizontal();
        }

        EditorGUILayout.Space();

        EditorGUILayout.LabelField("Sprite Mode Settings", EditorStyles.boldLabel);

        // start horizontal row
        EditorGUILayout.BeginHorizontal();
        // label for sprite mode
        EditorGUILayout.LabelField("Sprite Mode", GUILayout.Width(130));
        // enum popup for sprite mode
        mode = (SpriteImportMode)EditorGUILayout.EnumPopup(mode);
        // end horizontal row
        EditorGUILayout.EndHorizontal();

        // start horizontal row
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("", GUILayout.Width(130));
        if (mode != importer.spriteImportMode)
        {
            if (GUILayout.Button("Convert"))
            {
                importer.spriteImportMode = mode;
                importer.SaveAndReimport();
            }
        }
        else
        {
            if (mode == SpriteImportMode.Multiple)
            {
                /*
                 * if (GUILayout.Button("Launch Sprite Editor"))
                 * {
                 *  Selection.activeObject = sprites[0];
                 *  EditorWindow.GetWindow(typeof(EditorWindow).Assembly.GetTypes().Where(t => t.Name == "SpriteEditorWindow").FirstOrDefault());
                 * }
                 */

                if (GUILayout.Button("Generate Multiple Sprites"))
                {
                    GenerateMultiple(sprites[0]);
                }

                if (GUILayout.Button("Layout"))
                {
                    PlaceInScene(sprites[0]);
                }
            }
        }

        // end horizontal row
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.Space();

        EditorGUILayout.LabelField("Import Settings", EditorStyles.boldLabel);

        // start horizontal row
        EditorGUILayout.BeginHorizontal();
        // label for max size
        EditorGUILayout.LabelField("Max Size", GUILayout.Width(130));
        size = EditorGUILayout.Popup(size, convertMaxSize);
        if (int.Parse(convertMaxSize[size]) != importer.maxTextureSize)
        {
            if (GUILayout.Button("Apply"))
            {
                importer.maxTextureSize = int.Parse(convertMaxSize[size]);
                importer.SaveAndReimport();
                AssetDatabase.Refresh();
            }
        }
        // end horizontal row
        EditorGUILayout.EndHorizontal();

        // start horizontal row
        EditorGUILayout.BeginHorizontal();
        // label for max size
        EditorGUILayout.LabelField("Compression", GUILayout.Width(130));
        if (powerOf4 || alreadyPower4)
        {
            compressionQuality = (TextureImporterCompression)EditorGUILayout.EnumPopup(compressionQuality);
            if (compressionQuality != importer.textureCompression)
            {
                if (GUILayout.Button("Apply"))
                {
                    importer.textureCompression = compressionQuality;
                    importer.SaveAndReimport();
                    AssetDatabase.Refresh();
                }
            }
        }
        else
        {
            EditorGUILayout.LabelField("Must be power of 4");
        }
        // end horizontal row
        EditorGUILayout.EndHorizontal();

        // start horizontal row
        EditorGUILayout.BeginHorizontal();
        // label for max size
        EditorGUILayout.LabelField("Crunch Compression", GUILayout.Width(130));
        if (powerOf4 || alreadyPower4)
        {
            useCrunch = EditorGUILayout.Toggle(useCrunch);
            if (useCrunch != importer.crunchedCompression)
            {
                if (GUILayout.Button("Apply"))
                {
                    importer.crunchedCompression = useCrunch;
                    importer.SaveAndReimport();
                    AssetDatabase.Refresh();
                }
            }
        }
        else
        {
            EditorGUILayout.LabelField("Must be power of 4");
        }
        // end horizontal row
        EditorGUILayout.EndHorizontal();

        if (useCrunch || importer.crunchedCompression)
        {
            // start horizontal row
            EditorGUILayout.BeginHorizontal();
            // label for max size
            EditorGUILayout.LabelField("Compressor Quality", GUILayout.Width(130));
            if (powerOf4 || alreadyPower4)
            {
                quality = EditorGUILayout.IntSlider(quality, 0, 100);
                if (quality != importer.compressionQuality)
                {
                    if (GUILayout.Button("Apply"))
                    {
                        importer.compressionQuality = quality;
                        importer.SaveAndReimport();
                        AssetDatabase.Refresh();
                    }
                }
            }
            else
            {
                EditorGUILayout.LabelField("Must be power of 4");
            }
            // end horizontal row
            EditorGUILayout.EndHorizontal();
        }

        bool changed = false;

        if (quality != importer.compressionQuality)
        {
            changed = true;
        }
        else if (useCrunch != importer.crunchedCompression)
        {
            changed = true;
        }
        else if (compressionQuality != importer.textureCompression)
        {
            changed = true;
        }
        else if (int.Parse(convertMaxSize[size]) != importer.maxTextureSize)
        {
            changed = true;
        }

        // start horizontal row
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("", GUILayout.Width(130));
        GUI.enabled = changed;
        if (GUILayout.Button("Revert All"))
        {
            quality            = importer.compressionQuality;
            useCrunch          = importer.crunchedCompression;
            compressionQuality = importer.textureCompression;
            for (int i = 0; i < convertMaxSize.Length; i++)
            {
                if (int.Parse(convertMaxSize[i]) == importer.maxTextureSize)
                {
                    size = i;
                }
            }
        }

        if (GUILayout.Button("Apply All"))
        {
            importer.compressionQuality  = quality;
            importer.crunchedCompression = useCrunch;
            importer.textureCompression  = compressionQuality;
            importer.compressionQuality  = quality;
            importer.maxTextureSize      = int.Parse(convertMaxSize[size]);
            importer.SaveAndReimport();
            AssetDatabase.Refresh();
        }

        GUI.enabled = true;
        // end horizontal row
        EditorGUILayout.EndHorizontal();


        GUILayout.Space(20);
        EditorGUILayout.LabelField("Split Settings", EditorStyles.boldLabel);

        // start horizontal row
        EditorGUILayout.BeginHorizontal();
        // label for max size
        EditorGUILayout.LabelField("Max Size", GUILayout.Width(130));
        splitSize = EditorGUILayout.Popup(splitSize, convertMaxSize);
        // end horizontal row
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Texture Type", GUILayout.Width(130));
        splitImporterType = (TextureImporterType)EditorGUILayout.EnumPopup(splitImporterType);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Use Import Settings", GUILayout.Width(130));
        useImportSettings = EditorGUILayout.Toggle(useImportSettings);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Create folder", GUILayout.Width(130));
        createSplitFolder = EditorGUILayout.Toggle(createSplitFolder);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("", GUILayout.Width(130));
        if (GUILayout.Button("Apply"))
        {
            SplitSprite(sprites[0]);
        }
        EditorGUILayout.EndHorizontal();

        // end vertical column
        EditorGUILayout.EndVertical();

        Rect rect = EditorGUILayout.BeginVertical(GUILayout.Width(position.width / 2));

        Texture2D tex    = sprites[0];
        float     width  = tex.width;
        float     height = tex.height;

        if (width > height)
        {
            width = width < (position.width / 2) - 130 ? width : (position.width / 2) - 130;
            float ratio = width / tex.width;
            height = height * ratio;
        }
        else
        {
            height = height < (position.height - 130) ? height : (position.height - 130);
            float ratio = height / tex.height;
            width = width * ratio;
        }

        float texWidth  = tex.width;
        float texHeight = tex.height;

        if (powerOf4)
        {
            while (texWidth % 4 != 0)
            {
                texWidth++;
            }

            while (texHeight % 4 != 0)
            {
                texHeight++;
            }
        }

        // draw texture
        if (showBackground)
        {
            EditorGUI.DrawTextureTransparent(new Rect(rect.x + 5, rect.y + 5, width, height), tex);
        }
        else
        {
            GUI.DrawTexture(new Rect(rect.x + 5, rect.y + 5, width, height), tex);
        }

        GUIStyle style = new GUIStyle();
        float    w     = style.CalcSize(new GUIContent(texWidth + "px")).x;
        float    lineW = (width - w) / 2.0f;

        GUI.DrawTexture(new Rect(rect.x + 5, rect.y + height + 10, lineW - 5, 2), CreateTexture(2, 2, Color.black));
        GUI.Label(new Rect(rect.x + 5 + (width / 2) - (w / 2), rect.y + height + 12 - 7.5f, w + 5, 15), texWidth + "px");
        GUI.DrawTexture(new Rect(rect.x + 5 + w + lineW + 5, rect.y + height + 10, lineW - 5, 2), CreateTexture(2, 2, Color.black));

        Vector2 h     = style.CalcSize(new GUIContent(texHeight + "px"));
        float   lineH = (height - h.y) / 2.0f;

        GUI.DrawTexture(new Rect(rect.x + 10 + width, rect.y + 5, 2, lineH - 5), CreateTexture(2, 2, Color.black));
        GUI.Label(new Rect(rect.x + 5 + width, rect.y + (height / 2) - (h.y / 2) + 5, h.x + 5, h.y + 5), texHeight + "px");
        GUI.DrawTexture(new Rect(rect.x + 10 + width, rect.y + 5 + h.y + lineH + 5, 2, lineH - 5), CreateTexture(2, 2, Color.black));

        EditorGUILayout.EndVertical();

        EditorGUILayout.EndHorizontal();
    }
Esempio n. 12
0
        //Analyzes textures in library, finds identical textures, removes duplicates
        public int removeTextures()
        {
            string[]         assetLib   = AssetDatabase.FindAssets("t:texture2D");
            List <string>    textureLib = new List <string>();
            List <Texture2D> duplicates = new List <Texture2D>();
            bool             remapped;
            List <Texture2D> remove = new List <Texture2D>();

            for (int i = 0; i < assetLib.Length; i++)
            {
                if (!AssetDatabase.GUIDToAssetPath(assetLib[i]).Contains(".cubemap"))
                {
                    textureLib.Add(assetLib[i]);
                }
            }
            string[] path = new string[textureLib.Count];
            byte[]   texData;
            int      index;

            int[]       texSize         = new int[textureLib.Count];
            Texture2D[] compareTextures = new Texture2D[textureLib.Count];
            Color32[]   comparePixels1;
            Color32[]   comparePixels2;

            bool dup  = false;
            bool orig = false;

            TextureImporterType[] texTypes = new TextureImporterType[textureLib.Count];

            string newPath = "Removed Assets";

            if (!Directory.Exists(newPath))
            {
                CreateFileStructure();
            }

            //Imports all textures as "advanced" so the pixel information is readable
            for (int i = 0; i < textureLib.Count; i++)
            {
                path[i]    = AssetDatabase.GUIDToAssetPath(textureLib[i]);
                texData    = File.ReadAllBytes(path[i]);
                texSize[i] = texData.Length;
                TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(path[i]);
                texTypes[i]             = texImporter.textureType;
                texImporter.textureType = TextureImporterType.Advanced;
                texImporter.isReadable  = true;
                compareTextures[i]      = AssetDatabase.LoadAssetAtPath(path[i], typeof(Texture2D)) as Texture2D;
                AssetDatabase.ImportAsset(path[i], ImportAssetOptions.ForceUpdate);
            }

            for (int a = 0; a < textureLib.Count; a++)
            {
                for (int b = 1; b < textureLib.Count - a; b++)
                {
                    index = a + b;
                    //is the size of texture[a] equal to the size of each subsesquent texture?
                    if (texSize[a] == texSize[index])
                    {
                        comparePixels1 = compareTextures[a].GetPixels32();
                        comparePixels2 = compareTextures[index].GetPixels32();
                        //does texture[a] have the same number of pixels?
                        if (comparePixels1.Length == comparePixels2.Length)
                        {
                            //is each pixel in texture[a] the same color?
                            for (int c = 0; c < comparePixels1.Length; c++)
                            {
                                if (!comparePixels1[c].Equals(comparePixels2[c]))
                                {
                                    c   = comparePixels1.Length;
                                    dup = false;
                                }
                                else
                                {
                                    dup = true;
                                }
                            }
                            //add the texture that matches texture[a] to the list of duplicates
                            if (dup)
                            {
                                duplicates.Add(compareTextures[index]);
                                //if texture[a] doesn't already exist in the duplicates, it is the original texture
                                for (int d = 0; d < duplicates.Count; d++)
                                {
                                    if (compareTextures[a] == duplicates[d])
                                    {
                                        orig = false;
                                        d    = duplicates.Count;
                                    }
                                    else
                                    {
                                        orig = true;
                                    }
                                }
                                //if texture[a] is the original texture, remap the duplicate texture to it. if able to remap, add the duplicate texture to the list of textures to remove
                                if (orig)
                                {
                                    remapped = remapMaterials(compareTextures[a], compareTextures[index], texTypes[a]);
                                    if (remapped)
                                    {
                                        remove.Add(compareTextures[index]);
                                    }
                                    if (path[index].Contains("Perfect Parallel Libraries"))
                                    {
                                        remove.Add(compareTextures[index]);
                                        remove.Add(compareTextures[a]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            //Reformats textures to be their original type
            for (int i = 0; i < textureLib.Count; i++)
            {
                path[i] = AssetDatabase.GUIDToAssetPath(textureLib[i]);
                if (File.Exists(path[i]))
                {
                    TextureImporter texImporter = (TextureImporter)TextureImporter.GetAtPath(path[i]);
                    texImporter.textureType = texTypes[i];
                    AssetDatabase.ImportAsset(path[i], ImportAssetOptions.ForceUpdate);
                }
            }
            //Moves remapped duplicate textures out of library; excludes if they are in the library associated with the course
            for (int i = 0; i < remove.Count; i++)
            {
                string currentAsset = AssetDatabase.GetAssetPath(remove.ElementAt(i).GetInstanceID());
                if (File.Exists(currentAsset) && !currentAsset.Contains(Course.LibraryName))
                {
                    File.Move(currentAsset, "Removed Assets/" + currentAsset);
                    if (File.Exists(currentAsset + ".meta"))
                    {
                        File.Move(currentAsset + ".meta", "Removed Assets/" + currentAsset + ".meta");
                    }
                    File.AppendAllText("Removed Assets/duplicateTextures.txt", currentAsset + "\r\n");
                    AssetDatabase.Refresh();
                }
            }
            return(remove.Count);
        }
Esempio n. 13
0
        public void DrawInspector(SerializedObject so,
                                  TextureImporterType importType)
        {
            EditorGUILayout.BeginHorizontal();
            for (int i = 0; i < 4; i++)
            {
                bool s = GUILayout.Toggle(i == selected,
                                          GetCaptionFor(i),
                                          GetStyleFor(i));
                selected = s ? i : selected;
            }
            EditorGUILayout.EndHorizontal();

            GUIStyle backgroundBox = new GUIStyle("box");

            backgroundBox.margin = new RectOffset(0, 0, 0, 0);
            EditorGUILayout.BeginVertical(backgroundBox);
            {
                string texSize    = "maxTextureSize";
                string texFormat  = "textureFormat";
                string alphaSplit = "allowsAlphaSplit";
                string compQual   = "compressionQuality";

                if (selected > 0)
                {
                    GUI.enabled = ToggleOverride(so, selected - 1);
                    string id = overrideID[selected - 1];
                    texSize   = id + texSize;
                    texFormat = id + texFormat;
                    compQual  = id + compQual;
                }

                bool android = selected == 3;
                bool ios     = selected == 2;

                SerializedProperty maxSize = so.FindProperty(texSize);
                MaxTextureSize     mts     = MaxTextureSize.POW5;
                int maxSel = GetIndex(mts, maxSize.intValue);
                maxSel = maxSel < 0 ? defaultMaxSize : maxSel;
                int maxSelNew = EditorGUILayout.Popup("Max Size", maxSel, GetLabels(mts));
                maxSize.intValue = GetValue(mts, maxSelNew);

                SerializedProperty frm = so.FindProperty(texFormat);
                int frmSel             = frm.enumValueIndex < 0 ? 0 : frm.enumValueIndex;
                frm.enumValueIndex = EditorGUILayout.Popup("Format", frmSel, texFormats);

                bool crunched   = TexFormatIs(frm, TextureImporterFormat.AutomaticCrunched);
                bool compressed = TexFormatIs(frm, TextureImporterFormat.AutomaticCompressed);

                // Crunched is not supported on iOS
                if (ios && crunched)
                {
                    EditorGUILayout.HelpBox("Crunched mode is not supported on " +
                                            "iOS. Unity will default to Compressed " +
                                            "when Crunch is selected.", MessageType.Warning);
                }

                SerializedProperty quality = so.FindProperty(compQual);

                // Show slider when:
                // Format = Crunched and Platform = default or standalone
                bool defaultOrStandalone = selected == 0 || selected == 1;
                if (crunched && defaultOrStandalone)
                {
                    quality.intValue = (int)EditorGUILayout.Slider("Compression Quality", quality.intValue, 0, 100);
                }

                // Show dropdown when:
                // Format = Crunched or Compressed and Platform = iOS or Android
                if ((crunched || compressed) && (ios || android))
                {
                    int qi = (quality.intValue / 100) * 2;
                    qi = EditorGUILayout.Popup("Compression Quality", qi, qualityLabels);
                    quality.intValue = (qi / 2) * 100;
                }

                // Split alpha channel = false on all, except
                // when import type is anything but Advanced and override platform is Android
                SerializedProperty alpha = so.FindProperty(alphaSplit);
                if (importType != TextureImporterType.Default && android)
                {
                    alpha.boolValue = EditorGUILayout.ToggleLeft("Compress using ETC1 (split alpha channel)",
                                                                 alpha.boolValue);
                }

                GUI.enabled = true;
            }
            EditorGUILayout.EndVertical();
        }
Esempio n. 14
0
        public virtual void ShowImportSettings(BaseTextureImportPlatformSettings editor)
        {
            // Max texture size
            EditorGUI.BeginChangeCheck();
            EditorGUI.showMixedValue = editor.model.overriddenIsDifferent || editor.model.maxTextureSizeIsDifferent;
            int maxTextureSize = EditorGUILayout.IntPopup(maxSize.text, editor.model.platformTextureSettings.maxTextureSize, kMaxTextureSizeStrings, kMaxTextureSizeValues);

            EditorGUI.showMixedValue = false;
            if (EditorGUI.EndChangeCheck())
            {
                editor.model.SetMaxTextureSizeForAll(maxTextureSize);
            }

            // Resize Algorithm
            EditorGUI.BeginChangeCheck();
            EditorGUI.showMixedValue = editor.model.overriddenIsDifferent || editor.model.resizeAlgorithmIsDifferent;
            int resizeAlgorithmVal = EditorGUILayout.IntPopup(kResizeAlgorithm.text, (int)editor.model.platformTextureSettings.resizeAlgorithm, kResizeAlgorithmStrings, kResizeAlgorithmValues);

            EditorGUI.showMixedValue = false;
            if (EditorGUI.EndChangeCheck())
            {
                editor.model.SetResizeAlgorithmForAll((TextureResizeAlgorithm)resizeAlgorithmVal);
            }

            // Texture format
            int[]    formatValuesForAll        = null;
            string[] formatStringsForAll       = null;
            bool     formatOptionsAreDifferent = false;

            int formatForAll = 0;

            // TODO : This should not be calculated every refresh and be kept in a cache somewhere instead...
            for (int i = 0; i < editor.GetTargetCount(); i++)
            {
                TextureImporterSettings settings           = editor.GetImporterSettings(i);
                TextureImporterType     textureTypeForThis = editor.textureTypeHasMultipleDifferentValues ? settings.textureType : editor.textureType;
                int format = (int)editor.model.platformTextureSettings.format;

                int[]    formatValues  = null;
                string[] formatStrings = null;

                if (!editor.model.isDefault && !editor.model.platformTextureSettings.overridden)
                {
                    // If not overriden, show what the auto format is going to be
                    // don't care about alpha in normal maps. If editor.assetTarget is null
                    // then we are dealing with texture preset and we show all options.
                    var showSettingsForPreset = editor.ShowPresetSettings();
                    var sourceHasAlpha        = showSettingsForPreset || (editor.DoesSourceTextureHaveAlpha(i) &&
                                                                          textureTypeForThis != TextureImporterType.NormalMap);

                    format = (int)TextureImporter.DefaultFormatFromTextureParameters(settings,
                                                                                     editor.model.platformTextureSettings,
                                                                                     !showSettingsForPreset && sourceHasAlpha,
                                                                                     !showSettingsForPreset && editor.IsSourceTextureHDR(i),
                                                                                     editor.model.buildTarget);

                    formatValues  = new int[] { format };
                    formatStrings = new string[] { TextureUtil.GetTextureFormatString((TextureFormat)format) };
                }
                else
                {
                    // otherwise show valid formats
                    editor.model.GetValidTextureFormatsAndStrings(textureTypeForThis, out formatValues, out formatStrings);
                }

                // Check if values are the same
                if (i == 0)
                {
                    formatValuesForAll  = formatValues;
                    formatStringsForAll = formatStrings;
                    formatForAll        = format;
                }
                else
                {
                    if (!formatValues.SequenceEqual(formatValuesForAll) || !formatStrings.SequenceEqual(formatStringsForAll))
                    {
                        formatOptionsAreDifferent = true;
                        break;
                    }
                }
            }

            using (new EditorGUI.DisabledScope(formatOptionsAreDifferent || formatStringsForAll.Length == 1))
            {
                EditorGUI.BeginChangeCheck();
                bool mixedValues = formatOptionsAreDifferent || editor.model.textureFormatIsDifferent;
                EditorGUI.showMixedValue = mixedValues;
                var selectionResult = EditorGUILayout.IntPopup(kTextureFormat, formatForAll, EditorGUIUtility.TempContent(formatStringsForAll), formatValuesForAll);
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    editor.model.SetTextureFormatForAll((TextureImporterFormat)selectionResult);
                    formatForAll = selectionResult;
                }

                if (!mixedValues && !Array.Exists(formatValuesForAll, i => i == formatForAll))
                {
                    EditorGUILayout.HelpBox(string.Format(L10n.Tr("The selected format value {0} is not compatible on this platform, please change it to a valid one from the dropdown."), (TextureImporterFormat)formatForAll), MessageType.Error);
                }
            }

            // Texture Compression
            if (editor.model.isDefault && editor.model.platformTextureSettings.format == TextureImporterFormat.Automatic)
            {
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = editor.model.overriddenIsDifferent ||
                                           editor.model.textureCompressionIsDifferent ||
                                           editor.model.platformTextureSettings.format != TextureImporterFormat.Automatic;
                TextureImporterCompression textureCompression =
                    (TextureImporterCompression)EditorGUILayout.IntPopup(kTextureCompression,
                                                                         (int)editor.model.platformTextureSettings.textureCompression, kTextureCompressionOptions,
                                                                         kTextureCompressionValues);
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    editor.model.SetTextureCompressionForAll(textureCompression);
                }
            }

            // Use Crunch Compression
            if (editor.model.isDefault &&
                (TextureImporterFormat)formatForAll == TextureImporterFormat.Automatic &&
                editor.model.platformTextureSettings.textureCompression != TextureImporterCompression.Uncompressed)
            {
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = editor.model.overriddenIsDifferent ||
                                           editor.model.crunchedCompressionIsDifferent;
                bool crunchedCompression = EditorGUILayout.Toggle(
                    kCrunchedCompression, editor.model.platformTextureSettings.crunchedCompression);
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    editor.model.SetCrunchedCompressionForAll(crunchedCompression);
                }
            }

            // compression quality
            bool isCrunchedFormat = false ||
                                    TextureUtil.IsCompressedCrunchTextureFormat((TextureFormat)formatForAll)
            ;

            if (
                (editor.model.isDefault &&
                 (TextureImporterFormat)formatForAll == TextureImporterFormat.Automatic &&
                 editor.model.platformTextureSettings.textureCompression != TextureImporterCompression.Uncompressed &&
                 editor.model.platformTextureSettings.crunchedCompression) ||
                (editor.model.isDefault && editor.model.platformTextureSettings.crunchedCompression && isCrunchedFormat) ||
                (!editor.model.isDefault && isCrunchedFormat) ||
                (!editor.model.textureFormatIsDifferent && ArrayUtility.Contains <TextureImporterFormat>(
                     TextureImporterInspector.kFormatsWithCompressionSettings,
                     (TextureImporterFormat)formatForAll)))
            {
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = editor.model.overriddenIsDifferent ||
                                           editor.model.compressionQualityIsDifferent;

                // Prior to exposing compression quality for BC6H/BC7 formats they were always compressed at maximum quality even though the setting was
                // defaulted to 'Normal'.  Now BC6H/BC7 quality is exposed to the user as Fast/Normal/Best 'Normal' maps to one setting down from maximum in the
                // ISPC compressor but to maintain the behaviour of existing projects we need to force their quality up to 'Best'.  The 'forceMaximumCompressionQuality_BC6H_BC7'
                // flag is set when loading existing texture platform settings to do this and cleared when the compression quality level is manually set (by UI or API)
                bool forceBestQuality   = editor.model.forceMaximumCompressionQuality_BC6H_BC7 && (((TextureImporterFormat)formatForAll == TextureImporterFormat.BC6H) || ((TextureImporterFormat)formatForAll == TextureImporterFormat.BC7));
                int  compressionQuality = forceBestQuality ? (int)TextureCompressionQuality.Best : editor.model.platformTextureSettings.compressionQuality;

                compressionQuality       = EditCompressionQuality(editor.model.buildTarget, compressionQuality, isCrunchedFormat, (TextureImporterFormat)formatForAll);
                EditorGUI.showMixedValue = false;
                if (EditorGUI.EndChangeCheck())
                {
                    editor.model.SetCompressionQualityForAll(compressionQuality);
                    //SyncPlatformSettings ();
                }
            }

            // show the ETC1 split option only for sprites on platforms supporting ETC and only when there is an alpha channel
            bool isETCPlatform       = TextureImporter.IsETC1SupportedByBuildTarget(BuildPipeline.GetBuildTargetByName(editor.model.platformTextureSettings.name));
            bool isDealingWithSprite = (editor.spriteImportMode != SpriteImportMode.None);
            bool isETCFormatSelected = TextureImporter.IsTextureFormatETC1Compression((TextureFormat)formatForAll);

            if (isETCPlatform && isDealingWithSprite && isETCFormatSelected)
            {
                EditorGUI.BeginChangeCheck();
                EditorGUI.showMixedValue = editor.model.overriddenIsDifferent || editor.model.allowsAlphaSplitIsDifferent;
                bool allowsAlphaSplit = EditorGUILayout.Toggle(kUseAlphaSplitLabel, editor.model.platformTextureSettings.allowsAlphaSplitting);
                if (EditorGUI.EndChangeCheck())
                {
                    editor.model.SetAllowsAlphaSplitForAll(allowsAlphaSplit);
                }
            }
        }
Esempio n. 15
0
    void OnGUI()
    {
        int i, j;

        ResetManager();        //Remakes game objects require to operate.
        e = Event.current;     //Gets current event (mouse move, repaint, keyboard press, etc)

        if (renameId != -1 && (e.keyCode == KeyCode.Return || e.keyCode == KeyCode.KeypadEnter))
        {
            renameId = -1;
        }

        if (cmTileSets == null)        //Check to make certain there is actually a tileset in the resources/tileset folder.
        {
            EditorGUILayout.LabelField("No tilesets found. Retrying.");
            OnEnable();
        }
        else
        {
            string[] names = new string[cmTileSets.Length];             //Gets the name of the tilesets into a useable list
            for (i = 0; i < cmTileSets.Length; i++)
            {
                try
                {
                    names[i] = cmTileSets[i].name;
                }
                catch (System.Exception ex)
                {
                    Debug.Log("There was an error getting the names of the files. We'll try to reload the tilesets. If this continues to show, please close the script and try remimporting and check your images.");
                    Debug.Log("Full system error: " + ex.Message);
                    OnEnable();
                }
            }

            //Mode variable to swith between major features.
            string[] mode = { "Tile Painter", "Help Video" };          //, "Pad Tileset"};// Pad tileset not finished yet, removed to allow for earlier release. You can try it out if you want, but is has issues with larger images and places tiles in the wrong order.
            curMode = GUILayout.Toolbar(curMode, mode);

            if (curMode == 0)
            {
                //If in standard paint mode, display the proper gui elements for the user to use.
                EditorGUILayout.BeginHorizontal();
                int tmpInt = EditorGUILayout.Popup("Tileset", cmSelectedTileSet, names);
                if (GUILayout.Button("Reload"))
                {
                    OnEnable();
                }
                EditorGUILayout.EndHorizontal();

                string[] tools = { "Paint", "Erase", "Box Paint" };
                //curTool = EditorGUILayout.Popup("Tool", curTool, tools);

                EditorGUILayout.BeginHorizontal(GUILayout.Width(position.width));
                //Causes an error on editor load if the window is visible.
                //This seems to be a problem with how the gui is drawn the first
                //loop of the script. It only happens the once, and I can't figure
                //out why. I've been trying for literally weeks and still can't
                //find an answer. This is the only known bug, but it doesn't
                //stop the functionality of the script in any way, and only serves
                //as an annoying message on unity load or this script being
                //recompiled. Sorry for this bug. I am looking for a way to remove
                //this error, but I really am stummped as to why it's happening
                //and I just can not find an answer online.


                EditorGUILayout.LabelField("Tool", GUILayout.Width(50));
                GUILayout.FlexibleSpace();
                curTool = GUILayout.Toolbar(curTool, tools);
                GUILayout.FlexibleSpace();
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Paint With Collider", GUILayout.Width(150));
                makeCollider = EditorGUILayout.Toggle(makeCollider);
                EditorGUILayout.EndHorizontal();

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Highlight Current Layer", GUILayout.Width(150));
                highlightLayer = EditorGUILayout.Toggle(highlightLayer, GUILayout.Width(25));
                highlightColor = EditorGUILayout.ColorField(highlightColor);
                EditorGUILayout.EndHorizontal();

                if (tmpInt != cmSelectedTileSet)                //Forces selection of first tileset if none are selected.
                {
                    LoadTileset(tmpInt);
                }

                cmSelectedTileSet = tmpInt;                 //sets the selected tileset value

                i = 0;
                int columnCount = Mathf.RoundToInt((position.width) / 38) - 2;     //figures out how many columns are required for the tileset
                j = 0;
                int current = 0;

                tileScrollPosition = EditorGUILayout.BeginScrollView(tileScrollPosition, false, true, GUILayout.Width(position.width));
                //creates scrollbox area for tiles inside of the current tileset.

                GUILayout.BeginHorizontal();                 //Initializing first row

                for (int q = 0; q < cmSprites.Length; q++)
                {
                    Sprite child = cmSprites[q];
                    //for every tile inside the currently selected tileset, add a tile
                    try
                    {
                        if (child.texture.name == names[cmSelectedTileSet] && child.name != names[cmSelectedTileSet])
                        {
                            //if it's the tiles inside the image, not the entire image

                            Rect newRect = new Rect(
                                child.rect.x / child.texture.width,
                                child.rect.y / child.texture.height,
                                child.rect.width / child.texture.width,
                                child.rect.height / child.texture.height
                                );                                                   //gets the x and y position in pixels of where the image is. Used later for display.

                            if (GUILayout.Button("", GUILayout.Width(34), GUILayout.Height(34)))
                            {
                                //draw a clickable button
                                if (cmSelectedTile != null && !e.control)
                                {
                                    //empty the selected tile list if control isn't held. Allows multiselect of tiles.
                                    cmSelectedTile.Clear();
                                    cmCurSprite.Clear();
                                }
                                cmSelectedTile.Add(current);                         //Adds clicked on tile to list of selected tiles.
                                cmCurSprite.Add(cmCurSprites[current]);
                            }

                            GUI.DrawTextureWithTexCoords(new Rect(5 + (j * 38), 4 + (i * 37), 32, 32), child.texture, newRect, true);             //draws tile base on pixels gotten at the beginning of the loop
                            if (cmSelectedTile != null && cmSelectedTile.Contains(current))
                            {
                                //if the current tile is inside of the list of selected tiles, draw a highlight indicator over the button.
                                if (cmSelectedColor == null)
                                {
                                    cmSelectedColor = new Texture2D(1, 1);
                                    cmSelectedColor.alphaIsTransparency = true;
                                    cmSelectedColor.filterMode          = FilterMode.Point;
                                    cmSelectedColor.SetPixel(0, 0, new Color(.5f, .5f, 1f, .5f));
                                    cmSelectedColor.Apply();
                                }
                                GUI.DrawTexture(new Rect(5 + (j * 38), 4 + (i * 37), 32, 32), cmSelectedColor, ScaleMode.ScaleToFit, true);
                            }

                            if (j < columnCount)
                            {
                                j++;
                            }
                            else
                            {
                                // if we have enough columns to fill the scroll area, reset the column count and start a new line of buttons
                                j = 0;
                                i++;
                                GUILayout.EndHorizontal();
                                GUILayout.BeginHorizontal();
                            }
                            current++;
                        }
                    }catch (System.Exception ex) {
                        if (ex.Message.StartsWith("IndexOutOfRangeException"))
                        {
                            Debug.Log("Tileset index was out of bounds, reloading and trying again.");
                            OnEnable();
                            return;
                        }
                    }
                }
                GUILayout.EndHorizontal();                 //finish the drawing of tiles
                EditorGUILayout.EndScrollView();
                //Display all of the layers. May be put into a foldout for if there are too many layers. Haven't decided yet.
                GUILayout.Label("Layers:");

                if (GUILayout.Button("Add Layer"))
                {
                    AddLayer();
                }
                String[] minusPlus = { "-", "+", "x", "r" };


                ResetLayers();
                layers = ResortLayers(layers);                //Sort the layers based on their sorting order instead of name
                int destroyFlag = -1;
                for (i = 0; i < layers.Count; i++)
                {
                    //iterates through layers and displays gui for options.
                    EditorGUILayout.BeginHorizontal();

                    RectOffset tmpPadding = GUI.skin.button.padding;
                    GUI.skin.button.padding = new RectOffset(3, 3, 3, 3);

                    if (layers[i].gameObject.activeSelf)
                    {
                        if (GUILayout.Button(texVisible, GUILayout.Width(15), GUILayout.Height(15)))
                        {
                            layers[i].gameObject.SetActive(false);
                        }
                    }
                    else
                    {
                        if (GUILayout.Button(texHidden, GUILayout.Width(15), GUILayout.Height(15)))
                        {
                            layers[i].gameObject.SetActive(true);
                        }
                    }
                    GUI.skin.button.padding = tmpPadding;

                    if (i == selectedLayer)
                    {
                        //if selected layer, draw checked checkbox to show it's selected
                        if (i != renameId)
                        {
                            EditorGUILayout.ToggleLeft(layers[i].name + " - " + layers[i].GetComponent <SpriteRenderer>().sortingOrder, true);
                        }
                        else
                        {
                            layers[i].name = EditorGUILayout.TextField(layers[i].name);
                        }
                    }
                    else
                    {
                        //if not the selected layer, and is clicked, set it as the selected layer
                        if (i != renameId)
                        {
                            if (EditorGUILayout.ToggleLeft(layers[i].name + " - " + layers[i].GetComponent <SpriteRenderer>().sortingOrder, false))
                            {
                                selectedLayer = i;
                            }
                        }
                        else
                        {
                            layers[i].name = EditorGUILayout.TextField(layers[i].name);
                        }
                    }

                    //sets pressed value to -1 if nothing is pressed.
                    int pressed = GUILayout.Toolbar(-1, minusPlus);

                    switch (pressed)
                    {
                    case 0:
                        if (i > 0)
                        {
                            //moves layer and all tiles in it to move away from the camera, and moves the layer above it toward the camera.
                            layers[i - 1].GetComponent <SpriteRenderer>().sortingOrder += 1;
                            int upLayer = layers[i - 1].GetComponent <SpriteRenderer>().sortingOrder;

                            foreach (SpriteRenderer sr in layers[i - 1].GetComponentsInChildren <SpriteRenderer>())
                            {
                                sr.sortingOrder = upLayer;
                            }

                            //layers[i].GetComponent<SpriteRenderer>().sortingOrder -= 1;
                            int downLayer = layers[i].GetComponent <SpriteRenderer>().sortingOrder -= 1;

                            foreach (SpriteRenderer sr in layers[i].GetComponentsInChildren <SpriteRenderer>())
                            {
                                sr.sortingOrder = downLayer;
                            }
                            selectedLayer = i - 1;
                        }
                        layers = ResortLayers(layers);
                        break;

                    case 1:
                        if (i < layers.Count - 1)
                        {
                            //moves layer and all tiles in it to move toward the camera, and moves the layer above it away from the camera.
                            layers[i + 1].GetComponent <SpriteRenderer>().sortingOrder -= 1;
                            int upLayer = layers[i + 1].GetComponent <SpriteRenderer>().sortingOrder;

                            foreach (SpriteRenderer sr in layers[i + 1].GetComponentsInChildren <SpriteRenderer>())
                            {
                                sr.sortingOrder = upLayer;
                            }

                            //layers[i].GetComponent<SpriteRenderer>().sortingOrder += 1;
                            int downLayer = layers[i].GetComponent <SpriteRenderer>().sortingOrder += 1;

                            foreach (SpriteRenderer sr in layers[i].GetComponentsInChildren <SpriteRenderer>())
                            {
                                sr.sortingOrder = downLayer;
                            }
                            selectedLayer = i + 1;
                        }
                        layers = ResortLayers(layers);
                        break;

                    case 2:
                        //deletes the layer game object, which also deletes all the children
                        destroyFlag = i;
                        break;

                    case 3:
                        if (renameId == -1)
                        {
                            renameId = i;
                        }
                        else
                        {
                            renameId = -1;
                        }
                        break;

                    default:
                        //do nothing if a button wasn't pressed (required or I get errors T_T)
                        break;
                    }
                    EditorGUILayout.EndHorizontal();                     //end the layer gui
                }
                if (selectedLayer <= layers.Count - 1 && selectedLayer > 0)
                {
                    //double check to make certain a layer of some sort is selected and is in valid range
                    curLayer = layers[selectedLayer].gameObject;
                }

                if (selectedLayer <= layers.Count - 1 && layers[selectedLayer] != null)
                {
                    ResetHighlight(layers[selectedLayer].gameObject, highlightLayer);
                    curLayer = layers[selectedLayer].gameObject;
                }
                else
                {
                    if (layers.Count - 1 > 0 && layers[selectedLayer] != null)
                    {
                        curLayer = layers[selectedLayer].gameObject;
                    }
                    else
                    {
                    }
                }
                if (destroyFlag != -1)
                {
                    DestroyImmediate(layers[destroyFlag].gameObject);
                    return;                     //Breaks method to not have errors down the line. Forces reload of tilesets to keep inside the bounds of the array.
                }
                destroyFlag = -1;
            }
            else if (curMode == 1)
            {
                curMode = 0;
                Application.OpenURL("https://www.youtube.com/watch?v=mxy9HdNM-is");
                return;
            }
            else if (curMode == 2)
            {
                int tmpInt = EditorGUILayout.Popup("Tileset", cmSelectedTileSet, names);
                if (tmpInt != cmSelectedTileSet)                //Forces selection of first tileset if none are selected.
                {
                    LoadTileset(tmpInt);
                }

                cmSelectedTileSet = tmpInt;                 //sets the selected tileset value

                GUILayout.BeginHorizontal();
                GUILayout.Label("Grid Size X", GUILayout.Width(200));
                gridSizeX = EditorGUILayout.IntField(gridSizeX);
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Label("Grid Size Y", GUILayout.Width(200));
                gridSizeY = EditorGUILayout.IntField(gridSizeY);
                GUILayout.EndHorizontal();

                /*GUILayout.BeginHorizontal();
                 * GUILayout.Label("Pad Size X", GUILayout.Width(200));
                 * padSizeX = EditorGUILayout.IntField(padSizeX);
                 * GUILayout.EndHorizontal();
                 *
                 * GUILayout.BeginHorizontal();
                 * GUILayout.Label("Pad Size Y", GUILayout.Width(200));
                 * padSizeY = EditorGUILayout.IntField(padSizeY);
                 * GUILayout.EndHorizontal();*/


                if (GUILayout.Button("Generate New Texture"))
                {
                    List <Rect> listOfNewSlices = new List <Rect>();
                    Texture2D   curTileSet      = Resources.Load <Texture2D>("Tilesets/" + cmTileSets[cmSelectedTileSet].name);            //cmTileSets[cmSelectedTileSet];
                    int         newWidth        = (int)(curTileSet.width + (padSizeX * 2 * (curTileSet.width / gridSizeX)));
                    int         newHeight       = (int)(curTileSet.height + (((curTileSet.height / gridSizeY)) * (padSizeY * 2)));

                    Texture2D newTileSet = new Texture2D(newWidth, newHeight);

                    Debug.Log("Generated new tile image with a size of " + newTileSet.width + ", " + newTileSet.height);
//					Debug.Log("Tilecount: " + (int)(curTileSet.width/gridSizeX) + ", " + (int)(curTileSet.height/gridSizeY));
                    for (j = 0; j < (int)(curTileSet.width / gridSizeX); j++)
                    {
                        for (i = 0; i < (int)(curTileSet.height / gridSizeY); i++)
                        {
                            //Copies old image tiles to new image with padding.
                            try{
                                newTileSet.SetPixels(
                                    ((j * gridSizeX) + (j * padSizeX * 2)) + padSizeX,
                                    ((i * gridSizeY) + (i * padSizeY * 2)) + padSizeY,
                                    gridSizeX,
                                    gridSizeY,
                                    curTileSet.GetPixels(
                                        j * gridSizeX,
                                        i * gridSizeY,
                                        gridSizeX,
                                        gridSizeY));
                                Debug.Log(i * 32);

                                //LeftSide

                                /*newTileSet.SetPixels(
                                 *      (j*gridSizeX)+(j*padSizeX*2)+padSizeX-1,
                                 *      (i*gridSizeY)+(i*padSizeY*2),
                                 *      1,
                                 *      gridSizeY,
                                 *      curTileSet.GetPixels(
                                 *      j*gridSizeX,
                                 *      i*gridSizeY,
                                 *      1,
                                 *      gridSizeY));
                                 *
                                 * //RightSide
                                 * newTileSet.SetPixels(
                                 *      (j*gridSizeX)+(j*padSizeX*2)+padSizeX + gridSizeX,
                                 *      (i*gridSizeY)+(i*padSizeY*2),
                                 *      1,
                                 *      gridSizeY,
                                 *      curTileSet.GetPixels(
                                 *      (j*gridSizeX)+gridSizeX-1,
                                 *      i*gridSizeY,
                                 *      1,
                                 *      gridSizeY));
                                 *
                                 * //BottomSide
                                 * newTileSet.SetPixels(
                                 *      (j*gridSizeX)+(j*padSizeX*2)+padSizeX,
                                 *      (i*gridSizeY)+(i*padSizeY*2)-1,
                                 *      gridSizeX,
                                 *      1,
                                 *      curTileSet.GetPixels(
                                 *      j*gridSizeX,
                                 *      i*gridSizeY,
                                 *      gridSizeX,
                                 *      1));
                                 *
                                 * //TopSide
                                 * newTileSet.SetPixels(
                                 *      (j*gridSizeX)+(j*padSizeX*2)+padSizeX,
                                 *      (i*gridSizeY)+(i*padSizeY*2)+gridSizeY,
                                 *      gridSizeX,
                                 *      1,
                                 *      curTileSet.GetPixels(
                                 *      (j*gridSizeX),
                                 *      (i*gridSizeY)+gridSizeY-1,
                                 *      gridSizeX,
                                 *      1));*/
                                listOfNewSlices.Add(new Rect(
                                                        ((i * gridSizeY) + (i * padSizeY * 2)) + padSizeY,
                                                        ((j * gridSizeX) + (j * padSizeX * 2)) + padSizeX,
                                                        gridSizeX,
                                                        gridSizeY));

                                //Debug.Log("Drawing tile " + i + ", " + j + " at " + ((i*padSizeX)+(i*gridSizeX)) + ", " + ((j*padSizeY)+(j*gridSizeY)) + " from " + i*gridSizeX + ", " + j*gridSizeY);
                            }catch (System.Exception ex)
                            {
                                Debug.Log("ERROR: " + ex.Message);
                                if (0 == 0)
                                {
                                }
                            }
                        }
                    }
                    newTileSet.Apply();
                    //listOfNewSlices.Add(new Rect(0,newTileSet.height-gridSizeX,100,100));
                    Debug.Log("Image generation completed, generating slices.");

                    /*FileStream fs = new FileStream(Application.dataPath + "/Resources/Tilesets/" + curTileSet.name + "_padded.png", FileMode.Append);
                     * BinaryWriter bw = new BinaryWriter(fs);
                     * bw.Write(newTileSet.EncodeToPNG());
                     * bw.Close();
                     * fs.Close();*/

                    //AssetDatabase.CreateAsset(newTileSet.EncodeToPNG(), "Assets/Resources/Tilesets/" + curTileSet.name + "_padded.png");
                    bool isWriting = true;
                    while (isWriting)
                    {
                        File.WriteAllBytes(Application.dataPath + "/Resources/Tilesets/" + curTileSet.name + "_padded.png", newTileSet.EncodeToPNG());
                        isWriting = false;
                    }
                    AssetDatabase.Refresh();
                    TextureImporter ti = new TextureImporter();
                    ti = (TextureImporter)AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(Resources.Load <Texture>("Tilesets/" + curTileSet.name + "_padded")));
                    TextureImporterType type = new TextureImporterType();
                    type                   = TextureImporterType.Sprite;
                    ti.textureType         = type;
                    ti.spritePixelsPerUnit = gridSizeX;
                    ti.spriteImportMode    = SpriteImportMode.Multiple;
                    ti.filterMode          = FilterMode.Point;

                    List <SpriteMetaData> spriteData = new List <SpriteMetaData>();                  //[listOfNewSlices.Count+1];
                    //listOfNewSlices.Reverse();

                    for (i = 0; i < listOfNewSlices.Count; i++)
                    {
                        float alpha = 0;
                        foreach (Color pixel in newTileSet.GetPixels((int)listOfNewSlices[i].x, (int)listOfNewSlices[i].y, (int)listOfNewSlices[i].width, (int)listOfNewSlices[i].height))
                        {
                            alpha += pixel.a;
                        }
                        if (alpha > 0)
                        {
                            listOfNewSlices[i] = new Rect(listOfNewSlices[i].x, listOfNewSlices[i].y, listOfNewSlices[i].width, listOfNewSlices[i].height);
                            SpriteMetaData tmpSpriteData = new SpriteMetaData();
                            tmpSpriteData.rect      = listOfNewSlices[i];
                            tmpSpriteData.name      = curTileSet.name + "_padded_" + i;                       // ti.spritesheet.GetLength(0);
                            tmpSpriteData.alignment = 0;
                            tmpSpriteData.pivot     = new Vector2(gridSizeX / 2, gridSizeY / 2);
                            spriteData.Add(tmpSpriteData);
                        }
                        else
                        {
                            listOfNewSlices.RemoveAt(i);
                            //spriteData.RemoveAt(i);
                            i--;
                        }
                    }

                    ti.spritesheet = spriteData.ToArray();

                    Debug.Log("Finished generating new padded tileset. Pausing thread to update file.");
                    System.Threading.Thread.Sleep(4000);                    //Added to allow for saving and reimporting image in unity. Required to run without error.
                    OnEnable();
                }
                if (GUILayout.Button("Regenerate to Original File"))
                {
                }
            }
        }
    }
Esempio n. 16
0
        public TextureGenerationSettings(TextureImporterType type)
        {
            m_EnablePostProcessor     = true;
            m_AssetPath               = "";
            m_QualifyForSpritePacking = false;
            m_SpritePackingTag        = "";
            m_SpriteImportData        = null;
            m_SecondarySpriteTextures = null;

            m_SourceTextureInformation               = new SourceTextureInformation();
            m_SourceTextureInformation.width         = m_SourceTextureInformation.height = 0;
            m_SourceTextureInformation.containsAlpha = false;
            m_SourceTextureInformation.hdr           = false;

            m_PlatformSettings                      = new TextureImporterPlatformSettings();
            m_PlatformSettings.overridden           = false;
            m_PlatformSettings.format               = TextureImporterFormat.Automatic;
            m_PlatformSettings.maxTextureSize       = 2048;
            m_PlatformSettings.allowsAlphaSplitting = false;
            m_PlatformSettings.resizeAlgorithm      = TextureResizeAlgorithm.Mitchell;
            m_PlatformSettings.compressionQuality   = (int)TextureCompressionQuality.Normal;
            m_PlatformSettings.crunchedCompression  = false;
            m_PlatformSettings.name                 = TextureImporter.defaultPlatformName;

            // Values from TextureImporterSettings native constructor
            m_Settings                          = new TextureImporterSettings();
            m_Settings.textureType              = type;
            m_Settings.textureShape             = TextureImporterShape.Texture2D;
            m_Settings.convertToNormalMap       = false;
            m_Settings.mipmapEnabled            = true;
            m_Settings.mipmapFilter             = TextureImporterMipFilter.BoxFilter;
            m_Settings.sRGBTexture              = true;
            m_Settings.borderMipmap             = false;
            m_Settings.mipMapsPreserveCoverage  = false;
            m_Settings.alphaTestReferenceValue  = 0.5f;
            m_Settings.readable                 = false;
            m_Settings.fadeOut                  = false;
            m_Settings.mipmapFadeDistanceStart  = 1;
            m_Settings.mipmapFadeDistanceEnd    = 3;
            m_Settings.heightmapScale           = 0.25f;
            m_Settings.normalMapFilter          = TextureImporterNormalFilter.Standard;
            m_Settings.cubemapConvolution       = 0;
            m_Settings.generateCubemap          = TextureImporterGenerateCubemap.AutoCubemap;
            m_Settings.seamlessCubemap          = false;
            m_Settings.npotScale                = TextureImporterNPOTScale.ToNearest;
            m_Settings.spriteMode               = (int)SpriteImportMode.Single;
            m_Settings.spriteExtrude            = 1;
            m_Settings.spriteMeshType           = SpriteMeshType.Tight;
            m_Settings.spriteAlignment          = (int)SpriteAlignment.Center;
            m_Settings.spritePivot              = Vector2.one * 0.5f;
            m_Settings.spritePixelsPerUnit      = 100;
            m_Settings.spriteBorder             = Vector4.zero;
            m_Settings.alphaSource              = TextureImporterAlphaSource.FromInput;
            m_Settings.alphaIsTransparency      = false;
            m_Settings.spriteTessellationDetail = -1;
            m_Settings.wrapMode                 = m_Settings.wrapModeU = m_Settings.wrapModeV = m_Settings.wrapModeW = TextureWrapMode.Repeat;

            // From TextureImporterSettings::ApplyTextureType
            switch (type)
            {
            case TextureImporterType.Default:
                m_Settings.sRGBTexture   = true;
                m_Settings.mipmapEnabled = true;
                break;

            case TextureImporterType.NormalMap:
                m_Settings.sRGBTexture = false;
                break;

            case TextureImporterType.GUI:
                m_Settings.sRGBTexture         = false;
                m_Settings.mipmapEnabled       = false;
                m_Settings.alphaIsTransparency = true;
                m_Settings.npotScale           = TextureImporterNPOTScale.None;
                m_Settings.aniso    = 1;
                m_Settings.wrapMode = m_Settings.wrapModeU = m_Settings.wrapModeV = m_Settings.wrapModeW = TextureWrapMode.Clamp;
                break;

            case TextureImporterType.Sprite:
                m_Settings.npotScale           = TextureImporterNPOTScale.None;
                m_Settings.alphaIsTransparency = true;
                m_Settings.mipmapEnabled       = false;
                m_Settings.sRGBTexture         = true;
                m_Settings.wrapMode            = m_Settings.wrapModeU = m_Settings.wrapModeV = m_Settings.wrapModeW = TextureWrapMode.Clamp;
                m_Settings.alphaSource         = TextureImporterAlphaSource.FromInput;
                break;

            case TextureImporterType.Cursor:
                m_Settings.readable            = true;
                m_Settings.alphaIsTransparency = true;
                m_Settings.mipmapEnabled       = false;
                m_Settings.npotScale           = TextureImporterNPOTScale.None;
                m_Settings.aniso    = 1;
                m_Settings.wrapMode = m_Settings.wrapModeU = m_Settings.wrapModeV = m_Settings.wrapModeW = TextureWrapMode.Clamp;
                break;

            case TextureImporterType.Cookie:
                m_Settings.borderMipmap = true;
                m_Settings.wrapMode     = m_Settings.wrapModeU = m_Settings.wrapModeV = m_Settings.wrapModeW = TextureWrapMode.Clamp;
                m_Settings.aniso        = 0;
                break;

            case TextureImporterType.Lightmap:
                m_Settings.sRGBTexture         = true;
                m_Settings.npotScale           = TextureImporterNPOTScale.ToNearest;
                m_Settings.alphaIsTransparency = false;
                m_Settings.alphaSource         = TextureImporterAlphaSource.None;
                break;

            case TextureImporterType.SingleChannel:
                m_Settings.sRGBTexture = false;
                break;
            }
        }
Esempio n. 17
0
        static TextureGenerationOutput GenerateTexture(NativeArray <Color32> imageBuffer, int imageBufferWidth, int imageBufferHeight, TextureImporterType type, TextureImporterPlatformSettings platformSettings, params ITextureSettings[] otherSettings)
        {
            var textureGenerationSettings = new TextureGenerationSettings();

            textureGenerationSettings.platformSettings = platformSettings;

            textureGenerationSettings.sourceTextureInformation        = new SourceTextureInformation();
            textureGenerationSettings.sourceTextureInformation.height = imageBufferHeight;
            textureGenerationSettings.sourceTextureInformation.width  = imageBufferWidth;

            textureGenerationSettings.textureImporterSettings              = new TextureImporterSettings();
            textureGenerationSettings.textureImporterSettings.textureType  = type;
            textureGenerationSettings.textureImporterSettings.textureShape = TextureImporterShape.Texture2D;

            textureGenerationSettings.textureImporterSettings.alphaIsTransparency = false;
            textureGenerationSettings.textureImporterSettings.convertToNormalMap  = false;
            textureGenerationSettings.textureImporterSettings.mipmapEnabled       = false;
            textureGenerationSettings.textureImporterSettings.sRGBTexture         = true;
            textureGenerationSettings.textureImporterSettings.readable            = false;
            textureGenerationSettings.textureImporterSettings.fadeOut             = false;
            textureGenerationSettings.textureImporterSettings.wrapMode            = TextureWrapMode.Repeat;
            textureGenerationSettings.textureImporterSettings.wrapModeU           = TextureWrapMode.Repeat;
            textureGenerationSettings.textureImporterSettings.wrapModeV           = TextureWrapMode.Repeat;
            textureGenerationSettings.textureImporterSettings.wrapModeW           = TextureWrapMode.Repeat;

            foreach (var otherSetting in otherSettings)
            {
                if (otherSetting != null)
                {
                    otherSetting.FillTextureGenerationSettings(ref textureGenerationSettings);
                }
            }
            return(TextureGenerator.GenerateTexture(textureGenerationSettings, imageBuffer));
        }
 public void ApplyTextureType(TextureImporterType type, bool applyAll)
 {
     TextureImporterSettings.Internal_ApplyTextureType(this, type, applyAll);
 }
 internal static extern TextureImporterFormat[] RecommendedFormatsFromTextureTypeAndPlatform(TextureImporterType textureType, BuildTarget destinationPlatform);
 private static extern void Internal_ApplyTextureType(TextureImporterSettings s, TextureImporterType type, bool applyAll);
Esempio n. 21
0
 public void ApplyTextureType(TextureImporterType type)
 {
     Internal_ApplyTextureType(this, type);
 }
Esempio n. 22
0
            void MakeTexture(TerrainLayer layer, Texture2D texture, Vector4 min, Vector4 max, DisposableList <WorkingTexture> results)
            {
                bool linear = !GraphicsFormatUtility.IsSRGBFormat(texture.graphicsFormat);

                var offset = layer.tileOffset;
                var size   = layer.tileSize;

                if (!linear)
                {
                    min.x = Mathf.Pow(min.x, 0.45f);
                    min.y = Mathf.Pow(min.y, 0.45f);
                    min.z = Mathf.Pow(min.z, 0.45f);

                    max.x = Mathf.Pow(max.x, 0.45f);
                    max.y = Mathf.Pow(max.y, 0.45f);
                    max.z = Mathf.Pow(max.z, 0.45f);
                }


                //make to texture readable.
                var assetImporter        = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture));
                var textureImporter      = assetImporter as TextureImporter;
                TextureImporterType type = TextureImporterType.Default;

                if (textureImporter)
                {
                    type = textureImporter.textureType;
                    textureImporter.isReadable  = true;
                    textureImporter.textureType = TextureImporterType.Default;
                    textureImporter.SaveAndReimport();
                }

                try
                {
                    for (int i = 0; i < texture.mipmapCount; ++i)
                    {
                        int            width          = texture.width >> i;
                        int            height         = texture.height >> i;
                        WorkingTexture workingTexture = new WorkingTexture(Allocator.Persistent, texture.format, width, height, linear);
                        Color[]        colors         = texture.GetPixels(i);
                        for (int y = 0; y < height; ++y)
                        {
                            for (int x = 0; x < width; ++x)
                            {
                                workingTexture.SetPixel(x, y, colors[y * width + x]);
                            }
                        }

                        RemapTexture(workingTexture, min, max);
                        results.Add(workingTexture);
                    }
                }
                finally
                {
                    if (textureImporter)
                    {
                        textureImporter.isReadable  = false;
                        textureImporter.textureType = type;
                        textureImporter.SaveAndReimport();
                    }
                }
            }
 public void ApplyTextureType(TextureImporterType type, bool applyAll)
 {
     Internal_ApplyTextureType(this, type);
 }
 public TextureModification(TextureImporter importer)
 {
     this.importer = importer;
     this.origReadable = importer.isReadable;
     this.origType = importer.textureType;
     this.origFormat = importer.textureFormat;
     this.origNormalMap = importer.normalmap;
     this.origConvertToNormalmap = importer.convertToNormalmap;
 }
	public TextureImportSettings()
	{
		textureFormat = TextureImporterFormat.AutomaticTruecolor;
		maxTextureSize = (int)TextureSize.Unlimited;
		grayscaleToAlpha = false;
		generateCubemap = TextureImporterGenerateCubemap.None;
		isReadable = false;
		mipmapEnabled = true;
		borderMipmap = false;
		mipmapFilter = TextureImporterMipFilter.BoxFilter;
		fadeout = false;
		mipmapFadeDistanceStart = 1;
		mipmapFadeDistanceEnd = 1;
		generateMipsInLinearSpace = false;
		normalmapFilter = TextureImporterNormalFilter.Standard;
		heightmapScale = 0.25f;
		anisoLevel = 1;
		filterMode = FilterMode.Bilinear;
		wrapMode = TextureWrapMode.Repeat;
		textureType = TextureImporterType.Image;
	}
Esempio n. 26
0
 internal static extern TextureImporterFormat SimpleToFullTextureFormat2(TextureImporterFormat simpleFormat, TextureImporterType tType, TextureImporterSettings settings, bool doesTextureContainAlpha, bool sourceWasHDR, BuildTarget destinationPlatform);
		public void ApplyTextureType(TextureImporterType type, bool applyAll)
		{
			TextureImporterSettings.Internal_ApplyTextureType(this, type, applyAll);
		}
	 static void SelectedChangeTextureTypeSettings(TextureImporterType newType) {
 
        Object[] textures = GetSelectedTextures();
        Selection.objects = new Object[0];
        foreach (Texture2D texture in textures)  {
            string path = AssetDatabase.GetAssetPath(texture);
            //Debug.Log("path: " + path);
            TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
            textureImporter.textureType = newType; 
            AssetDatabase.ImportAsset(path);
        }
    }
Esempio n. 29
0
 internal static extern TextureImporterFormat SimpleToFullTextureFormat2(TextureImporterFormat simpleFormat, TextureImporterType tType, TextureImporterSettings settings, bool doesTextureContainAlpha, bool sourceWasHDR, BuildTarget destinationPlatform);
Esempio n. 30
0
        public static void DoActionForTextures(ref Texture2D[] texs, Action <Texture2D[]> action)
        {
            bool[] readables = new bool[texs.Length];
            TextureImporterType[]        types   = new TextureImporterType[texs.Length];
            TextureImporterCompression[] formats = new TextureImporterCompression[texs.Length];
            bool[] convertToNormalmaps           = new bool[texs.Length];

            int i = 0;

            foreach (var tex in texs)
            {
                TextureImporter im = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(tex)) as TextureImporter;
                if (!im)
                {
                    continue;
                }

                readables[i]           = im.isReadable;
                formats[i]             = im.textureCompression;
                types[i]               = im.textureType;
                convertToNormalmaps[i] = im.convertToNormalmap;

                if (!readables[i])
                {
                    im.isReadable = true;
                }
                if (types[i] != TextureImporterType.Default)
                {
                    im.textureType = TextureImporterType.Default;
                }

                im.textureCompression = TextureImporterCompression.Uncompressed;
                im.SaveAndReimport();

                i += 1;
            }


            action(texs);

            i = 0;
            foreach (var tex in texs)
            {
                TextureImporter im = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(tex)) as TextureImporter;
                if (!readables[i])
                {
                    im.isReadable = false;
                }
                if (types[i] != TextureImporterType.Default)
                {
                    im.textureType = types[i];
                }
                if (convertToNormalmaps[i])
                {
                    im.convertToNormalmap = true;
                }

                im.textureCompression = formats[i];
                im.SaveAndReimport();
                i += 1;
            }
        }