Пример #1
0
    static void func_MakeFontEditable()
    {
        if (Selection.objects.Length == 0)
        {
            Debug.LogError("Sorry, but you have to select the Font (left click it once in the Project Panel) 1st! Abort!");
            return;
        }

        string sFilePath = AssetDatabase.GetAssetPath(Selection.objects[0]);
        string sFilename = Path.GetFileNameWithoutExtension(sFilePath);
        string sFileExt  = Path.GetExtension(sFilePath);

        if (sFileExt.ToLower() != ".ttf")               // add more extension when Unity adds others font types
        {
            Debug.LogError("Sorry, but you have Not selected a Font! Abort!");
            return;
        }

        UnityEngine.Object f    = AssetDatabase.LoadMainAssetAtPath(sFilePath);
        string             path = AssetDatabase.GetAssetPath(f);

        TrueTypeFontImporter fontImporter = AssetImporter.GetAtPath(path) as TrueTypeFontImporter;

        string sFilePath_Import = path.Replace(sFilename + sFileExt, sFilename + "-Edit-Me" + sFileExt);

        fontImporter.GenerateEditableFont(sFilePath_Import);

        Debug.Log("Editable Font created at: " + sFilePath_Import);
    }
Пример #2
0
        /// <summary>
        /// Create Soft Font, Soft Font Material, Soft Font Texture from SoftEffect Settings,
        /// </summary>
        /// <param name="font"></param>
        private void CreateSoftFont(Font font, bool createNewFolder) // http://answers.unity3d.com/questions/485695/truetypefontimportergenerateeditablefont-does-not.html
        {
            //  Mkey.Utils.Measure("<<<<<<<<<<<<Summary CreateSoftFontTexture>>>>>>>>>>>>>>>: ", () => {
            gpuWorker = new GPUWorker(eShader);
            string dirPath = Path.GetDirectoryName(AssetDatabase.GetAssetPath(font));

            //1) load source font asset
            string path = AssetDatabase.GetAssetPath(font);
            Font   f    = font;

            if (SoftEffects.debuglog)
            {
                Debug.Log("Path to Source font: " + path);
            }

            font = (Font)AssetDatabase.LoadMainAssetAtPath(path);
            if (f && !font)
            {
                Debug.LogError("Can't use embedded font : " + f.name);
                return;
            }

            //2) Remove old Editable font
            if (SoftFont && !createNewFolder)
            {
                if (SoftEffects.debuglog)
                {
                    Debug.Log("EditableFont folder: " + Path.GetDirectoryName(AssetDatabase.GetAssetPath(SoftFont)));
                }
                if (SoftEffects.debuglog)
                {
                    Debug.Log("Remove old EditableFont: " + SoftFont.name);
                }
                if (SoftFont.material)
                {
                    AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(SoftFont.material.mainTexture));
                    AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(SoftFont.material));
                }
                AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(SoftFont));
                AssetDatabase.Refresh();
            }

            //3) reimport source font as editable
            TrueTypeFontImporter fontImporter = AssetImporter.GetAtPath(path) as TrueTypeFontImporter;

            //source settings
            int sourceSize    = fontImporter.fontSize;
            int sourcePadding = fontImporter.characterPadding;
            int sourceSpacing = fontImporter.characterSpacing;

            FontTextureCase sourceCase = fontImporter.fontTextureCase;
            string          chars      = fontImporter.customCharacters;

            fontImporter.fontSize         = GetComponent <Text>().fontSize;
            fontImporter.characterPadding = Mathf.Clamp(faceOptions.extPixels, 1, 100);
            fontImporter.characterSpacing = 0;

            // Mkey.Utils.Measure("Summary PreCreateFontTexture: ", () =>  {
            //     Mkey.Utils.Measure("Reimport font: ", () => {
            if (SoftFontTextureCase == FontTextureCase.CustomSet)
            {
                if (customCharacters.Length == 0 || customCharacters == " ")
                {
                    Debug.LogError("Custom Characters string is empty. Set default string.");
                    customCharacters = GetComponent <Text>().text;
                    if (customCharacters.Length == 0 || customCharacters == " ")
                    {
                        customCharacters = "New txt";
                    }
                }
                fontImporter.customCharacters = customCharacters;
            }
            else if (SoftFontTextureCase == FontTextureCase.Dynamic)
            {
                SoftFontTextureCase = FontTextureCase.ASCII;
            }
            fontImporter.fontTextureCase = SoftFontTextureCase;
            fontImporter.SaveAndReimport();
            // });

            //  Mkey.Utils.Measure("GenerateEditableFont: ", () =>  {
            SoftFont = fontImporter.GenerateEditableFont(path);
            // });
            int maxSize = Mathf.Max(font.material.mainTexture.width, font.material.mainTexture.height);

            // Mkey.Utils.Measure("RenameAsset: ", () =>    {
            AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(SoftFont), font.name + key);
            AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(SoftFont.material), font.name + key + "_edit");
            AssetDatabase.RenameAsset(AssetDatabase.GetAssetPath(SoftFont.material.mainTexture), font.name + key);
            AssetDatabase.Refresh();
            //  });

            Shader softShader = Shader.Find("SoftEffects/SoftEditShader");

            SoftFont.material.shader = softShader;
            SoftMaterial             = SoftFont.material;

            if (SoftEffects.debuglog)
            {
                Debug.Log("Editable texture size: " + SoftFont.material.mainTexture.width + " x " + SoftFont.material.mainTexture.height);
            }
            // Mkey.Utils.Measure("Reimport texture: ", () =>  {
            //5) Reimport EditableFont texture as readable
            SoftFont.material.mainTexture.ReimportTexture(true, maxSize);
            if (SoftEffects.debuglog)
            {
                Debug.Log("Editable texture size after reimport: " + SoftFont.material.mainTexture.width + " x " + SoftFont.material.mainTexture.height);
            }
            // });

            // });

            //5) Generate new Texture for editable font
            // Mkey.Utils.Measure("faceOptions.RenderFontTexture: ", () =>  {
            faceOptions.RenderFontTexture(gpuWorker, SoftFont, cb);
            //});

            // Mkey.Utils.Measure("AfterCreateFontTexture: ", () =>  {
            faceOptions.CreateTextureFromRender_ARGB32(true, dirPath + "/" + font.name + key + "_edit" + ".png");

            AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(SoftFont.material.mainTexture));                           //  Remove old texture

            Texture2D t = (Texture2D)AssetDatabase.LoadMainAssetAtPath(dirPath + "/" + font.name + key + "_edit" + ".png"); // load new texture asset

            t.ReimportTexture(true);

            //6 extend verts and uvs
            // SoftFont.ExtendVertsAndUvs(faceOptions.extPixels);
            faceOptions.mainTexture = t;

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


            // 9) remove editable font to unique folder
            string targetFolder = AssetDatabase.GUIDToAssetPath(FolderGUID);
            string fontPath     = AssetDatabase.GetAssetPath(SoftFont);
            string materialPath = AssetDatabase.GetAssetPath(SoftFont.material);
            string texturePath  = AssetDatabase.GetAssetPath(t);

            if (SoftEffects.debuglog)
            {
                Debug.Log("Move file: " + fontPath + " to : " + targetFolder + "/" + Path.GetFileName(fontPath));
            }
            AssetDatabase.MoveAsset(fontPath, targetFolder + "/" + Path.GetFileName(fontPath));// FileUtil.MoveFileOrDirectory(fontPath, targetFolder + "/"+  Path.GetFileName(fontPath));
            AssetDatabase.MoveAsset(materialPath, targetFolder + "/" + Path.GetFileName(materialPath));
            AssetDatabase.MoveAsset(texturePath, targetFolder + "/" + Path.GetFileName(texturePath));

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

            faceOptions.IsCombinedDirty = true;
            RenderNewTextures(gpuWorker, true);
            /**/
            EditorGUIUtility.PingObject(SoftFont);
            EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());

            //revert source settings
            fontImporter                 = AssetImporter.GetAtPath(path) as TrueTypeFontImporter;
            fontImporter.fontSize        = sourceSize;
            fontImporter.fontTextureCase = sourceCase;
            // fontImporter.characterPadding = sourcePadding;
            // fontImporter.characterSpacing = sourceSpacing;

            fontImporter.characterPadding = 1;
            fontImporter.characterSpacing = 0;

            if (sourceCase == FontTextureCase.CustomSet)
            {
                fontImporter.customCharacters = chars;
            }
            fontImporter.SaveAndReimport();
            // });
            // });
        }
