Пример #1
0
        public static Enum_TextureImporterNPOTScale ConvertTextureImporterNPOTScale(TextureImporterNPOTScale type)
        {
            var result = (Enum_TextureImporterNPOTScale)(-1);

            switch (type)
            {
            case TextureImporterNPOTScale.None:
                result = Enum_TextureImporterNPOTScale.None;
                break;

            case TextureImporterNPOTScale.ToNearest:
                result = Enum_TextureImporterNPOTScale.ToNearest;
                break;

            case TextureImporterNPOTScale.ToLarger:
                result = Enum_TextureImporterNPOTScale.ToLarger;
                break;

            case TextureImporterNPOTScale.ToSmaller:
                result = Enum_TextureImporterNPOTScale.ToSmaller;
                break;

            default:
                throw new NotImplementedException();
            }
            return(result);
        }
Пример #2
0
        public static void SetTextureInfo(TextureImporterType textureType, bool alphaIsTransparency,
                                          TextureImporterNPOTScale npotScale, TextureWrapMode wrapMode, int textureSize,
                                          Action <UnityEditor.TextureImporter> customAction)
        {
            Texture[] selections = Selection.GetFiltered <Texture>(SelectionMode.Assets);
            if (selections == null || selections.Length == 0)
            {
                Debug.Log("Please select some assets first");
                return;
            }

            foreach (var asset in selections)
            {
                string path = AssetDatabase.GetAssetPath(asset);
                UnityEditor.TextureImporter tex = UnityEditor.TextureImporter.GetAtPath(path) as UnityEditor.TextureImporter;
                tex.textureType         = textureType;
                tex.alphaIsTransparency = alphaIsTransparency;
                tex.npotScale           = npotScale;
                tex.wrapMode            = wrapMode;
                tex.maxTextureSize      = textureSize;

                customAction?.Invoke(tex);

                AssetDatabase.ImportAsset(path);
                Debug.Log($"TextureImporter  {path}");
            }
        }
Пример #3
0
 public TextureAssetSettings(XmlTextReader reader)
 {
     if (reader.MoveToAttribute("path"))
     {
         path = reader.Value;
     }
     while (reader.Read())
     {
         if (reader.NodeType == XmlNodeType.EndElement && reader.Name == "TextureAsset")
         {
             reader.ReadEndElement();
             break;
         }
         if (reader.NodeType == XmlNodeType.Element && reader.Name == "maxSize")
         {
             maxSize = int.Parse(reader.ReadInnerXml());
         }
         else if (reader.NodeType == XmlNodeType.Element && reader.Name == "format")
         {
             format = (TextureImporterFormat)System.Enum.Parse(typeof(TextureImporterFormat), reader.ReadInnerXml());
         }
         else if (reader.NodeType == XmlNodeType.Element && reader.Name == "mipmaps")
         {
             mipmaps = bool.Parse(reader.ReadInnerXml());
         }
         else if (reader.NodeType == XmlNodeType.Element && reader.Name == "npotScale")
         {
             npotScale = (TextureImporterNPOTScale)System.Enum.Parse(typeof(TextureImporterNPOTScale), reader.ReadInnerXml());
         }
     }
 }
Пример #4
0
    // ----------------------------------------------------------------------------------
    public static Texture2D CloneAtlasTexture(Texture tex)
    {
        string                   texturePath   = AssetDatabase.GetAssetPath(tex);
        TextureImporter          importer      = (TextureImporter)TextureImporter.GetAtPath(texturePath);
        bool                     bReadable     = importer.isReadable;
        int                      maxTexSize    = importer.maxTextureSize;
        TextureImporterFormat    textureFormat = importer.textureFormat;
        TextureImporterNPOTScale npotScale     = importer.npotScale;

        Texture2D srcTex = (Texture2D)AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D));

        SetSourceTexture(srcTex);
        Texture2D tarTex = new Texture2D(srcTex.width, srcTex.height, TextureFormat.ARGB32, false);

        Color[] colBuf = srcTex.GetPixels(0);
        tarTex.SetPixels(colBuf, 0);
        tarTex.Apply(false);

        // Restore
        importer.isReadable     = bReadable;
        importer.maxTextureSize = maxTexSize;
        importer.textureFormat  = textureFormat;
        importer.npotScale      = npotScale;
        AssetDatabase.ImportAsset(texturePath, ImportAssetOptions.ForceSynchronousImport);

        return(tarTex);
    }
 public static void SelectedChangeNonPowerOf2(TextureImporterNPOTScale scale)
 {
     Object[] textures = GetSelectedTextures();
     foreach (Texture2D tex in textures)
     {
         SetTexNonPowerOf2(tex, scale);
     }
 }
        public static void SetTexNonPowerOf2(Texture2D tex, TextureImporterNPOTScale scale)
        {
            string          path   = AssetDatabase.GetAssetPath(tex);
            TextureImporter teximp = AssetImporter.GetAtPath(path) as TextureImporter;

            teximp.npotScale = scale;
            AssetDatabase.ImportAsset(path);
        }
    static void SelectedChangeNonePowerOfTwo(TextureImporterNPOTScale newScale) {
 
        Object[] textures = GetSelectedTextures();
        foreach (Texture2D texture in textures)  {
            string path = AssetDatabase.GetAssetPath(texture);
            TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
            textureImporter.npotScale = newScale; 
            AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate );
        }
    } 
Пример #8
0
    public TextureImporterNPOTScale NpotScaleSetup()
    {
        TextureImporterNPOTScale t = new TextureImporterNPOTScale();

        if(TextureImporterSetting.npotIndex == 0) t = TextureImporterNPOTScale.None;
        if(TextureImporterSetting.npotIndex == 1) t = TextureImporterNPOTScale.ToLarger;
        if(TextureImporterSetting.npotIndex == 2) t = TextureImporterNPOTScale.ToNearest;
        if(TextureImporterSetting.npotIndex == 3) t = TextureImporterNPOTScale.ToSmaller;

        return t;
    }
 static void SelectedChangeNonPowerOf2(TextureImporterNPOTScale npot)
 {
     Object[] textures = GetSelectedTextures();
     Selection.objects = new Object[0];
     foreach (Texture2D texture in textures)
     {
         string          path            = AssetDatabase.GetAssetPath(texture);
         TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
         textureImporter.npotScale = npot;
         AssetDatabase.ImportAsset(path);
     }
 }
Пример #10
0
    private static bool SetNpotScale(TextureImporter im, TextureImporterNPOTScale npotScale)
    {
        bool rt = false;

        if (im.npotScale != npotScale)
        {
            rt           = true;
            im.npotScale = npotScale;
            Debug.Log("SetNpotScale succ:" + im.assetPath + " " + npotScale);
        }
        return(rt);
    }
Пример #11
0
 // Token: 0x060003EB RID: 1003 RVA: 0x00034CDC File Offset: 0x00032EDC
 public static int GetPOTSize(int size, TextureImporterNPOTScale scale)
 {
     if (scale == null)
     {
         return(size);
     }
     if ((int)scale == 3)
     {
         for (int i = 1; i < 16; i++)
         {
             int num = 1 << i;
             if (size < num)
             {
                 return(1 << i - 1);
             }
         }
     }
     if ((int)scale == 2)
     {
         for (int j = 1; j < 16; j++)
         {
             int num2 = 1 << j;
             if (size <= num2)
             {
                 return(num2);
             }
         }
     }
     if ((int)scale == 1)
     {
         int k = 1;
         while (k < 16)
         {
             int num3 = 1 << k - 1;
             int num4 = 1 << k;
             if (size > num3 && size <= num4)
             {
                 int num5 = size - num3;
                 int num6 = num4 - size;
                 if (num5 < num6)
                 {
                     return(num3);
                 }
                 return(num4);
             }
             else
             {
                 k++;
             }
         }
     }
     return(size);
 }
        static void SelectedChangeNonPowerOf2(TextureImporterNPOTScale npot)
        {
            var textures = GetSelectedTextures();

            Selection.objects = new Object[0];
            foreach (var o in textures)
            {
                var texture         = (Texture2D)o;
                var path            = AssetDatabase.GetAssetPath(texture);
                var textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
                Debug.Assert(textureImporter != null, "textureImporter != null");
                textureImporter.npotScale = npot;
                AssetDatabase.ImportAsset(path);
            }
        }
        public override void ApplyDefaults()
        {
            this.RuleName     = "New Texture Rule";
            this.SuffixFilter = ".png";

            textureType = TextureImporterType.Default;

            isReadable           = false;
            mipmapEnabled        = false;
            allowsAlphaSplitting = false;
            npotScale            = TextureImporterNPOTScale.None;

            wrapMode   = TextureWrapMode.Clamp;
            filterMode = FilterMode.Bilinear;

            textureCompression = TextureImporterCompression.Compressed;
        }
    public override void ReadFromAsset(Object asset)
    {
        if (!(asset is Texture2D))
        {
            Debug.Log("Asset isn't a Texture2D. Can't read from asset");
            return;
        }

        Texture2D texture = asset as Texture2D;

        name = texture.name;

        TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter;

        if (textureImporter == null)
        {
            Debug.Log("Could not get texture importer for asset at path: " + AssetDatabase.GetAssetPath(texture));
            return;
        }

        guid = AssetDatabase.AssetPathToGUID(textureImporter.assetPath);

        anisoLevel                = textureImporter.anisoLevel;
        borderMipmap              = textureImporter.borderMipmap;
        convertToNormalmap        = textureImporter.convertToNormalmap;
        generateMipsInLinearSpace = textureImporter.generateMipsInLinearSpace;
        fadeout                 = textureImporter.fadeout;
        filterMode              = textureImporter.filterMode;
        generateCubemap         = textureImporter.generateCubemap;
        grayscaleToAlpha        = textureImporter.grayscaleToAlpha;
        heightmapScale          = textureImporter.heightmapScale;
        isReadable              = textureImporter.isReadable;
        lightmap                = textureImporter.lightmap;
        maxTextureSize          = textureImporter.maxTextureSize;
        mipMapBias              = textureImporter.mipMapBias;
        mipmapEnabled           = textureImporter.mipmapEnabled;
        mipmapFadeDistanceEnd   = textureImporter.mipmapFadeDistanceEnd;
        mipmapFadeDistanceStart = textureImporter.mipmapFadeDistanceStart;
        mipmapFilter            = textureImporter.mipmapFilter;
        normalmap               = textureImporter.normalmap;
        normalmapFilter         = textureImporter.normalmapFilter;
        npotScale               = textureImporter.npotScale;
        textureFormat           = textureImporter.textureFormat;
        textureType             = textureImporter.textureType;
        wrapMode                = textureImporter.wrapMode;
    }
Пример #15
0
    private void Revert()
    {
        textureType         = TextureImporterType.Image;
        grayscaleToAlpha    = false;
        alphaIsTransparency = false;
        wrapMode            = TextureWrapMode.Repeat;
        filterMode          = FilterMode.Bilinear;
        anisoLevel          = 1;
        createFromGrayscale = true;
        bumpiness           = 0.25f;
        filtering           = 0;
        spriteMode          = SpriteImportMode.Single;
        packingTag          = "";
        pixelsToUnits       = 100;
        meshType            = SpriteMeshType.Tight;
        extrudeEdges        = 1;
        pivot              = 505;
        pivotX             = 0.5f;
        pivotY             = 0.5f;
        mapping            = 4;
        fixupEdgeSeams     = false;
        lightType          = LightType.Spot;
        nonPowerOf2        = TextureImporterNPOTScale.ToNearest;
        generateCubemap    = TextureImporterGenerateCubemap.None;
        readWriteEnabled   = false;
        importType         = 0;
        bypassSRGBSampling = false;
        generateMipMaps    = true;
        inLinearSpace      = false;
        borderMipMaps      = false;
        mipMapFiltering    = TextureImporterMipFilter.BoxFilter;
        fadeoutMipMaps     = false;
        fadeoutMin         = 1;
        fadeoutMax         = 3;

        for (int i = 0, length = textureFormats.Length; i < length; i++)
        {
            textureFormats[i] = TextureImporterFormat.AutomaticCompressed;
        }
        for (int i = 0, length = compressionQualitys.Length; i < length; i++)
        {
            compressionQualitys[i] = (int)TextureCompressionQuality.Normal;
        }
    }
 public void Apply(TextureImporterSettings settings)
 {
     this.seamlessCubemap                    = settings.seamlessCubemap;
     this.mipmapBias                         = settings.mipmapBias;
     this.wrapMode                           = settings.wrapMode;
     this.wrapModeU                          = settings.wrapModeU;
     this.wrapModeV                          = settings.wrapModeV;
     this.wrapModeW                          = settings.wrapModeW;
     this.alphaIsTransparency                = settings.alphaIsTransparency;
     this.spriteMode                         = settings.spriteMode;
     this.spritePixelsPerUnit                = settings.spritePixelsPerUnit;
     this.spriteTessellationDetail           = settings.spriteTessellationDetail;
     this.spriteExtrude                      = settings.spriteExtrude;
     this.spriteMeshType                     = settings.spriteMeshType;
     this.spriteAlignment                    = settings.spriteAlignment;
     this.spritePivot                        = settings.spritePivot;
     this.spriteBorder                       = settings.spriteBorder;
     this.spriteGenerateFallbackPhysicsShape = settings.spriteGenerateFallbackPhysicsShape;
     this.aniso                    = settings.aniso;
     this.filterMode               = settings.filterMode;
     this.cubemapConvolution       = settings.cubemapConvolution;
     this.textureType              = settings.textureType;
     this.textureShape             = settings.textureShape;
     this.mipmapFilter             = settings.mipmapFilter;
     this.mipmapEnabled            = settings.mipmapEnabled;
     this.sRGBTexture              = settings.sRGBTexture;
     this.fadeOut                  = settings.fadeOut;
     this.borderMipmap             = settings.borderMipmap;
     this.mipMapsPreserveCoverage  = settings.mipMapsPreserveCoverage;
     this.mipmapFadeDistanceStart  = settings.mipmapFadeDistanceStart;
     this.alphaTestReferenceValue  = settings.alphaTestReferenceValue;
     this.convertToNormalMap       = settings.convertToNormalMap;
     this.heightmapScale           = settings.heightmapScale;
     this.normalMapFilter          = settings.normalMapFilter;
     this.alphaSource              = settings.alphaSource;
     this.singleChannelComponent   = settings.singleChannelComponent;
     this.readable                 = settings.readable;
     this.streamingMipmaps         = settings.streamingMipmaps;
     this.streamingMipmapsPriority = settings.streamingMipmapsPriority;
     this.npotScale                = settings.npotScale;
     this.generateCubemap          = settings.generateCubemap;
     this.mipmapFadeDistanceEnd    = settings.mipmapFadeDistanceEnd;
 }
Пример #17
0
    private void DisplayAdvancedSettings()
    {
        GUILayout.Label("Advanced Settings", EditorStyles.miniBoldLabel);

        EditorGUI.indentLevel++;

        nonPowerofTwo    = (TextureImporterNPOTScale)EditorGUILayout.EnumPopup("Non Power of 2", nonPowerofTwo);
        readWriteEnabled = EditorGUILayout.Toggle("Read/Write Enabled", readWriteEnabled);
        generateMipMaps  = EditorGUILayout.Toggle("Generate Mip Maps", generateMipMaps);
        if (generateMipMaps)
        {
            EditorGUI.indentLevel++;
            borderMipMaps   = EditorGUILayout.Toggle("Border Mip Maps", borderMipMaps);
            mipMapFiltering = (TextureImporterMipFilter)EditorGUILayout.EnumPopup("Mip Map Filtering", mipMapFiltering);
            fadeoutMipMaps  = EditorGUILayout.Toggle("Fadeout Mip Maps", fadeoutMipMaps);
            EditorGUI.indentLevel--;
        }
        EditorGUI.indentLevel--;
    }
 public TextureAssetSettings(XmlTextReader reader)
 {
     if(reader.MoveToAttribute("path"))
         path = reader.Value;
     while(reader.Read()) {
         if(reader.NodeType == XmlNodeType.EndElement && reader.Name == "TextureAsset") {
             reader.ReadEndElement();
             break;
         }
         if(reader.NodeType == XmlNodeType.Element && reader.Name == "maxSize") {
             maxSize = int.Parse(reader.ReadInnerXml());
         } else if(reader.NodeType == XmlNodeType.Element && reader.Name == "format") {
             format = (TextureImporterFormat) System.Enum.Parse(typeof(TextureImporterFormat), reader.ReadInnerXml());
         } else if(reader.NodeType == XmlNodeType.Element && reader.Name == "mipmaps") {
             mipmaps = bool.Parse(reader.ReadInnerXml());
         } else if(reader.NodeType == XmlNodeType.Element && reader.Name == "npotScale") {
             npotScale = (TextureImporterNPOTScale) System.Enum.Parse(typeof(TextureImporterNPOTScale), reader.ReadInnerXml());
         }
     }
 }
Пример #19
0
        // Token: 0x060003E0 RID: 992 RVA: 0x00034AB4 File Offset: 0x00032CB4
        public static string GetNPOTScaleString(TextureImporterNPOTScale value)
        {
            switch ((int)value)
            {
            case 0:
                return("None");

            case 1:
                return("To Nearest");

            case 2:
                return("To Larger");

            case 3:
                return("To Smaller");

            default:
                return(value.ToString());
            }
        }
        public override void ApplyDefaults()
        {
            this.RuleKey = "New Texture Rule";
            this.Suffix  = ".png";

            TextureType = TextureImporterType.Default;

            IsReadable           = false;
            IsMipmap             = false;
            allowsAlphaSplitting = false;
            NpotScale            = TextureImporterNPOTScale.None;

            WrapMode   = TextureWrapMode.Clamp;
            FilterMode = FilterMode.Bilinear;

            Compression           = TextureImporterCompression.Compressed;
            AndroidCompressFormat = TextureImporterFormat.ETC2_RGBA8;
            iOSCompressFormat     = TextureImporterFormat.PVRTC_RGBA4;
            CompressionQuality    = TextureCompressionQuality.Best;
        }