Пример #3
0
        //[MenuItem("Assets/Create Editable Copy Font")]
        static void CreateFont()
        {
            var txts = UnityEngine.Object.FindObjectsOfType(typeof(Text));

            return;

            TextAsset sourceTextAsset = null;

            try
            {
                sourceTextAsset = (TextAsset)Selection.activeObject;
            } catch (InvalidCastException e)
            {
                Debug.Log("Selected Object is not a txt file: " + Environment.NewLine + e.Message);
            }

            if (sourceTextAsset == null)
            {
                EditorUtility.DisplayDialog("No Config selected", "Please select a TxtFile Config...\nSuch as Exsample.txt:\nname=Assets/GameAssets/Fonts/impact.ttf,size=40\n123456789abcdefghijk", "Cancel");
                return;
            }

            int    targetFontSize;
            string sourceFontPath, targetFontPath, targetFontCharacters = "";

            try
            {
                string   sourceConfigPath  = AssetDatabase.GetAssetPath(Selection.activeObject);
                string[] sourceConfigInfos = sourceTextAsset.text.Split('\n');
                string   headInfo          = sourceConfigInfos [0];
                string[] headInfos         = headInfo.Split(',');

                sourceFontPath = headInfos [0].Split('=') [1];
                targetFontPath = sourceConfigPath.Replace(".txt", "_copy");
                targetFontSize = int.Parse(headInfos [1].Split('=') [1]);
                for (int i = 1; i < sourceConfigInfos.Length; i++)
                {
                    targetFontCharacters += sourceConfigInfos [i];
                }
            } catch (Exception ex)
            {
                EditorUtility.DisplayDialog("Config Error", "The config header data error...", "Cancel");
                return;
            }

            // 重新生成字体文件会导致场景中已存在的丢失,
            // 所以需要生成后再次赋值
            string[] targetFontPathInfos = targetFontPath.Split('/');
            string   textCheckName       = targetFontPathInfos [targetFontPathInfos.Length - 1];
            var      listTexts           = new List <Text>();

            foreach (Text text in UnityEngine.Object.FindObjectsOfType(typeof(Text)))
            {
                if (text.font.name == textCheckName)
                {
                    listTexts.Add(text);
                }
            }

            UnityEngine.Object   f            = AssetDatabase.LoadMainAssetAtPath(sourceFontPath);
            string               path         = AssetDatabase.GetAssetPath(f);
            TrueTypeFontImporter fontImporter = AssetImporter.GetAtPath(path) as TrueTypeFontImporter;

            fontImporter.fontTextureCase  = FontTextureCase.CustomSet;
            fontImporter.customCharacters = targetFontCharacters;
            fontImporter.fontSize         = targetFontSize;
            fontImporter.SaveAndReimport();
            AssetDatabase.Refresh();
            Font font = fontImporter.GenerateEditableFont(targetFontPath);

            foreach (Text item in listTexts)
            {
                item.font = font;
            }

            // 还原ttf设置
            fontImporter.fontTextureCase = FontTextureCase.Dynamic;
            fontImporter.SaveAndReimport();
            AssetDatabase.Refresh();

            System.GC.Collect();
        }