Пример #21
0
    public void ReImportAsset(string path, int maxSize, bool alphaIsTransparency = false,
                              TextureImporterFormat androidFormat = TextureImporterFormat.Automatic,
                              TextureImporterFormat iosFormat     = TextureImporterFormat.Automatic,
                              TextureImporterNPOTScale npotScale  = TextureImporterNPOTScale.ToNearest)
    {
        var importer = AssetImporter.GetAtPath(path) as TextureImporter;

#if UNITY_5_5_OR_NEWER
        importer.textureType        = TextureImporterType.Default;
        importer.textureCompression = TextureImporterCompression.CompressedHQ;
#else
        importer.textureType   = TextureImporterType.Image;
        importer.textureFormat = TextureImporterFormat.AutomaticCompressed;
#endif

        importer.textureShape        = TextureImporterShape.Texture2D;
        importer.anisoLevel          = 0;
        importer.spriteImportMode    = SpriteImportMode.None;
        importer.filterMode          = FilterMode.Bilinear;
        importer.wrapMode            = TextureWrapMode.Clamp;
        importer.mipmapEnabled       = false;
        importer.maxTextureSize      = maxSize;
        importer.isReadable          = false;
        importer.alphaSource         = TextureImporterAlphaSource.None;
        importer.alphaIsTransparency = alphaIsTransparency;
        importer.compressionQuality  = (int)TextureCompressionQuality.Normal;
        importer.npotScale           = npotScale;

#if UNITY_5_5_OR_NEWER
        importer.SetPlatformTextureSettings(CreateTexPlatformSettings("iphone", maxSize, iosFormat));
        importer.SetPlatformTextureSettings(CreateTexPlatformSettings("Android", maxSize, androidFormat));
#else
        importer.SetPlatformTextureSettings("iPhone", maxSize, iosFormat);
        importer.SetPlatformTextureSettings("Android", maxSize, androidFormat);
#endif

        AssetDatabase.ImportAsset(path);
    }
Пример #22
0
    public TextureImporterNPOTScale NpotScaleSetup()
    {
        TextureImporterNPOTScale t = new TextureImporterNPOTScale();

        if (TextureImporterSetting.npotIndex == 0)
        {
            t = TextureImporterNPOTScale.None;
        }
        if (TextureImporterSetting.npotIndex == 1)
        {
            t = TextureImporterNPOTScale.ToLarger;
        }
        if (TextureImporterSetting.npotIndex == 2)
        {
            t = TextureImporterNPOTScale.ToNearest;
        }
        if (TextureImporterSetting.npotIndex == 3)
        {
            t = TextureImporterNPOTScale.ToSmaller;
        }

        return(t);
    }
Пример #23
0
    private void OnGUI()
    {
        Texturetype = (TextureImporterType)EditorGUILayout.EnumPopup("Texture Type", Texturetype);
        switch (Texturetype)
        {
        case TextureImporterType.Default:
            TexShape              = (TextureImporterShape)EditorGUILayout.EnumPopup("Texture Shape", TexShape);
            IsSrgb                = EditorGUILayout.Toggle("sRGB(Color Texture)", IsSrgb);
            AlphaSource           = (TextureImporterAlphaSource)EditorGUILayout.EnumPopup("Alpha Source", AlphaSource);
            IsAlphaIsTransparency = EditorGUILayout.Toggle("Alpha Is Transparency", IsAlphaIsTransparency);
            NpotScale             = (TextureImporterNPOTScale)EditorGUILayout.EnumPopup("Non Power of 2", NpotScale);
            IsRead                = EditorGUILayout.Toggle("Read/Write Enabled", IsRead);
            IsStreamingMipMap     = EditorGUILayout.Toggle("Streaming Mip Maps", IsStreamingMipMap);
            IsGenerateMipmap      = EditorGUILayout.Toggle("Generate Mip Maps", IsGenerateMipmap);
            DefalutWarpMode       = (TextureWrapMode)EditorGUILayout.EnumPopup("Wrap Mode", DefalutWarpMode);
            MaxSize               = (MaxSize)EditorGUILayout.EnumPopup("Max Size", MaxSize);
            Compression           = (TextureImporterCompression)EditorGUILayout.EnumPopup("Compression", Compression);
            break;

        case TextureImporterType.NormalMap:
            break;

        case TextureImporterType.GUI:
            break;

        case TextureImporterType.Sprite:
            SpriteImportMode      = (SpriteImportMode)EditorGUILayout.EnumPopup("Sprite Mode", SpriteImportMode);
            PackingTag            = EditorGUILayout.TextField("Packing Tag", PackingTag);
            IsSrgb                = EditorGUILayout.Toggle("sRGB(Color Texture)", IsSrgb);
            AlphaSource           = (TextureImporterAlphaSource)EditorGUILayout.EnumPopup("Alpha Source", AlphaSource);
            IsAlphaIsTransparency = EditorGUILayout.Toggle("Alpha Is Transparency", IsAlphaIsTransparency);
            IsRead                = EditorGUILayout.Toggle("Read/Write Enabled", IsRead);
            IsGenerateMipmap      = EditorGUILayout.Toggle("Generate Mip Maps", IsGenerateMipmap);
            SpriteWarpMode        = (TextureWrapMode)EditorGUILayout.EnumPopup("Wrap Mode", SpriteWarpMode);
            MaxSize               = (MaxSize)EditorGUILayout.EnumPopup("Max Size", MaxSize);
            Compression           = (TextureImporterCompression)EditorGUILayout.EnumPopup("Compression", Compression);
            break;

        case TextureImporterType.Cursor:
            break;

        case TextureImporterType.Cookie:
            break;

        case TextureImporterType.Lightmap:
            break;

        case TextureImporterType.SingleChannel:
            break;
        }
        if (GUILayout.Button("设置图片属性后、导入或修改前,请点击本按钮!"))
        {
            IsApply = true;
            Debug.Log("已应用设置");
        }
        if (GUILayout.Button("还原设置: 请点击本按钮 或者 直接关闭面板 !"))
        {
            IsApply = false;
            Debug.Log("已还原设置");
        }
    }
	static void SelectedChangeNonPowerOf2(TextureImporterNPOTScale npot) {
		
		Object[] textures = GetSelectedTextures();
		Selection.objects = new Object[0];
		foreach (Texture2D texture in textures)  {
			string path = AssetDatabase.GetAssetPath(texture);
			TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
			textureImporter.npotScale = npot;   
			AssetDatabase.ImportAsset(path);
		}
	}
        // 個々の要素をシングルタイプスプライトして書き出す
        private void OutputDividedSprite(Texture2D tAtlas, string tFolderPath)
        {
            if (string.IsNullOrEmpty(tFolderPath) == true)
            {
                return;
            }

            if (Directory.Exists(tFolderPath) == false)
            {
                return;
            }

            int l = tFolderPath.Length;

            if (tFolderPath[l - 1] != '/')
            {
                tFolderPath = tFolderPath + '/';
            }

            //----------------------------------------------------------

            // アトラススプライトを読み出し可能状態にする
            string tAtlasPath = AssetDatabase.GetAssetPath(tAtlas.GetInstanceID());

            // 元の状態を保存する
            TextureImporterCompression tAtlasFormat    = TextureImporterCompression.Uncompressed;
            TextureImporterNPOTScale   tAtlasNPOtScale = TextureImporterNPOTScale.None;

            SetTextureSetting(tAtlasPath, true, ref tAtlasFormat, ref tAtlasNPOtScale);                 // 読み込み属性を有効にする

            tAtlas = AssetDatabase.LoadAssetAtPath(tAtlasPath, typeof(Texture2D)) as Texture2D;

            TextureImporter tAtlasTextureImporter = AssetImporter.GetAtPath(tAtlasPath) as TextureImporter;
            int             x, y, w, h;

            Texture2D       tElementTexture;
            string          tElementPath;
            TextureImporter tElementTextureImporter;

            foreach (SpriteMetaData tSpriteMetaData in tAtlasTextureImporter.spritesheet)
            {
                x = ( int )tSpriteMetaData.rect.x;
                y = ( int )tSpriteMetaData.rect.y;
                w = ( int )tSpriteMetaData.rect.width;
                h = ( int )tSpriteMetaData.rect.height;

                tElementTexture = new Texture2D(w, h, TextureFormat.ARGB32, false);
                tElementTexture.SetPixels(tAtlas.GetPixels(x, y, w, h));
                tElementTexture.Apply();

                tElementPath = tFolderPath + tSpriteMetaData.name + ".png";

                // テクスチャをPNG画像として保存する
                byte[] tData = tElementTexture.EncodeToPNG();
                System.IO.File.WriteAllBytes(tElementPath, tData);
                tData = null;

                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();

                // 新規生成

                tElementTextureImporter = AssetImporter.GetAtPath(tElementPath) as TextureImporter;

                tElementTextureImporter.npotScale = TextureImporterNPOTScale.None;

                tElementTextureImporter.textureType      = TextureImporterType.Sprite;
                tElementTextureImporter.spriteImportMode = SpriteImportMode.Single;

                tElementTextureImporter.spriteBorder = tSpriteMetaData.border;
                tElementTextureImporter.spritePivot  = tSpriteMetaData.pivot;

                tElementTextureImporter.alphaIsTransparency = tAtlasTextureImporter.alphaIsTransparency;
                tElementTextureImporter.mipmapEnabled       = tAtlasTextureImporter.mipmapEnabled;
                tElementTextureImporter.wrapMode            = tAtlasTextureImporter.wrapMode;
                tElementTextureImporter.filterMode          = tAtlasTextureImporter.filterMode;
                tElementTextureImporter.textureCompression  = tAtlasTextureImporter.textureCompression;

                tElementTextureImporter.isReadable = false;                                             // 読み込み禁止

                AssetDatabase.ImportAsset(tElementPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);

                tElementTexture = null;
            }

            SetTextureSetting(tAtlasPath, false, ref tAtlasFormat, ref tAtlasNPOtScale);                // 読み込み属性を無効にする

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
Пример #26
0
 public TextureSettings(string assetPath, bool enablePostProcessor, bool colorTexture, bool readable, TextureImporterNPOTScale npotScale, FilterMode filterMode, int aniso, bool sourceContainsAlpha, bool sourceWasHDR)
 {
     this.assetPath           = assetPath;
     this.enablePostProcessor = enablePostProcessor;
     this.colorTexture        = colorTexture;
     this.readable            = readable;
     this.npotScale           = npotScale;
     this.filterMode          = filterMode;
     this.aniso         = aniso;
     this.containsAlpha = sourceContainsAlpha;
     this.hdr           = sourceWasHDR;
 }
    public TextureAsset(StreamReader reader)
    {
        string line = string.Empty;

        while ((line = reader.ReadLine()) != null)
        {
            if (line.Contains(VerySimpleXml.EndNode(nodeName)))
            {
                break;
            }

            //Name
            if (line.Contains(VerySimpleXml.StartNode(nameNodeName)))
            {
                name = VerySimpleXml.NodeValue(line, nameNodeName);
            }

            //Path
            if (line.Contains(VerySimpleXml.StartNode(pathNodeName)))
            {
                guid = AssetDatabase.AssetPathToGUID(VerySimpleXml.NodeValue(line, pathNodeName));
            }

            if (line.Contains(VerySimpleXml.StartNode(guidNodeName)))
            {
                guid = VerySimpleXml.NodeValue(line, guidNodeName);
            }

            //IMPORT SETTINGS
            if (line.Contains(VerySimpleXml.StartNode("anisoLevel")))
            {
                anisoLevel = int.Parse(VerySimpleXml.NodeValue(line, "anisoLevel"));
            }

            if (line.Contains(VerySimpleXml.StartNode("borderMipmap")))
            {
                borderMipmap = bool.Parse(VerySimpleXml.NodeValue(line, "borderMipmap"));
            }

            if (line.Contains(VerySimpleXml.StartNode("convertToNormalmap")))
            {
                convertToNormalmap = bool.Parse(VerySimpleXml.NodeValue(line, "convertToNormalmap"));
            }

            if (line.Contains(VerySimpleXml.StartNode("correctGamma")))
            {
                generateMipsInLinearSpace = bool.Parse(VerySimpleXml.NodeValue(line, "correctGamma"));
            }

            if (line.Contains(VerySimpleXml.StartNode("fadeout")))
            {
                fadeout = bool.Parse(VerySimpleXml.NodeValue(line, "fadeout"));
            }

            if (line.Contains(VerySimpleXml.StartNode("filterMode")))
            {
                filterMode = (FilterMode)System.Enum.Parse(typeof(FilterMode), VerySimpleXml.NodeValue(line, "filterMode"));
            }

            if (line.Contains(VerySimpleXml.StartNode("generateCubemap")))
            {
                generateCubemap = (TextureImporterGenerateCubemap)System.Enum.Parse(typeof(TextureImporterGenerateCubemap), VerySimpleXml.NodeValue(line, "generateCubemap"));
            }

            if (line.Contains(VerySimpleXml.StartNode("grayscaleToAlpha")))
            {
                grayscaleToAlpha = bool.Parse(VerySimpleXml.NodeValue(line, "grayscaleToAlpha"));
            }

            if (line.Contains(VerySimpleXml.StartNode("heightmapScale")))
            {
                heightmapScale = float.Parse(VerySimpleXml.NodeValue(line, "heightmapScale"));
            }

            if (line.Contains(VerySimpleXml.StartNode("isReadable")))
            {
                isReadable = bool.Parse(VerySimpleXml.NodeValue(line, "isReadable"));
            }

            if (line.Contains(VerySimpleXml.StartNode("lightmap")))
            {
                lightmap = bool.Parse(VerySimpleXml.NodeValue(line, "lightmap"));
            }

            if (line.Contains(VerySimpleXml.StartNode("maxTextureSize")))
            {
                maxTextureSize = int.Parse(VerySimpleXml.NodeValue(line, "maxTextureSize"));
            }

            if (line.Contains(VerySimpleXml.StartNode("mipMapBias")))
            {
                mipMapBias = float.Parse(VerySimpleXml.NodeValue(line, "mipMapBias"));
            }

            if (line.Contains(VerySimpleXml.StartNode("mipmapEnabled")))
            {
                mipmapEnabled = bool.Parse(VerySimpleXml.NodeValue(line, "mipmapEnabled"));
            }

            if (line.Contains(VerySimpleXml.StartNode("mipmapFadeDistanceEnd")))
            {
                mipmapFadeDistanceEnd = int.Parse(VerySimpleXml.NodeValue(line, "mipmapFadeDistanceEnd"));
            }

            if (line.Contains(VerySimpleXml.StartNode("mipmapFadeDistanceStart")))
            {
                mipmapFadeDistanceStart = int.Parse(VerySimpleXml.NodeValue(line, "mipmapFadeDistanceStart"));
            }

            if (line.Contains(VerySimpleXml.StartNode("mipmapFilter")))
            {
                mipmapFilter = (TextureImporterMipFilter)System.Enum.Parse(typeof(TextureImporterMipFilter), VerySimpleXml.NodeValue(line, "mipmapFilter"));
            }

            if (line.Contains(VerySimpleXml.StartNode("normalmap")))
            {
                normalmap = bool.Parse(VerySimpleXml.NodeValue(line, "normalmap"));
            }

            if (line.Contains(VerySimpleXml.StartNode("normalmapFilter")))
            {
                normalmapFilter = (TextureImporterNormalFilter)System.Enum.Parse(typeof(TextureImporterNormalFilter), VerySimpleXml.NodeValue(line, "normalmapFilter"));
            }

            if (line.Contains(VerySimpleXml.StartNode("npotScale")))
            {
                npotScale = (TextureImporterNPOTScale)System.Enum.Parse(typeof(TextureImporterNPOTScale), VerySimpleXml.NodeValue(line, "npotScale"));
            }

            if (line.Contains(VerySimpleXml.StartNode("textureFormat")))
            {
                textureFormat = (TextureImporterFormat)System.Enum.Parse(typeof(TextureImporterFormat), VerySimpleXml.NodeValue(line, "textureFormat"));
            }

            if (line.Contains(VerySimpleXml.StartNode("textureType")))
            {
                textureType = (TextureImporterType)System.Enum.Parse(typeof(TextureImporterType), VerySimpleXml.NodeValue(line, "textureType"));
            }

            if (line.Contains(VerySimpleXml.StartNode("wrapMode")))
            {
                wrapMode = (TextureWrapMode)System.Enum.Parse(typeof(TextureWrapMode), VerySimpleXml.NodeValue(line, "wrapMode"));
            }
        }
    }
        static void SelectedChangeNonPowerOf2(TextureImporterNPOTScale npot)
        {

            var textures = GetSelectedTextures();
            Selection.objects = new Object[0];
            foreach (var o in textures)
            {
                var texture = (Texture2D) o;
                var path = AssetDatabase.GetAssetPath(texture);
                var textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
                Debug.Assert(textureImporter != null, "textureImporter != null");
                textureImporter.npotScale = npot;
                AssetDatabase.ImportAsset(path);
            }
        }
Пример #29
0
    private void Reset()
    {
        switch (textureType)
        {
        case TextureImporterType.Image:
            grayscaleToAlpha    = false;
            alphaIsTransparency = false;
            for (int i = 0, length = textureFormats.Length; i < length; i++)
            {
                maxTextureSize[i] = 5;
                textureFormats[i] = TextureImporterFormat.AutomaticCompressed;
            }
            break;

        case TextureImporterType.Bump:
            createFromGrayscale = true;
            for (int i = 0, length = textureFormats.Length; i < length; i++)
            {
                maxTextureSize[i] = 5;
                textureFormats[i] = TextureImporterFormat.AutomaticCompressed;
            }
            break;

        case TextureImporterType.GUI:
            spriteMode = SpriteImportMode.Single;
            for (int i = 0, length = textureFormats.Length; i < length; i++)
            {
                maxTextureSize[i] = 5;
                textureFormats[i] = TextureImporterFormat.AutomaticCompressed;
            }
            break;

        case TextureImporterType.Sprite:
            for (int i = 0, length = textureFormats.Length; i < length; i++)
            {
                maxTextureSize[i] = 5;
                textureFormats[i] = TextureImporterFormat.AutomaticCompressed;
            }
            break;

        case TextureImporterType.Cursor:
            for (int i = 0, length = textureFormats.Length; i < length; i++)
            {
                maxTextureSize[i] = 5;
                textureFormats[i] = TextureImporterFormat.AutomaticCompressed;
            }
            break;

        case TextureImporterType.Reflection:
            for (int i = 0, length = textureFormats.Length; i < length; i++)
            {
                maxTextureSize[i] = 5;
                textureFormats[i] = TextureImporterFormat.AutomaticCompressed;
            }
            mapping        = 4;
            fixupEdgeSeams = false;
            break;

        case TextureImporterType.Cookie:
            for (int i = 0, length = textureFormats.Length; i < length; i++)
            {
                maxTextureSize[i] = 5;
                textureFormats[i] = TextureImporterFormat.Alpha8;
            }
            lightType           = LightType.Spot;
            mapping             = 2;
            fixupEdgeSeams      = false;
            grayscaleToAlpha    = false;
            alphaIsTransparency = false;
            break;

        case TextureImporterType.Lightmap:
            for (int i = 0, length = textureFormats.Length; i < length; i++)
            {
                maxTextureSize[i] = 5;
                textureFormats[i] = TextureImporterFormat.AutomaticCompressed;
            }
            break;

        case TextureImporterType.Advanced:
            nonPowerOf2         = 0;
            readWriteEnabled    = false;
            importType          = 0;
            grayscaleToAlpha    = false;
            alphaIsTransparency = false;
            bypassSRGBSampling  = false;
            spriteMode          = SpriteImportMode.None;
            generateMipMaps     = true;
            inLinearSpace       = false;
            borderMipMaps       = false;
            for (int i = 0, length = textureFormats.Length; i < length; i++)
            {
                maxTextureSize[i] = 5;
            }
            textureFormats[8] = TextureImporterFormat.AutomaticCompressed;
            textureFormats[0] = TextureImporterFormat.DXT5;
            textureFormats[1] = TextureImporterFormat.DXT5;
            textureFormats[2] = TextureImporterFormat.PVRTC_RGBA4;
            textureFormats[3] = TextureImporterFormat.RGBA16;
            textureFormats[4] = TextureImporterFormat.RGBA16;
            textureFormats[5] = TextureImporterFormat.DXT5;
            textureFormats[6] = TextureImporterFormat.DXT5;
            textureFormats[7] = TextureImporterFormat.DXT5;
            break;
        }
    }
    public override void ApplyCopiedValues(string[] properties, object[] values)
    {
        for (int i = 0; i < properties.Length; i++)
        {
            string property = properties[i];

            if (property == "anisoLevel")
            {
                anisoLevel = (int)values[i];
            }
            if (property == "borderMipmap")
            {
                borderMipmap = (bool)values[i];
            }
            if (property == "convertToNormalmap")
            {
                convertToNormalmap = (bool)values[i];
            }
            if (property == "correctGamma")
            {
                generateMipsInLinearSpace = (bool)values[i];
            }
            if (property == "fadeout")
            {
                fadeout = (bool)values[i];
            }
            if (property == "filterMode")
            {
                filterMode = (FilterMode)values[i];
            }
            ;
            if (property == "generateCubemap")
            {
                generateCubemap = (TextureImporterGenerateCubemap)values[i];
            }
            if (property == "grayscaleToAlpha")
            {
                grayscaleToAlpha = (bool)values[i];
            }
            if (property == "heightmapScale")
            {
                heightmapScale = (float)values[i];
            }
            if (property == "isReadable")
            {
                isReadable = (bool)values[i];
            }
            if (property == "lightmap")
            {
                lightmap = (bool)values[i];
            }
            if (property == "maxTextureSize")
            {
                maxTextureSize = (int)values[i];
            }
            if (property == "mipMapBias")
            {
                mipMapBias = (float)values[i];
            }
            if (property == "mipmapEnabled")
            {
                mipmapEnabled = (bool)values[i];
            }
            if (property == "mipmapFadeDistanceEnd")
            {
                mipmapFadeDistanceEnd = (int)values[i];
            }
            if (property == "mipmapFadeDistanceStart")
            {
                mipmapFadeDistanceStart = (int)values[i];
            }
            if (property == "mipmapFilter")
            {
                mipmapFilter = (TextureImporterMipFilter)values[i];
            }
            if (property == "normalmap")
            {
                normalmap = (bool)values[i];
            }
            if (property == "normalmapFilter")
            {
                normalmapFilter = (TextureImporterNormalFilter)values[i];
            }
            if (property == "npotScale")
            {
                npotScale = (TextureImporterNPOTScale)values[i];
            }
            if (property == "textureFormat")
            {
                textureFormat = (TextureImporterFormat)values[i];
            }
            if (property == "textureType")
            {
                textureType = (TextureImporterType)values[i];
            }
            if (property == "wrapMode")
            {
                wrapMode = (TextureWrapMode)values[i];
            }
        }
    }
    void _Process()
    {
        Texture2D texture = _texture as Texture2D;

        if (texture == null)
        {
            Debug.LogError("Texture is not Texture2D.");
            return;
        }

        string                   assetPath                = AssetDatabase.GetAssetPath(texture);
        TextureImporter          textureImporter          = (TextureImporter)TextureImporter.GetAtPath(assetPath);
        bool                     overrideTextureFormat    = false;
        bool                     overrideNPOTScale        = false;
        bool                     overrideGenerateMipmap   = false;
        bool                     overrideMaxTextureSize   = false;
        TextureImporterFormat    textureImporterFormat    = TextureImporterFormat.ARGB32;
        TextureImporterNPOTScale textureImporterNPOTScale = TextureImporterNPOTScale.None;
        int maxTextureSize = 0;

        if (textureImporter.textureFormat != TextureImporterFormat.ARGB32)
        {
            textureImporterFormat         = textureImporter.textureFormat;
            textureImporter.textureFormat = TextureImporterFormat.ARGB32;
            overrideTextureFormat         = true;
        }
        if (textureImporter.generateMipsInLinearSpace)
        {
            textureImporter.generateMipsInLinearSpace = false;
            overrideGenerateMipmap = true;
        }
        if (textureImporter.npotScale != TextureImporterNPOTScale.None)
        {
            textureImporterNPOTScale  = textureImporter.npotScale;
            textureImporter.npotScale = TextureImporterNPOTScale.None;
            overrideNPOTScale         = true;
        }
        if (textureImporter.maxTextureSize != 4096)
        {
            maxTextureSize = textureImporter.maxTextureSize;
            textureImporter.maxTextureSize = 4096;
            overrideMaxTextureSize         = true;
        }
        if (overrideTextureFormat || overrideGenerateMipmap || overrideNPOTScale || overrideMaxTextureSize)
        {
            AssetDatabase.WriteImportSettingsIfDirty(assetPath);
            AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);
        }

        int width  = texture.width;
        int height = texture.height;

        if (overrideTextureFormat || overrideGenerateMipmap || overrideNPOTScale || overrideMaxTextureSize)
        {
            if (overrideTextureFormat)
            {
                textureImporter.textureFormat = textureImporterFormat;
            }
            if (overrideGenerateMipmap)
            {
                textureImporter.generateMipsInLinearSpace = true;
            }
            if (overrideNPOTScale)
            {
                textureImporter.npotScale = textureImporterNPOTScale;
            }
            if (overrideMaxTextureSize)
            {
                textureImporter.maxTextureSize = maxTextureSize;
            }
            AssetDatabase.WriteImportSettingsIfDirty(assetPath);
            AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);
        }

        GameObject go = new GameObject(texture.name);

        go.transform.localPosition = Vector3.zero;
        go.transform.localRotation = Quaternion.identity;
        go.transform.localScale    = Vector3.one;

        if (string.IsNullOrEmpty(assetPath))
        {
            Debug.LogError("");
            return;
        }

        string directoryName = Path.GetDirectoryName(assetPath);
        string fileName      = Path.GetFileNameWithoutExtension(assetPath);
        string baseAssetPath = Path.Combine(directoryName, fileName);
        string materialPath  = baseAssetPath + ".mat";

        Material material = null;
        bool     isExistsAssetMaterial = false;

        if (_isCreateAsset)
        {
            material = (Material)AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material));
            isExistsAssetMaterial = (material != null);
            if (isExistsAssetMaterial)
            {
                material.shader = Shader.Find(_GetShaderName());
            }
        }

        if (material == null)
        {
            material = new Material(Shader.Find(_GetShaderName()));
        }

        material.mainTexture = texture;

        System.Text.StringBuilder postfixMeshName = new System.Text.StringBuilder();

        postfixMeshName.Append("_");
        if (_anchorType.ToString().StartsWith("Top"))
        {
            postfixMeshName.Append("t");
        }
        else if (_anchorType.ToString().StartsWith("Bottom"))
        {
            postfixMeshName.Append("b");
        }
        else
        {
            postfixMeshName.Append("c");
        }

        if (_anchorType.ToString().StartsWith("Left"))
        {
            postfixMeshName.Append("l");
        }
        else if (_anchorType.ToString().StartsWith("Right"))
        {
            postfixMeshName.Append("r");
        }
        else
        {
            postfixMeshName.Append("c");
        }

        postfixMeshName.Append("_");
        postfixMeshName.Append(_scaleBy.ToString().Substring(0, 1).ToLower());
        postfixMeshName.Append(_size.ToString());
        string meshPath = baseAssetPath + postfixMeshName.ToString() + ".asset";

        Mesh mesh = null;
        bool isExistsAssetMesh = false;

        if (_isCreateAsset)
        {
            mesh = (Mesh)AssetDatabase.LoadAssetAtPath(meshPath, typeof(Mesh));
            isExistsAssetMesh = (mesh != null);
        }

        float w = (float)width;
        float h = (float)height;

        switch (_scaleBy)
        {
        case ScaleBy.Pixel:
            w *= _size;
            h *= _size;
            break;

        case ScaleBy.Width:
            h *= _size / w;
            w  = _size;
            break;

        case ScaleBy.Height:
            w *= _size / h;
            h  = _size;
            break;
        }
        float x = 0.0f, y = 0.0f;

        switch (_anchorType)
        {
        case AnchorType.TopLeft:
            x = 0.0f;
            y = -h;
            break;

        case AnchorType.Top:
            x = -w * 0.5f;
            y = -h;
            break;

        case AnchorType.TopRight:
            x = -w;
            y = -h;
            break;

        case AnchorType.Left:
            x = 0.0f;
            y = -h * 0.5f;
            break;

        case AnchorType.Center:
            x = -w * 0.5f;
            y = -h * 0.5f;
            break;

        case AnchorType.Right:
            x = -w;
            y = -h * 0.5f;
            break;

        case AnchorType.BottomLeft:
            x = 0.0f;
            y = 0.0f;
            break;

        case AnchorType.Bottom:
            x = -w * 0.5f;
            y = 0.0f;
            break;

        case AnchorType.BottomRight:
            x = -w;
            y = 0.0f;
            break;
        }

        if (mesh == null)
        {
            mesh          = new Mesh();
            mesh.vertices = new Vector3[4] {
                new Vector3(x, y + h, 0.0f),
                new Vector3(x + w, y + h, 0.0f),
                new Vector3(x, y, 0.0f),
                new Vector3(x + w, y, 0.0f),
            };
            mesh.uv = new Vector2[4] {
                new Vector2(0.0f, 1.0f),
                new Vector2(1.0f, 1.0f),
                new Vector2(0.0f, 0.0f),
                new Vector2(1.0f, 0.0f),
            };
            mesh.triangles = new int[6] {
                0, 1, 2, 3, 2, 1,
            };

            mesh.RecalculateBounds();
            mesh.RecalculateNormals();
        }

        MeshRenderer meshRenderer = go.AddComponent <MeshRenderer>();

        meshRenderer.castShadows    = false;
        meshRenderer.receiveShadows = false;
        meshRenderer.sharedMaterial = material;
        MeshFilter meshFilter = go.AddComponent <MeshFilter>();

        meshFilter.sharedMesh = mesh;

        if (_isCreateAsset)
        {
            if (!isExistsAssetMaterial)
            {
                AssetDatabase.CreateAsset(material, materialPath);
            }
            else
            {
                EditorUtility.SetDirty(material);
                AssetDatabase.SaveAssets();
            }

            if (!isExistsAssetMesh)
            {
                AssetDatabase.CreateAsset(mesh, meshPath);
            }
        }
    }
        //------------------------------------------------------------

        // テクスチャの属性を設定する(読み出し・書き込み)
        private void SetTextureSetting(string tPath, bool tReadable, ref TextureImporterCompression rFormat, ref TextureImporterNPOTScale rNPOTScale)
        {
            TextureImporter tTextureImporter = AssetImporter.GetAtPath(tPath) as TextureImporter;

            if (tReadable == true)
            {
                // 読み込み許可
                rFormat    = tTextureImporter.textureCompression;
                rNPOTScale = tTextureImporter.npotScale;

                // 強制的に ARGB32 NPOT に変える必要がある
                tTextureImporter.textureCompression = TextureImporterCompression.Uncompressed;
                tTextureImporter.npotScale          = TextureImporterNPOTScale.None;
            }
            else
            {
                // 読み込み禁止
                tTextureImporter.textureCompression = rFormat;
                tTextureImporter.npotScale          = rNPOTScale;
            }

            tTextureImporter.isReadable = tReadable;

            AssetDatabase.ImportAsset(tPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);
        }
        // アトラステクスチャの更新を実行する
        private void BuildAtlas(Texture2D tAtlas)
        {
            Texture2D tTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false);

            List <SpriteMetaData> tSpriteSheetList   = new List <SpriteMetaData>();
            List <Texture2D>      tSpriteTextureList = new List <Texture2D>();
            List <string>         tDeleteSpriteList  = new List <string>();

            string tPath;

            // 元の状態を保存する(バックアップが必要な項目)
            TextureImporterCompression tAtlasFormat    = TextureImporterCompression.Uncompressed;
            TextureImporterNPOTScale   tAtlasNPOtScale = TextureImporterNPOTScale.None;

            if (tAtlas != null)
            {
                // 既に作成済みのアトラスの更新
                tPath = AssetDatabase.GetAssetPath(tAtlas.GetInstanceID());

                SetTextureSetting(tPath, true, ref tAtlasFormat, ref tAtlasNPOtScale);                          // 書き込み属性を有効にする

                tAtlas = AssetDatabase.LoadAssetAtPath(tPath, typeof(Texture2D)) as Texture2D;
            }

            foreach (KeyValuePair <string, SpriteElement> tSpriteElementKeyValue in m_SpriteElementHash)
            {
                string        tName          = tSpriteElementKeyValue.Key;
                SpriteElement tSpriteElement = tSpriteElementKeyValue.Value;

                Texture2D tElementTexture;
                int       x, y, w, h;

                switch (tSpriteElement.action)
                {
                // アトラススプライトに内包される領域
                case SpriteAction.None:
                    tSpriteSheetList.Add(tSpriteElement.metaData);

                    x = ( int )tSpriteElement.metaData.rect.x;
                    y = ( int )tSpriteElement.metaData.rect.y;
                    w = ( int )tSpriteElement.metaData.rect.width;
                    h = ( int )tSpriteElement.metaData.rect.height;

                    tElementTexture = new Texture2D(w, h, TextureFormat.ARGB32, false);
                    tElementTexture.SetPixels(tAtlas.GetPixels(x, y, w, h));
                    tElementTexture.Apply();

                    tSpriteTextureList.Add(tElementTexture);
                    break;

                // 新規追加
                case SpriteAction.Add:
                    tSpriteSheetList.Add(tSpriteElement.metaData);

                    tPath = AssetDatabase.GetAssetPath(tSpriteElement.texture.GetInstanceID());

                    // 読み込む前にフォーマットを強制的に ARGB32 NPOT にしてやる(アルファテクスチャなどだとオリジナルの状態が正しく読み込めない)
                    SetTextureSetting(tPath, true, ref tSpriteElement.format, ref tSpriteElement.NPOTscale);

                    if (tSpriteElement.type == 0)
                    {
                        // テクスチャまたはシングルスプライトタイプ
                        tSpriteElement.texture = AssetDatabase.LoadAssetAtPath(tPath, typeof(Texture2D)) as Texture2D;
                        tSpriteTextureList.Add(tSpriteElement.texture);
                    }
                    else
                    {
                        // マルチプルスプライトタイプ
                        x = ( int )tSpriteElement.metaData.rect.x;
                        y = ( int )tSpriteElement.metaData.rect.y;
                        w = ( int )tSpriteElement.metaData.rect.width;
                        h = ( int )tSpriteElement.metaData.rect.height;

                        tElementTexture = new Texture2D(w, h, TextureFormat.ARGB32, false);
                        tElementTexture.SetPixels(tSpriteElement.texture.GetPixels(x, y, w, h));
                        tElementTexture.Apply();

                        tSpriteTextureList.Add(tElementTexture);
                    }
                    break;

                // 領域更新
                case SpriteAction.Update:
                    tSpriteSheetList.Add(tSpriteElement.metaData);

                    tPath = AssetDatabase.GetAssetPath(tSpriteElement.texture.GetInstanceID());

                    // 読み込む前にフォーマットを強制的に ARGB32 NPOT にしてやる(アルファテクスチャなどだとオリジナルの状態が正しく読み込めない)
                    SetTextureSetting(tPath, true, ref tSpriteElement.format, ref tSpriteElement.NPOTscale);

                    if (tSpriteElement.type == 0)
                    {
                        // テクスチャまたはシングルスプライトタイプ
                        tSpriteElement.texture = AssetDatabase.LoadAssetAtPath(tPath, typeof(Texture2D)) as Texture2D;
                        tSpriteTextureList.Add(tSpriteElement.texture);
                    }
                    else
                    {
                        // マルチプルスプライトタイプ
                        x = ( int )tSpriteElement.metaData.rect.x;
                        y = ( int )tSpriteElement.metaData.rect.y;
                        w = ( int )tSpriteElement.metaData.rect.width;
                        h = ( int )tSpriteElement.metaData.rect.height;

                        tElementTexture = new Texture2D(w, h, TextureFormat.ARGB32, false);
                        tElementTexture.SetPixels(tSpriteElement.texture.GetPixels(x, y, w, h));
                        tElementTexture.Apply();

                        tSpriteTextureList.Add(tElementTexture);
                    }
                    break;

                case SpriteAction.Delete:
                    tDeleteSpriteList.Add(tName);
                    break;
                }

                tElementTexture = null;
            }

            if (tSpriteSheetList.Count > 0 && tSpriteTextureList.Count > 0)
            {
                int tMaxSize = Mathf.Min(SystemInfo.maxTextureSize, 2048);

                int tPadding = m_Padding;
                if (tSpriteTextureList.Count == 1)
                {
                    // 要素が1つだけの場合はパディングは強制的に0にする
                    tPadding = 0;
                }

                Rect[] tRectList = tTexture.PackTextures(tSpriteTextureList.ToArray(), tPadding, tMaxSize);

                // 後始末
                foreach (KeyValuePair <string, SpriteElement> tSpriteElementKeyValue in m_SpriteElementHash)
                {
                    SpriteElement tSpriteElement = tSpriteElementKeyValue.Value;

                    switch (tSpriteElement.action)
                    {
                    // 新規追加
                    case SpriteAction.Add:
                        tPath = AssetDatabase.GetAssetPath(tSpriteElement.texture.GetInstanceID());
                        SetTextureSetting(tPath, false, ref tSpriteElement.format, ref tSpriteElement.NPOTscale);

                        tSpriteElement.texture = null;

                        tSpriteElement.action = SpriteAction.None;
                        break;

                    // 領域更新
                    case SpriteAction.Update:
                        tPath = AssetDatabase.GetAssetPath(tSpriteElement.texture.GetInstanceID());
                        SetTextureSetting(tPath, false, ref tSpriteElement.format, ref tSpriteElement.NPOTscale);

                        tSpriteElement.texture = null;

                        tSpriteElement.action = SpriteAction.None;
                        break;
                    }
                }

                //---------------------------------------------------

                // 出来上がったテクスチャに無駄が無いか確認し無駄があれば除去する

                int i, l;

                float tw = tTexture.width;
                float th = tTexture.height;

                l = tSpriteSheetList.Count;

                for (i = 0; i < l; i++)
                {
                    Rect tRect = tRectList[i];
                    tRect.x      *= tw;
                    tRect.y      *= th;
                    tRect.width  *= tw;
                    tRect.height *= th;
                    tRectList[i]  = tRect;
                }

                // ソースのリージョンを検査して無駄が無いか確認する
                float xMin = tw;
                float yMin = th;
                float xMax = 0;
                float yMax = 0;

                for (i = 0; i < l; i++)
                {
                    if (tRectList[i].xMin < xMin)
                    {
                        xMin = tRectList[i].xMin;
                    }

                    if (tRectList[i].yMin < yMin)
                    {
                        yMin = tRectList[i].yMin;
                    }

                    if (tRectList[i].xMax > xMax)
                    {
                        xMax = tRectList[i].xMax;
                    }

                    if (tRectList[i].yMax > yMax)
                    {
                        yMax = tRectList[i].yMax;
                    }
                }

                xMin = xMin - tPadding;
                if (xMin < 0)
                {
                    xMin = 0;
                }
                yMin = yMin - tPadding;
                if (yMin < 0)
                {
                    yMin = 0;
                }
                xMax = xMax + tPadding;
                if (xMax > tw)
                {
                    xMax = tw;
                }
                yMax = yMax + tPadding;
                if (yMax > th)
                {
                    yMax = th;
                }
                int pw = ( int )(xMax - xMin);
                int ph = ( int )(yMax - yMin);

                int rw = 1;
                for (i = 0; i < 16; i++)
                {
                    if (rw >= pw)
                    {
                        break;
                    }
                    rw = rw << 1;
                }

                int rh = 1;
                for (i = 0; i < 16; i++)
                {
                    if (rh >= ph)
                    {
                        break;
                    }
                    rh = rh << 1;
                }

                if (rw <= ( int )(tw / 2) || rh <= ( int )(th / 2))
                {
                    // 無駄がある

                    //				Debug.LogWarning( "無駄がある:" + rw + " / " + tw + " " + rh + " / " + th ) ;

                    int rx = ( int )xMin;
                    int ry = ( int )yMin;

                    //				Debug.LogWarning( "取得範囲:" + rx + " " + ry + " " + rw + " " + rh ) ;

                    Texture2D tReduceTexture = new Texture2D(rw, rh, TextureFormat.ARGB32, false);
                    tReduceTexture.SetPixels(tTexture.GetPixels(rx, ry, rw, rh));
                    tReduceTexture.Apply();

                    tTexture       = tReduceTexture;
                    tReduceTexture = null;

                    for (i = 0; i < l; i++)
                    {
                        Rect tRect = tRectList[i];
                        tRect.x     -= rx;
                        tRect.y     -= ry;
                        tRectList[i] = tRect;
                    }
                }

                //---------------------------------------------------

                string tAtlasFullPath;
                if (tAtlas == null)
                {
                    // 生成
                    tAtlasFullPath = m_AtlasFullPath;
                }
                else
                {
                    // 更新
                    tAtlasFullPath = AssetDatabase.GetAssetPath(tAtlas.GetInstanceID());
                }

                // テクスチャをPNG画像として保存する
                byte[] tData = tTexture.EncodeToPNG();
                System.IO.File.WriteAllBytes(tAtlasFullPath, tData);
                tData = null;

                AssetDatabase.SaveAssets();
                if (tAtlas == null)
                {
                    AssetDatabase.Refresh();
                }

                TextureImporter tTextureImporter = AssetImporter.GetAtPath(tAtlasFullPath) as TextureImporter;

                // 既存の場合は以前の設定を引き継がせる
                tTextureImporter.textureCompression = tAtlasFormat;
                tTextureImporter.npotScale          = tAtlasNPOtScale;

                if (tAtlas == null)
                {
                    // 新規作成の場合に設定する
                    tTextureImporter.textureType      = TextureImporterType.Sprite;
                    tTextureImporter.spriteImportMode = SpriteImportMode.Multiple;
                    tTextureImporter.mipmapEnabled    = false;
                }

                for (i = 0; i < l; i++)
                {
                    SpriteMetaData tSpriteMetaData = tSpriteSheetList[i];

                    tSpriteMetaData.rect = tRectList[i];

                    tSpriteSheetList[i] = tSpriteMetaData;
                }

                tTextureImporter.spritesheet = tSpriteSheetList.ToArray();

                tTextureImporter.isReadable = false;                    // 書き込み属性を無効にする

                AssetDatabase.ImportAsset(tAtlasFullPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);

                tAtlas = AssetDatabase.LoadAssetAtPath(tAtlasFullPath, typeof(Texture2D)) as Texture2D;

                tSpriteSheetList.Clear();
                tSpriteTextureList.Clear();

                Resources.UnloadUnusedAssets();
            }
            else
            {
                // 要素が全て無くなるためファイル自体を削除する
                AssetDatabase.DeleteAsset(m_AtlasFullPath);
                tAtlas = null;
            }

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();

            foreach (string tName in tDeleteSpriteList)
            {
                m_SpriteElementHash.Remove(tName);
            }
            UpdateList(tAtlas, true);
        }
Пример #34
0
    private void DrawTextureSettings(TextureImporterType textureType)
    {
        if (textureType != oldTextureType)
        {
            Reset();
        }
        switch (textureType)
        {
        case TextureImporterType.Image:
            if ((grayscaleToAlpha = EditorGUILayout.Toggle("Alpha from Grayscale", grayscaleToAlpha)))
            {
                alphaIsTransparency = EditorGUILayout.Toggle("Alpha is Transparency", alphaIsTransparency);
            }
            GUILayout.Space(8f);
            wrapMode = (TextureWrapMode)DrawPopup("Wrap Mode", (int)wrapMode, wrapModeString);
            if ((filterMode = (FilterMode)DrawPopup("Filter Mode", (int)filterMode, filterModeString)) != FilterMode.Point)
            {
                anisoLevel = EditorGUILayout.IntSlider("Aniso Level", anisoLevel, 0, 9);
            }
            break;

        case TextureImporterType.Bump:
            if (createFromGrayscale = EditorGUILayout.Toggle("(Invalid) Create from Grayscale", createFromGrayscale))
            {
                bumpiness = EditorGUILayout.Slider("(Invalid) Bumpiness", bumpiness, 0, 0.3f);
                filtering = DrawPopup("(Invalid) Filtering", filtering, filteringString);
            }
            GUILayout.Space(8f);
            wrapMode = (TextureWrapMode)DrawPopup("Wrap Mode", (int)wrapMode, wrapModeString);
            if ((filterMode = (FilterMode)DrawPopup("Filter Mode", (int)filterMode, filterModeString)) != FilterMode.Point)
            {
                anisoLevel = EditorGUILayout.IntSlider("Aniso Level", anisoLevel, 0, 9);
            }
            break;

        case TextureImporterType.GUI:
            GUILayout.Space(8f);
            filterMode = (FilterMode)DrawPopup("Filter Mode", (int)filterMode, filterModeString);
            break;

        case TextureImporterType.Sprite:
            spriteMode    = (SpriteImportMode)DrawPopup("Sprite Mode", (int)spriteMode, spriteModeString, spriteModeArray);
            packingTag    = EditorGUILayout.TextField("    Packing Tag", packingTag);
            pixelsToUnits = EditorGUILayout.FloatField("    Pixels To Units", pixelsToUnits);
            if (spriteMode == SpriteImportMode.Single)
            {
                if ((pivot = DrawPopup("    Pivot", pivot, pivotString, pivotArray)) == -1)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Space(EditorGUIUtility.labelWidth);
                    GUILayout.Label("X");
                    pivotX = EditorGUILayout.FloatField(pivotX);
                    GUILayout.Label("Y");
                    pivotY = EditorGUILayout.FloatField(pivotY);
                    GUILayout.EndHorizontal();
                }
            }
            GUILayout.Space(8f);
            filterMode = (FilterMode)DrawPopup("Filter Mode", (int)filterMode, filterModeString);
            break;

        case TextureImporterType.Cursor:
            GUILayout.Space(8f);
            wrapMode   = (TextureWrapMode)DrawPopup("Wrap Mode", (int)wrapMode, wrapModeString);
            filterMode = (FilterMode)DrawPopup("Filter Mode", (int)filterMode, filterModeString);
            break;

        case TextureImporterType.Reflection:
            mapping        = DrawPopup("Mapping", mapping, mappingString);
            fixupEdgeSeams = EditorGUILayout.Toggle("Fixup Edge Seams", fixupEdgeSeams);
            GUILayout.Space(8f);
            if ((filterMode = (FilterMode)DrawPopup("Filter Mode", (int)filterMode, filterModeString)) != FilterMode.Point)
            {
                anisoLevel = EditorGUILayout.IntSlider("Aniso Level", anisoLevel, 0, 9);
            }
            break;

        case TextureImporterType.Cookie:
            if ((lightType = (LightType)DrawPopup("(Invalid) Light Type", (int)lightType, lightTypeString)) == LightType.Point)
            {
                mapping        = DrawPopup("(Invalid) Mapping", mapping, mappingString);
                fixupEdgeSeams = EditorGUILayout.Toggle("(Invalid) Fixup Edge Seams", fixupEdgeSeams);
            }
            grayscaleToAlpha = EditorGUILayout.Toggle("Alpha from Grayscale", grayscaleToAlpha);
            GUILayout.Space(8f);
            if ((filterMode = (FilterMode)DrawPopup("Filter Mode", (int)filterMode, filterModeString)) != FilterMode.Point)
            {
                anisoLevel = EditorGUILayout.IntSlider("Aniso Level", anisoLevel, 0, 9);
            }
            break;

        case TextureImporterType.Lightmap:
            GUILayout.Space(8f);
            if ((filterMode = (FilterMode)DrawPopup("Filter Mode", (int)filterMode, filterModeString)) != FilterMode.Point)
            {
                anisoLevel = EditorGUILayout.IntSlider("Aniso Level", anisoLevel, 0, 9);
            }
            break;

        case TextureImporterType.Advanced:
            nonPowerOf2      = (TextureImporterNPOTScale)DrawPopup("Non Power of 2", (int)nonPowerOf2, nonPowerOf2String);
            generateCubemap  = (TextureImporterGenerateCubemap)DrawPopup("Generate Cubemap", (int)generateCubemap, generateCubemapString);
            readWriteEnabled = EditorGUILayout.Toggle("Read/Write Enabled", readWriteEnabled);
            importType       = (TextureImporterType)DrawPopup("Import Type", (int)importType, importTypeString, importTypeArray);
            if (importType == TextureImporterType.Image)
            {
                grayscaleToAlpha    = EditorGUILayout.Toggle("    Alpha from Grayscale", grayscaleToAlpha);
                alphaIsTransparency = EditorGUILayout.Toggle("    Alpha is Transparency", alphaIsTransparency);
                bypassSRGBSampling  = EditorGUILayout.Toggle("    (Invalid) Bypass sRGB Sampling", bypassSRGBSampling);
                spriteMode          = (SpriteImportMode)DrawPopup("    Sprite Mode", (int)spriteMode, spriteModeStringFull);
                if (spriteMode != SpriteImportMode.None)
                {
                    packingTag    = EditorGUILayout.TextField("        Packing Tag", packingTag);
                    pixelsToUnits = EditorGUILayout.FloatField("        Pixels To Units", pixelsToUnits);
                    meshType      = (SpriteMeshType)DrawPopup("        Mesh Type", (int)meshType, meshTypeString);
                    extrudeEdges  = (uint)EditorGUILayout.IntSlider("        Extrude Edges", (int)extrudeEdges, 0, 32);
                    if (spriteMode == SpriteImportMode.Single)
                    {
                        if ((pivot = DrawPopup("        Pivot", pivot, pivotString, pivotArray)) == -1)
                        {
                            GUILayout.BeginHorizontal();
                            GUILayout.Space(EditorGUIUtility.labelWidth);
                            GUILayout.Label("X");
                            pivotX = EditorGUILayout.FloatField(pivotX);
                            GUILayout.Label("Y");
                            pivotY = EditorGUILayout.FloatField(pivotY);
                            GUILayout.EndHorizontal();
                        }
                    }
                }
            }
            else if (importType == TextureImporterType.Bump)
            {
                if (createFromGrayscale = EditorGUILayout.Toggle("    (Invalid) Create from Grayscale", createFromGrayscale))
                {
                    bumpiness = EditorGUILayout.Slider("    (Invalid) Bumpiness", bumpiness, 0, 0.3f);
                    filtering = DrawPopup("    Filtering", filtering, filteringString);
                }
            }
            GUILayout.Space(8f);
            if (generateMipMaps = EditorGUILayout.Toggle("Generate Mip Maps", generateMipMaps))
            {
                inLinearSpace   = EditorGUILayout.Toggle("    In Linear Space", inLinearSpace);
                borderMipMaps   = EditorGUILayout.Toggle("    Border Mip Maps", borderMipMaps);
                mipMapFiltering = (TextureImporterMipFilter)DrawPopup("    Mip Map Filtering", (int)mipMapFiltering, mipMapFilteringString);
                if (fadeoutMipMaps = EditorGUILayout.Toggle("    Fadeout Mip Maps", fadeoutMipMaps))
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.Label("        Fade Range");
                    GUILayout.Space(43f);
                    EditorGUILayout.MinMaxSlider(ref fadeoutMin, ref fadeoutMax, 0, 10);
                    fadeoutMin = Mathf.RoundToInt(fadeoutMin);
                    fadeoutMax = Mathf.RoundToInt(fadeoutMax);
                    GUILayout.EndHorizontal();
                }
            }
            GUILayout.Space(8f);
            wrapMode = (TextureWrapMode)DrawPopup("Wrap Mode", (int)wrapMode, wrapModeString);
            if ((filterMode = (FilterMode)DrawPopup("Filter Mode", (int)filterMode, filterModeString)) != FilterMode.Point)
            {
                anisoLevel = EditorGUILayout.IntSlider("Aniso Level", anisoLevel, 0, 9);
            }
            break;

        default:
            break;
        }
        GUILayout.Space(8f);
    }
 public ShelfTextureImportParams SetNonPowerOfTwoScale(TextureImporterNPOTScale scale)
 {
     _textureImporter.textureType = TextureImporterType.Advanced;
     _textureImporter.npotScale = scale;
     return this;
 }