public override void OnInspectorGUI()
    {
        if (MadTrialEditor.isTrialVersion && MadTrialEditor.expired)
        {
            MadTrialEditor.OnEditorGUIExpired("Mad Level Manager");
            return;
        }

        LoadTextures(); // loading textures with delay to prevent editor errors
        CheckAssetLocation();
        ActiveInfo();

        GUIGroupPopup();

        LoadItems();

        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.BeginVertical(GUILayout.Width(1));
        GUILayout.Space(200);
        EditorGUILayout.EndVertical();
        list.Draw();
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        GUI.backgroundColor = Color.green;
        if (GUILayout.Button("Add"))
        {
            AddLevel();
        }
        GUI.backgroundColor = Color.white;

        GUI.enabled         = list.selectedItem != null;
        GUI.backgroundColor = Color.red;
        if (GUILayout.Button("Remove") || GUI.enabled && Event.current.keyCode == KeyCode.Delete)
        {
            RemoveLevel();
        }
        GUI.backgroundColor = Color.white;

        GUILayout.FlexibleSpace();

        GUILayout.Label("Move");

        if (GUILayout.Button("Down"))
        {
            MoveDown();
            configuration.SetDirty();
        }

        if (GUILayout.Button("Up"))
        {
            MoveUp();
            configuration.SetDirty();
        }

        GUILayout.Space(10);

        if (GUILayout.Button("Bottom"))
        {
            MoveToBottom();
            configuration.SetDirty();
        }

        if (GUILayout.Button("Top"))
        {
            MoveToTop();
            configuration.SetDirty();
        }

        GUI.enabled = true;

        EditorGUILayout.EndHorizontal();

        MadGUI.IndentBox("Level Properties", () => {
            var item  = list.selectedItem;
            var items = list.selectedItems;

            if (item == null)
            {
                item        = new LevelItem(configuration);
                GUI.enabled = false;
            }

            MadUndo.RecordObject(configuration, "Edit '" + item.level.name + "'");
            EditorGUI.BeginChangeCheck();

            EditorGUILayout.BeginHorizontal();

            EditorGUI.BeginChangeCheck();
            UnityEngine.Object sceneValue = null;
            if (!multiSelection)
            {
                MadGUI.Validate(() => item.level.sceneObject != null, () => {
                    sceneValue =
                        EditorGUILayout.ObjectField("Scene", item.level.sceneObject, typeof(UnityEngine.Object), false);
                });
            }
            else
            {
                bool unified = (from i in items select i.level.sceneObject).Distinct().Count() == 1;
                if (unified)
                {
                    sceneValue =
                        EditorGUILayout.ObjectField("Scene", item.level.sceneObject, typeof(UnityEngine.Object), false);
                }
                else
                {
                    sceneValue = EditorGUILayout.ObjectField("Scene", null, typeof(UnityEngine.Object), false);
                }
            }

            if (EditorGUI.EndChangeCheck())
            {
                MadUndo.RecordObject2(target, "Changed Level Scene");
                foreach (var levelItem in items)
                {
                    levelItem.level.sceneObject = sceneValue;
                }
            }


            GUI.backgroundColor = Color.yellow;
            if (GUILayout.Button("Set Current", GUILayout.Width(85)))
            {
                MadUndo.RecordObject2(target, "Change Scene");
                var obj = AssetDatabase.LoadAssetAtPath(EditorApplication.currentScene, typeof(UnityEngine.Object));
                if (obj != null)
                {
                    foreach (var levelItem in items)
                    {
                        levelItem.level.sceneObject = obj;
                    }
                }
                else
                {
                    EditorUtility.DisplayDialog("Scene not saved", "Current scene is not saved. Please save it first (CTRL+S).", "OK");
                }
            }
            GUI.backgroundColor = Color.white;

            EditorGUILayout.EndHorizontal();
            if (!CheckAssetIsScene(item.level.sceneObject))
            {
                item.level.sceneObject = null;
            }

            MadGUI.Validate(() => !string.IsNullOrEmpty(item.level.name), () => {
                GUI.SetNextControlName("level name"); // needs names to unfocus
                using (MadGUI.EnabledIf(!multiSelection)) {
                    if (!multiSelection)
                    {
                        EditorGUI.BeginChangeCheck();
                        var value = EditorGUILayout.TextField("Level Name", item.level.name);
                        if (EditorGUI.EndChangeCheck())
                        {
                            MadUndo.RecordObject2(target, "Changed Level Name");
                            item.level.name = value;
                        }
                    }
                    else
                    {
                        EditorGUILayout.TextField("Level Name", "-");
                    }
                }
            });


            // level type
            MadLevel.Type typeValue = default(MadLevel.Type);
            EditorGUI.BeginChangeCheck();
            if (!multiSelection)
            {
                typeValue = (MadLevel.Type)EditorGUILayout.EnumPopup("Type", item.level.type);
            }
            else
            {
                bool unified = (from i in items select i.level.type).Distinct().Count() == 1;
                if (unified)
                {
                    typeValue = (MadLevel.Type)EditorGUILayout.EnumPopup("Type", item.level.type);
                }
                else
                {
                    int val = EditorGUILayout.Popup("Type", -1, Enum.GetNames(typeof(MadLevel.Type)));
                    if (val != -1)
                    {
                        typeValue = (MadLevel.Type)val;
                    }
                }
            }

            if (EditorGUI.EndChangeCheck())
            {
                MadUndo.RecordObject2(target, "Changed Level Type");
                foreach (var levelItem in items)
                {
                    levelItem.level.type = typeValue;
                }
            }


            GUI.SetNextControlName("arguments"); // needs names to unfocus
            if (!multiSelection)
            {
                EditorGUI.BeginChangeCheck();
                var value = EditorGUILayout.TextField("Arguments", item.level.arguments);
                if (EditorGUI.EndChangeCheck())
                {
                    MadUndo.RecordObject2(target, "Changed Level Arguments");
                    item.level.arguments = value;
                }
            }
            else
            {
                bool unified = (from i in items select i.level.arguments).Distinct().Count() == 1;
                EditorGUI.BeginChangeCheck();
                string value = "";
                if (unified)
                {
                    value = EditorGUILayout.TextField("Arguments", item.level.arguments);
                }
                else
                {
                    value = EditorGUILayout.TextField("Arguments", "-");
                }
                if (EditorGUI.EndChangeCheck())
                {
                    MadUndo.RecordObject2(target, "Changed Level Arguments");
                    foreach (var levelItem in items)
                    {
                        levelItem.level.arguments = value;
                    }
                }
            }

            if (MadGUI.Foldout("Locking", false))
            {
                using (MadGUI.Indent()) {
                    bool lockedByDefultState = false;
                    if (multiSelection)
                    {
                        bool unified = (from i in items select i.level.lockedByDefault).Distinct().Count() == 1;
                        if (unified && (item.level.lockedByDefault))
                        {
                            lockedByDefultState = true;
                        }
                    }
                    else
                    {
                        lockedByDefultState = item.level.lockedByDefault;
                    }

                    EditorGUI.BeginChangeCheck();
                    GUI.SetNextControlName("locked by default"); // needs names to unfocus
                    bool lockedByDefaultValue = EditorGUILayout.Toggle("Locked By Default", lockedByDefultState);
                    if (EditorGUI.EndChangeCheck())
                    {
                        MadUndo.RecordObject2(target, "Changed Locked By Default");
                        foreach (var levelItem in items)
                        {
                            levelItem.level.lockedByDefault = lockedByDefaultValue;
                        }
                    }
                }
                EditorGUILayout.Space();
            }

            if (MadGUI.Foldout("Extensions", false))
            {
                using (MadGUI.Indent()) {
                    EditorGUI.BeginChangeCheck();
                    int extensionIndex = -1;

                    if (!multiSelection)
                    {
                        extensionIndex = configuration.extensions.FindIndex((e) => e == item.level.extension) + 1;
                    }
                    else
                    {
                        bool unified = (from i in items select i.level.extension).Distinct().Count() == 1;
                        if (unified)
                        {
                            extensionIndex = configuration.extensions.FindIndex((e) => e == item.level.extension) + 1;
                        }
                    }

                    extensionIndex = MadGUI.DynamicPopup(extensionIndex, "Extension", configuration.extensions.Count + 1,
                                                         (index) => {
                        if (index == 0)
                        {
                            return("(none)");
                        }
                        else
                        {
                            return(configuration.extensions[index - 1].name);
                        }
                    });
                    if (EditorGUI.EndChangeCheck())
                    {
                        MadUndo.RecordObject2(target, "Changed Extension For Level");

                        foreach (var levelItem in items)
                        {
                            if (extensionIndex == 0)
                            {
                                levelItem.level.extension = null;
                            }
                            else
                            {
                                levelItem.level.extension = configuration.extensions[extensionIndex - 1];
                            }
                        }

                        configuration.SetDirty();
                    }

                    bool enabledState = GUI.enabled;
                    GUI.enabled       = true;
                    if (MadGUI.Button("Open Extension Editor", Color.magenta))
                    {
                        MadLevelExtensionEditor.Show(configuration);
                    }
                    GUI.enabled = enabledState;

                    EditorGUILayout.Space();
                }
            }

            EditorGUI.BeginChangeCheck();
            int groupIndex = GroupToIndex(item.level.group);
            groupIndex     = EditorGUILayout.Popup("Move To Group:", groupIndex, GroupNames());
            if (EditorGUI.EndChangeCheck())
            {
                var @group = IndexToGroup(groupIndex);
                MadUndo.RecordObject2(target, "Move Levels To Group " + @group.name);
                foreach (var levelItem in items)
                {
                    levelItem.level.group = @group;
                }
            }


            if (EditorGUI.EndChangeCheck())
            {
                configuration.SetDirty();
            }

            if (inspectorAddons.Count > 0)
            {
                EditorGUILayout.Space();
            }

            foreach (var addon in inspectorAddons)
            {
                addon.OnInspectorGUI(item.level);
            }

            GUI.enabled = true;
        });

        EditorGUILayout.Space();
        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button("Help"))
        {
            Help.BrowseURL(MadLevelHelp.LevelConfigurationHelp);
        }
        GUILayout.FlexibleSpace();
        EditorGUILayout.EndHorizontal();

        if (!configuration.IsValid())
        {
            MadGUI.Error("Configuration is invalid. Please make sure that:\n"
                         + "- There's no levels with \"!!!\" icon. These levels may have duplicated name or missing scene.\n"
                         + "- All your extensions have no missing scenes (in Extension Editor)"
                         );
        }

        if (configuration.active && !MadLevelConfigurationEditor.CheckBuildSynchronized(configuration))
        {
            if (MadGUI.ErrorFix(
                    "Build configuration is not in synch with level configuration.",
                    "Synchronize Now"))
            {
                MadLevelConfigurationEditor.SynchronizeBuild(configuration);
            }
        }

        ExecuteDelayed();
    }
Exemplo n.º 2
0
 public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
 {
     return(EditorGUI.GetPropertyHeight(property, label, true));
 }
Exemplo n.º 3
0
    /// <summary>
    /// Draw the UI for this tool.
    /// </summary>

    void OnGUI()
    {
        Object fnt    = (Object)NGUISettings.FMFont ?? (Object)NGUISettings.BMFont;
        UIFont uiFont = (fnt as UIFont);

        NGUIEditorTools.SetLabelWidth(80f);
        GUILayout.Space(3f);

        NGUIEditorTools.DrawHeader("Input", true);
        NGUIEditorTools.BeginContents(false);

        GUILayout.BeginHorizontal();
        mType = (FontType)EditorGUILayout.EnumPopup("Type", mType, GUILayout.MinWidth(200f));
        NGUIEditorTools.DrawPadding();
        GUILayout.EndHorizontal();
        Create create = Create.None;

        if (mType == FontType.ImportedBitmap)
        {
            NGUISettings.fontData    = EditorGUILayout.ObjectField("Font Data", NGUISettings.fontData, typeof(TextAsset), false) as TextAsset;
            NGUISettings.fontTexture = EditorGUILayout.ObjectField("Texture", NGUISettings.fontTexture, typeof(Texture2D), false, GUILayout.Width(140f)) as Texture2D;
            NGUIEditorTools.EndContents();

            // Draw the atlas selection only if we have the font data and texture specified, just to make it easier
            EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
            {
                NGUIEditorTools.DrawHeader("Output", true);
                NGUIEditorTools.BeginContents(false);
                ComponentSelector.Draw <UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
                NGUIEditorTools.EndContents();
            }
            EditorGUI.EndDisabledGroup();

            if (NGUISettings.fontData == null)
            {
                EditorGUILayout.HelpBox("To create a font from a previously exported FNT file, you need to use BMFont on " +
                                        "Windows or your choice of Glyph Designer or the less expensive bmGlyph on the Mac.\n\n" +
                                        "Either of these tools will create a FNT file for you that you will drag & drop into the field above.", MessageType.Info);
            }
            else if (NGUISettings.fontTexture == null)
            {
                EditorGUILayout.HelpBox("When exporting your font, you should get two files: the FNT, and the texture. Only one texture can be used per font.", MessageType.Info);
            }
            else if (NGUISettings.atlas == null)
            {
                EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
                                        "labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
            }

            EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
            {
                GUILayout.BeginHorizontal();
                GUILayout.Space(20f);
                if (GUILayout.Button("Create the Font"))
                {
                    create = Create.Import;
                }
                GUILayout.Space(20f);
                GUILayout.EndHorizontal();
            }
            EditorGUI.EndDisabledGroup();
        }
        else
        {
            GUILayout.BeginHorizontal();
            if (NGUIEditorTools.DrawPrefixButton("Source"))
            {
                ComponentSelector.Show <Font>(OnUnityFont, new string[] { ".ttf", ".otf" });
            }

            Font ttf = EditorGUILayout.ObjectField(NGUISettings.FMFont, typeof(Font), false) as Font;
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            {
                NGUISettings.FMSize = EditorGUILayout.IntField("Size", NGUISettings.FMSize, GUILayout.Width(120f));

                if (mType == FontType.Dynamic)
                {
                    NGUISettings.fontStyle = (FontStyle)EditorGUILayout.EnumPopup(NGUISettings.fontStyle);
                    NGUIEditorTools.DrawPadding();
                }
            }
            GUILayout.EndHorizontal();

            // Choose the font style if there are multiple faces present
            if (mType == FontType.GeneratedBitmap)
            {
                if (!FreeType.isPresent)
                {
                    string filename = (Application.platform == RuntimePlatform.WindowsEditor) ? "FreeType.dll" : "FreeType.dylib";
                    EditorGUILayout.HelpBox(filename + " is missing", MessageType.Error);

                    GUILayout.BeginHorizontal();
                    GUILayout.Space(20f);

                    if (GUILayout.Button("Find " + filename))
                    {
                        string path = EditorUtility.OpenFilePanel("Find " + filename, NGUISettings.currentPath,
                                                                  (Application.platform == RuntimePlatform.WindowsEditor) ? "dll" : "dylib");

                        if (!string.IsNullOrEmpty(path))
                        {
                            if (System.IO.Path.GetFileName(path) == filename)
                            {
                                NGUISettings.currentPath    = System.IO.Path.GetDirectoryName(path);
                                NGUISettings.pathToFreeType = path;
                            }
                            else
                            {
                                Debug.LogError("The library must be named '" + filename + "'");
                            }
                        }
                    }
                    GUILayout.Space(20f);
                    GUILayout.EndHorizontal();
                }
                else if (ttf != null)
                {
                    string[] faces = FreeType.GetFaces(ttf);

                    if (faces != null)
                    {
                        if (mFaceIndex >= faces.Length)
                        {
                            mFaceIndex = 0;
                        }

                        if (faces.Length > 1)
                        {
                            GUILayout.Label("Style", EditorStyles.boldLabel);
                            for (int i = 0; i < faces.Length; ++i)
                            {
                                GUILayout.BeginHorizontal();
                                GUILayout.Space(10f);
                                if (DrawOption(i == mFaceIndex, " " + faces[i]))
                                {
                                    mFaceIndex = i;
                                }
                                GUILayout.EndHorizontal();
                            }
                        }
                    }

                    NGUISettings.fontKerning = EditorGUILayout.Toggle("Kerning", NGUISettings.fontKerning);

                    GUILayout.Label("Characters", EditorStyles.boldLabel);

                    CharacterMap cm = characterMap;

                    GUILayout.BeginHorizontal(GUILayout.Width(100f));
                    GUILayout.BeginVertical();
                    GUI.changed = false;
                    if (DrawOption(cm == CharacterMap.Numeric, " Numeric"))
                    {
                        cm = CharacterMap.Numeric;
                    }
                    if (DrawOption(cm == CharacterMap.Ascii, " ASCII"))
                    {
                        cm = CharacterMap.Ascii;
                    }
                    if (DrawOption(cm == CharacterMap.Latin, " Latin"))
                    {
                        cm = CharacterMap.Latin;
                    }
                    if (DrawOption(cm == CharacterMap.Custom, " Custom"))
                    {
                        cm = CharacterMap.Custom;
                    }
                    if (GUI.changed)
                    {
                        characterMap = cm;
                    }
                    GUILayout.EndVertical();

                    EditorGUI.BeginDisabledGroup(cm != CharacterMap.Custom);
                    {
                        if (cm != CharacterMap.Custom)
                        {
                            string chars = "";

                            if (cm == CharacterMap.Ascii)
                            {
                                for (int i = 33; i < 127; ++i)
                                {
                                    chars += System.Convert.ToChar(i);
                                }
                            }
                            else if (cm == CharacterMap.Numeric)
                            {
                                chars = "0123456789";
                            }
                            else if (cm == CharacterMap.Latin)
                            {
                                for (int i = 33; i < 127; ++i)
                                {
                                    chars += System.Convert.ToChar(i);
                                }

                                for (int i = 161; i < 256; ++i)
                                {
                                    chars += System.Convert.ToChar(i);
                                }
                            }

                            NGUISettings.charsToInclude = chars;
                        }

                        GUI.changed = false;

                        string text = NGUISettings.charsToInclude;

                        if (cm == CharacterMap.Custom)
                        {
                            text = EditorGUILayout.TextArea(text, GUI.skin.textArea,
                                                            GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
                        }
                        else
                        {
                            GUILayout.Label(text, GUI.skin.textArea,
                                            GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
                        }

                        if (GUI.changed)
                        {
                            string final = "";

                            for (int i = 0; i < text.Length; ++i)
                            {
                                char c = text[i];
                                if (c < 33)
                                {
                                    continue;
                                }
                                string s = c.ToString();
                                if (!final.Contains(s))
                                {
                                    final += s;
                                }
                            }

                            if (final.Length > 0)
                            {
                                char[] chars = final.ToCharArray();
                                System.Array.Sort(chars);
                                final = new string(chars);
                            }
                            else
                            {
                                final = "";
                            }

                            NGUISettings.charsToInclude = final;
                        }
                    }
                    EditorGUI.EndDisabledGroup();
                    GUILayout.EndHorizontal();
                }
            }
            NGUIEditorTools.EndContents();

            if (mType == FontType.Dynamic)
            {
                EditorGUI.BeginDisabledGroup(ttf == null);
                GUILayout.BeginHorizontal();
                GUILayout.Space(20f);
                if (GUILayout.Button("Create the Font"))
                {
                    create = Create.Dynamic;
                }
                GUILayout.Space(20f);
                GUILayout.EndHorizontal();
                EditorGUI.EndDisabledGroup();
#if UNITY_3_5
                EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
#else
                // Helpful info
                if (ttf == null)
                {
                    EditorGUILayout.HelpBox("You don't have to create a UIFont to use dynamic fonts. You can just reference the Unity Font directly on the label.", MessageType.Info);
                }
                EditorGUILayout.HelpBox("Please note that dynamic fonts can't be made a part of an atlas, and using dynamic fonts will result in at least one extra draw call.", MessageType.Warning);
#endif
            }
            else
            {
                bool isBuiltIn = (ttf != null) && string.IsNullOrEmpty(UnityEditor.AssetDatabase.GetAssetPath(ttf));

                // Draw the atlas selection only if we have the font data and texture specified, just to make it easier
                EditorGUI.BeginDisabledGroup(ttf == null || isBuiltIn || !FreeType.isPresent);
                {
                    NGUIEditorTools.DrawHeader("Output", true);
                    NGUIEditorTools.BeginContents(false);
                    ComponentSelector.Draw <UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
                    NGUIEditorTools.EndContents();

                    if (ttf == null)
                    {
                        EditorGUILayout.HelpBox("You can create a bitmap font by specifying a dynamic font to use as the source.", MessageType.Info);
                    }
                    else if (isBuiltIn)
                    {
                        EditorGUILayout.HelpBox("You chose an embedded font. You can't create a bitmap font from an embedded resource.", MessageType.Warning);
                    }
                    else if (NGUISettings.atlas == null)
                    {
                        EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
                                                "labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
                    }

                    GUILayout.BeginHorizontal();
                    GUILayout.Space(20f);
                    if (GUILayout.Button("Create the Font"))
                    {
                        create = Create.Bitmap;
                    }
                    GUILayout.Space(20f);
                    GUILayout.EndHorizontal();
                }
                EditorGUI.EndDisabledGroup();
            }
        }

        if (create == Create.None)
        {
            return;
        }

        // Open the "Save As" file dialog
#if UNITY_3_5
        string prefabPath = EditorUtility.SaveFilePanel("Save As",
                                                        NGUISettings.currentPath, "New Font.prefab", "prefab");
#else
        string prefabPath = EditorUtility.SaveFilePanelInProject("Save As",
                                                                 "New Font.prefab", "prefab", "Save font as...", NGUISettings.currentPath);
#endif
        if (string.IsNullOrEmpty(prefabPath))
        {
            return;
        }
        NGUISettings.currentPath = System.IO.Path.GetDirectoryName(prefabPath);

        // Load the font's prefab
        GameObject go     = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
        Object     prefab = null;
        string     fontName;

        // Font doesn't exist yet
        if (go == null || go.GetComponent <UIFont>() == null)
        {
            // Create a new prefab for the atlas
            prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);

            fontName = prefabPath.Replace(".prefab", "");
            fontName = fontName.Substring(prefabPath.LastIndexOfAny(new char[] { '/', '\\' }) + 1);

            // Create a new game object for the font
            go     = new GameObject(fontName);
            uiFont = go.AddComponent <UIFont>();
        }
        else
        {
            uiFont   = go.GetComponent <UIFont>();
            fontName = go.name;
        }

        if (create == Create.Dynamic)
        {
            uiFont.atlas            = null;
            uiFont.dynamicFont      = NGUISettings.FMFont;
            uiFont.dynamicFontStyle = NGUISettings.fontStyle;
            uiFont.defaultSize      = NGUISettings.FMSize;
        }
        else if (create == Create.Import)
        {
            Material mat = null;

            if (NGUISettings.atlas != null)
            {
                // Add the font's texture to the atlas
                UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, NGUISettings.fontTexture);
            }
            else
            {
                // Create a material for the font
                string matPath = prefabPath.Replace(".prefab", ".mat");
                mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;

                // If the material doesn't exist, create it
                if (mat == null)
                {
                    Shader shader = Shader.Find("Unlit/Transparent Colored");
                    mat = new Material(shader);

                    // Save the material
                    AssetDatabase.CreateAsset(mat, matPath);
                    AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

                    // Load the material so it's usable
                    mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
                }

                mat.mainTexture = NGUISettings.fontTexture;
            }

            uiFont.dynamicFont = null;
            BMFontReader.Load(uiFont.bmFont, NGUITools.GetHierarchy(uiFont.gameObject), NGUISettings.fontData.bytes);

            if (NGUISettings.atlas == null)
            {
                uiFont.atlas    = null;
                uiFont.material = mat;
            }
            else
            {
                uiFont.spriteName = NGUISettings.fontTexture.name;
                uiFont.atlas      = NGUISettings.atlas;
            }
            NGUISettings.FMSize = uiFont.defaultSize;
        }
        else if (create == Create.Bitmap)
        {
            // Create the bitmap font
            BMFont    bmFont;
            Texture2D tex;

            if (FreeType.CreateFont(
                    NGUISettings.FMFont,
                    NGUISettings.FMSize, mFaceIndex,
                    NGUISettings.fontKerning,
                    NGUISettings.charsToInclude, 1, out bmFont, out tex))
            {
                uiFont.bmFont = bmFont;
                tex.name      = fontName;

                if (NGUISettings.atlas != null)
                {
                    // Add this texture to the atlas and destroy it
                    UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, tex);
                    NGUITools.DestroyImmediate(tex);
                    NGUISettings.fontTexture = null;
                    tex = null;

                    uiFont.atlas      = NGUISettings.atlas;
                    uiFont.spriteName = fontName;
                }
                else
                {
                    string texPath = prefabPath.Replace(".prefab", ".png");
                    string matPath = prefabPath.Replace(".prefab", ".mat");

                    byte[]     png = tex.EncodeToPNG();
                    FileStream fs  = File.OpenWrite(texPath);
                    fs.Write(png, 0, png.Length);
                    fs.Close();

                    // See if the material already exists
                    Material mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;

                    // If the material doesn't exist, create it
                    if (mat == null)
                    {
                        Shader shader = Shader.Find("Unlit/Transparent Colored");
                        mat = new Material(shader);

                        // Save the material
                        AssetDatabase.CreateAsset(mat, matPath);
                        AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

                        // Load the material so it's usable
                        mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
                    }
                    else
                    {
                        AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
                    }

                    // Re-load the texture
                    tex = AssetDatabase.LoadAssetAtPath(texPath, typeof(Texture2D)) as Texture2D;

                    // Assign the texture
                    mat.mainTexture          = tex;
                    NGUISettings.fontTexture = tex;

                    uiFont.atlas    = null;
                    uiFont.material = mat;
                }
            }
            else
            {
                return;
            }
        }

        if (prefab != null)
        {
            // Update the prefab
            PrefabUtility.ReplacePrefab(go, prefab);
            DestroyImmediate(go);
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

            // Select the atlas
            go     = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
            uiFont = go.GetComponent <UIFont>();
        }

        if (uiFont != null)
        {
            NGUISettings.FMFont = null;
            NGUISettings.BMFont = uiFont;
        }
        MarkAsChanged();
        Selection.activeGameObject = go;
    }
Exemplo n.º 4
0
        public override void OnInspectorGUI()
        {
            EditorGUILayout.BeginHorizontal();

            if (GUILayout.Button("Paint"))
            {
                Tools.current = Tool.None;
                panel         = 0;
            }

            if (GUILayout.Button("Renderer"))
            {
                panel = 1;
            }

            if (GUILayout.Button("Collider"))
            {
                panel = 2;
            }

            if (GUILayout.Button("Other"))
            {
                panel = 3;
            }
            EditorGUI.BeginChangeCheck();

            EditorGUILayout.EndHorizontal();

            var tmp = (ptTilemap)target;

            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            switch (panel)
            {
            case 0:
                OnInspectorGUI_Paint(tmp);
                EditorGUI.EndChangeCheck();
                EditorGUI.BeginChangeCheck();
                break;

            case 1:
                OnInspectorGUI_Renderer(tmp);
                break;

            case 2:
                OnInspectorGUI_Collider(tmp);
                break;

            case 3:
                OnInspectorGUI_Other(tmp);
                break;

            default:
                panel = 0;
                break;
            }
            EditorGUILayout.EndVertical();

            if (EditorGUI.EndChangeCheck())
            {
                MakeSceneDirty();
            }
        }
Exemplo n.º 5
0
        //Draws Track inspector
        public override void OnInspectorGUI()
        {
            //Updates the Track object
            serializedObject.Update();
            CreateStyles();

            //Banner display
            Rect BannerRect = GUILayoutUtility.GetRect(0.0f, 0.0f);

            BannerRect.height = Screen.width * 250 / 1600;
            GUILayout.Space(BannerRect.height);
            GUI.Label(BannerRect, Banner);

            //Displays Track name
            GUILayout.BeginVertical(BackgroundStyles[0], GUILayout.Height(EditorGUIUtility.singleLineHeight));
            EditorGUILayout.PropertyField(TrackName, new GUIContent("Track Name", "(Optional) The name of the Track."));
            GUILayout.EndVertical();

            //Draws Intro field
            GUILayout.BeginVertical(BackgroundStyles[1], GUILayout.Height((TrackInstance.Intro != null ? 3 : 1) * EditorGUIUtility.singleLineHeight));
            Rect IntroRect = EditorGUILayout.GetControlRect();

            EditorGUI.LabelField(new Rect(IntroRect.x, IntroRect.y, EditorGUIUtility.labelWidth, EditorGUIUtility.singleLineHeight), new GUIContent("Intro Audio", "(Optional) The intro audio to be played before looping the main Edition."));
            EditorGUI.PropertyField(new Rect(IntroRect.x + EditorGUIUtility.labelWidth, IntroRect.y, IntroRect.width - EditorGUIUtility.labelWidth, EditorGUIUtility.singleLineHeight), Intro, GUIContent.none);

            //Full intro details
            if (TrackInstance.Intro != null)
            {
                //Draws intro duration
                EditorGUI.LabelField(new Rect(IntroRect.x + 82, IntroRect.y, EditorGUIUtility.labelWidth - 20 - 82, EditorGUIUtility.singleLineHeight), StringFormatting.FormatTime(TrackInstance.Intro.length), CenteredMiniLabel);

                //Draws Volume slider
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField(new GUIContent("Intro Volume", "The volume of the intro audio."), GUILayout.Width(EditorGUIUtility.labelWidth - 4));
                IntroVolume.floatValue = EditorGUILayout.Slider(IntroVolume.floatValue, 0, 1);
                EditorGUILayout.EndHorizontal();

                //Draws overlap slider
                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField(new GUIContent("Intro Overlap Duration", "Duration of the overlap between the end of the intro and the start of the first Edition."), GUILayout.Width(EditorGUIUtility.labelWidth - 4));
                IntroOverlap.floatValue = EditorGUILayout.Slider(IntroOverlap.floatValue, 0, TrackInstance.Intro.length);
                EditorGUILayout.EndHorizontal();
            }
            GUILayout.EndVertical();

            //Preview
            GUILayout.BeginVertical(BackgroundStyles[0], GUILayout.Height(EditorGUIUtility.singleLineHeight));
            EditorGUILayout.BeginHorizontal();
            GUI.enabled = MusicManager.Main;
            EditorGUILayout.LabelField(new GUIContent("Preview", "Preview options for the Track. Only available at runtime."));
            if (GUILayout.Button(new GUIContent("Play", "Plays the Track.")))
            {
                MusicManager.Main.Play(TrackInstance);
            }
            GUI.enabled = true;
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();

            //Adds new Edition if the list is empty
            if (TrackInstance.Editions.Length == 0)
            {
                TrackInstance.Editions = new Edition[1];
                TrackInstance.Editions[0].SoundtrackVolume = 1f;
                TrackInstance.Editions[0].TransitionVolume = 1f;
            }

            //Enables Edition removal button if more than one is present
            EditionListDisplay.displayRemove = TrackInstance.Editions.Length > 1;

            //Draws list and updates Track
            EditionListDisplay.DoLayoutList();
            serializedObject.ApplyModifiedProperties();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Draws info box of the provided scene
        /// </summary>
        private void DrawSceneInfoGUI(Rect position, BuildUtils.BuildScene buildScene, int sceneControlID)
        {
            bool   readOnly        = BuildUtils.IsReadOnly();
            string readOnlyWarning = readOnly ? "\n\nWARNING: Build Settings is not checked out and so cannot be modified." : "";

            // Label Prefix
            GUIContent iconContent  = new GUIContent();
            GUIContent labelContent = new GUIContent();

            // Missing from build scenes
            if (buildScene.buildIndex == -1)
            {
                iconContent          = EditorGUIUtility.IconContent("d_winbtn_mac_close");
                labelContent.text    = "NOT In Build";
                labelContent.tooltip = "This scene is NOT in build settings.\nIt will be NOT included in builds.";
            }
            // In build scenes and enabled
            else if (buildScene.scene.enabled)
            {
                iconContent          = EditorGUIUtility.IconContent("d_winbtn_mac_max");
                labelContent.text    = "BuildIndex: " + buildScene.buildIndex;
                labelContent.tooltip = "This scene is in build settings and ENABLED.\nIt will be included in builds." + readOnlyWarning;
            }
            // In build scenes and disabled
            else
            {
                iconContent          = EditorGUIUtility.IconContent("d_winbtn_mac_min");
                labelContent.text    = "BuildIndex: " + buildScene.buildIndex;
                labelContent.tooltip = "This scene is in build settings and DISABLED.\nIt will be NOT included in builds.";
            }

            // Left status label
            using (new EditorGUI.DisabledScope(readOnly)) {
                Rect labelRect = DrawUtils.GetLabelRect(position);
                Rect iconRect  = labelRect;
                iconRect.width   = iconContent.image.width + padSize;
                labelRect.width -= iconRect.width;
                labelRect.x     += iconRect.width;
                EditorGUI.PrefixLabel(iconRect, sceneControlID, iconContent);
                EditorGUI.PrefixLabel(labelRect, sceneControlID, labelContent);
            }

            // Right context buttons
            Rect buttonRect = DrawUtils.GetFieldRect(position);

            buttonRect.width = (buttonRect.width) / 3;

            string tooltipMsg = "";

            using (new EditorGUI.DisabledScope(readOnly)) {
                // NOT in build settings
                if (buildScene.buildIndex == -1)
                {
                    buttonRect.width *= 2;
                    int addIndex = EditorBuildSettings.scenes.Length;
                    tooltipMsg = "Add this scene to build settings. It will be appended to the end of the build scenes as buildIndex: " + addIndex + "." + readOnlyWarning;
                    if (DrawUtils.ButtonHelper(buttonRect, "Add...", "Add (buildIndex " + addIndex + ")", EditorStyles.miniButtonLeft, tooltipMsg))
                    {
                        BuildUtils.AddBuildScene(buildScene);
                    }
                    buttonRect.width /= 2;
                    buttonRect.x     += buttonRect.width;
                }
                // In build settings
                else
                {
                    bool   isEnabled   = buildScene.scene.enabled;
                    string stateString = isEnabled ? "Disable" : "Enable";
                    tooltipMsg = stateString + " this scene in build settings.\n" + (isEnabled ? "It will no longer be included in builds" : "It will be included in builds") + "." + readOnlyWarning;

                    if (DrawUtils.ButtonHelper(buttonRect, stateString, stateString + " In Build", EditorStyles.miniButtonLeft, tooltipMsg))
                    {
                        BuildUtils.SetBuildSceneState(buildScene, !isEnabled);
                    }
                    buttonRect.x += buttonRect.width;

                    tooltipMsg = "Completely remove this scene from build settings.\nYou will need to add it again for it to be included in builds!" + readOnlyWarning;
                    if (DrawUtils.ButtonHelper(buttonRect, "Remove...", "Remove from Build", EditorStyles.miniButtonMid, tooltipMsg))
                    {
                        BuildUtils.RemoveBuildScene(buildScene);
                    }
                }
            }

            buttonRect.x += buttonRect.width;

            tooltipMsg = "Open the 'Build Settings' Window for managing scenes." + readOnlyWarning;
            if (DrawUtils.ButtonHelper(buttonRect, "Settings", "Build Settings", EditorStyles.miniButtonRight, tooltipMsg))
            {
                BuildUtils.OpenBuildSettings();
            }
        }
Exemplo n.º 7
0
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        CheckInitialize(property, label);


        var foldoutRect = position;

        foldoutRect.width -= 2 * 50;
        foldoutRect.height = 17f;
        EditorGUI.BeginChangeCheck();
        _foldout = EditorGUI.Foldout(foldoutRect, _foldout, label, true);
        if (EditorGUI.EndChangeCheck())
        {
            EditorPrefs.SetBool(label.text, _foldout);
        }

        float yPos = 17f;

        if (_foldout)
        {
            EditorGUI.LabelField(new Rect(new Vector2(position.position.x, position.position.y + yPos), new Vector2(position.size.x, 17f)), "Count: " + _dict.Count);
            yPos += 17f;
            EditorGUI.BeginChangeCheck();
            GameObject newObj = EditorGUI.ObjectField(new Rect(new Vector2(position.position.x + position.size.x / 2, position.position.y + yPos), new Vector2(position.size.x / 2, 17f)), _nextObject, typeof(GameObject), false) as GameObject;
            if (EditorGUI.EndChangeCheck())
            {
                _nextObject = newObj;
                ValueChanged(property);
            }

            yPos += 20f;
            if (GUI.Button(new Rect(new Vector2(position.position.x + position.size.x * 0.1f, position.position.y + yPos), new Vector2(position.size.x * 0.8f, 17f)), "Add"))
            {
                if (_nextObject == null)
                {
                    Debug.LogWarning("Cannot add empty gameobject here");
                    return;
                }
                else if (_dict.ContainsKey(_nextObject) == false)
                {
                    _dict.Add(_nextObject, new DictionaryIntInt());
                    DictionaryIntIntDrawer newDrawer = new DictionaryIntIntDrawer();
                    newDrawer._dict = _dict[_nextObject];
                    _drawers.Add(_nextObject, newDrawer);
                    _orderedKeys.Add(_nextObject);
                    ValueChanged(property);
                }
                else
                {
                    Debug.LogWarning("This dictionary already contains a value for key " + _nextObject.name);
                }
                return;
            }
            yPos += 17f;

            for (int keyOrder = 0; keyOrder < _orderedKeys.Count; ++keyOrder)
            {
                GameObject       key = _orderedKeys[keyOrder];
                DictionaryIntInt val = _dict[key];
                yPos += 8f;
                if (GUI.Button(new Rect(new Vector2(position.position.x, position.position.y + yPos), new Vector2(17f, 17f)), "-"))
                {
                    _dict.Remove(key);
                    _drawers.Remove(key);
                    _orderedKeys.RemoveAt(keyOrder);
                    ValueChanged(property);
                    return;
                }
                GameObject newObject = EditorGUI.ObjectField(new Rect(new Vector2(position.position.x + 18f, position.position.y + yPos), new Vector2(position.size.x / 2 - 9f, 17f)), key, typeof(GameObject), false) as GameObject;
                if (newObject == null)
                {
                    return;
                }
                if (newObject != key)
                {
                    int        idx      = _orderedKeys.FindIndex((o) => o == key);
                    GameObject oldValue = _orderedKeys[idx];
                    _orderedKeys[idx] = newObject;
                    _dict.Add(newObject, _dict[oldValue]);
                    _dict.Remove(oldValue);
                    _drawers.Add(newObject, _drawers[oldValue]);
                    _drawers.Remove(oldValue);
                    ValueChanged(property);
                    return;
                }
                GUIContent guiContent = new GUIContent("Values");
                yPos += 17f;
                _drawers[key].OnGUI(new Rect(new Vector2(position.position.x + 17f, position.position.y + yPos), new Vector2(position.size.x - 17f, _drawers[key].GetPropertyHeight(null, guiContent))), null, guiContent);
                yPos += _drawers[key].GetPropertyHeight(null, guiContent);
            }
        }
    }
		public override void OnInspectorGUI () {
			animationNameProperty = animationNameProperty ?? serializedObject.FindProperty("animationName");
			string animationName = animationNameProperty.stringValue;

			Animation animation = null;
			if (ThisSkeletonDataAsset != null) {
				var skeletonData = ThisSkeletonDataAsset.GetSkeletonData(true);
				if (skeletonData != null) {
					animation = skeletonData.FindAnimation(animationName);
				}
			} 
			bool animationNotFound = (animation == null);

			if (changeNextFrame) {
				changeNextFrame = false;
				
				if (ThisSkeletonDataAsset != lastSkeletonDataAsset) {
					preview.Clear();
					preview.Initialize(Repaint, ThisSkeletonDataAsset, LastSkinName);

					if (animationNotFound) {
						animationNameProperty.stringValue = "";
						preview.ClearAnimationSetupPose();
					}
				}

				preview.ClearAnimationSetupPose();

				if (!string.IsNullOrEmpty(animationNameProperty.stringValue))
					preview.PlayPauseAnimation(animationNameProperty.stringValue, true);
			}
			lastSkeletonDataAsset = ThisSkeletonDataAsset;

			//EditorGUILayout.HelpBox(AnimationReferenceAssetEditor.InspectorHelpText, MessageType.Info, true);
			EditorGUILayout.Space();
			EditorGUI.BeginChangeCheck();
			DrawDefaultInspector();
			if (EditorGUI.EndChangeCheck()) {
				changeNextFrame = true;
			}

			// Draw extra info below default inspector.
			EditorGUILayout.Space();
			if (ThisSkeletonDataAsset == null) {
				EditorGUILayout.HelpBox("SkeletonDataAsset is missing.", MessageType.Error);
			} else if (string.IsNullOrEmpty(animationName)) {
				EditorGUILayout.HelpBox("No animation selected.", MessageType.Warning);
			} else if (animationNotFound) {
				EditorGUILayout.HelpBox(string.Format("Animation named {0} was not found for this Skeleton.", animationNameProperty.stringValue), MessageType.Warning);
			} else {
				using (new SpineInspectorUtility.BoxScope()) {
					if (!string.Equals(SpineEditorUtilities.GetPathSafeName(animationName), ThisAnimationReferenceAsset.name, System.StringComparison.OrdinalIgnoreCase))
						EditorGUILayout.HelpBox("Animation name value does not match this asset's name. Inspectors using this asset may be misleading.", MessageType.None);

					EditorGUILayout.LabelField(SpineInspectorUtility.TempContent(animationName, SpineEditorUtilities.Icons.animation));
					if (animation != null) {
						EditorGUILayout.LabelField(string.Format("Timelines: {0}", animation.Timelines.Count));
						EditorGUILayout.LabelField(string.Format("Duration: {0} sec", animation.Duration));
					}
				}
			}
		}
		ReorderableList CreateReorderableList(SerializedProperty listProp)
		{
			var list = new ReorderableList(listProp.serializedObject, listProp);
			var recorder = ((UniversalObserver)listProp.serializedObject.targetObject).GetRecorder();

			list.drawHeaderCallback +=
				(Rect position) =>
				{
					EditorGUI.LabelField(position, "Observation Targets");
				};

			list.elementHeightCallback =
				(int index) =>
				{
					if(listProp.arraySize == 0)
						return EditorGUIUtility.singleLineHeight + 10;

					var container = listProp.GetArrayElementAtIndex(index);
					var target = container.FindPropertyRelative("target");
					var keyChain = container.FindPropertyRelative("keys");
					var height = 0f;
					if (target.objectReferenceValue == null || keyChain.arraySize == 0)
					{
						height = EditorGUIUtility.singleLineHeight + 10;
					}
					else
					{
						height = EditorGUIUtility.singleLineHeight * (2 + keyChain.arraySize) + 10;
					}
					return height;
				};

			list.drawElementBackgroundCallback =
				(Rect position, int index, bool selected, bool focused) =>
				{
					position.height = list.elementHeightCallback(index);
					if (focused)
						EditorGUI.DrawRect(position, new Color(0.35f, 0.54f, 0.81f));
					else if (selected)
						EditorGUI.DrawRect(position, new Color(0.6f, 0.6f, 0.6f));
					else if ((index & 1) == 0)
						EditorGUI.DrawRect(position, new Color(0f, 0f, 0f, 0.1f));

				};

			list.drawElementCallback =
				(Rect position, int index, bool selected, bool focused) => 
				{
					var container = listProp.GetArrayElementAtIndex(index);

					var enabled = container.FindPropertyRelative("enabled");
					var target = container.FindPropertyRelative("target");
					var propName = container.FindPropertyRelative("propertyName");
					var keyChain = container.FindPropertyRelative("keys");
					var memberType = container.FindPropertyRelative("memberType");
					var ducTrigger = container.FindPropertyRelative("distinctUntilChanged");
					
					var mPos = new Rect(position);
					mPos.height = EditorGUIUtility.singleLineHeight;
					mPos.y += 5;

					if (target.objectReferenceValue != null)
					{
						mPos.xMin = mPos.xMax - 20;
						enabled.boolValue = EditorGUI.Toggle(mPos, enabled.boolValue);
						mPos.xMin = position.xMin;
					}
					else enabled.boolValue = true;
					EditorGUI.BeginDisabledGroup(!enabled.boolValue);

					var prevName = propName.stringValue;
					var type = TargetSelectField(mPos, target, propName, memberType);
					if (type == null)
					{
						keyChain.arraySize = 0;
					}
					else
					{
						if (prevName != propName.stringValue)
						{
							var reader = TypeReader.Get(type);
							if (reader != null)
							{
								var labels = reader.CreateKeyLabels();
								var prevLength = keyChain.arraySize;
								keyChain.arraySize = labels.Length;
								for (int i = 0; i < keyChain.arraySize; i++)
								{
									var elem = keyChain.GetArrayElementAtIndex(i);
									if (prevLength <= i)
										elem.FindPropertyRelative("key").intValue = -1;
									elem.FindPropertyRelative("label").stringValue = labels[i];
								}
							}
						}

						var recorderObj = new SerializedObject(recorder);
						for (int i = 0; i < keyChain.arraySize; i++)
						{
							var elem = keyChain.GetArrayElementAtIndex(i);
							var label = elem.FindPropertyRelative("label");
							var key = elem.FindPropertyRelative("key");

							mPos.y += mPos.height;
							key.intValue = GraphDataKeyAttributeDrawer.RecorderKeyField(
									mPos, recorderObj, label.stringValue, key.intValue, false);
						}

						mPos.y += mPos.height + 5;
						EditorGUI.PropertyField(mPos, ducTrigger);
					}
					EditorGUI.EndDisabledGroup();
				};
			return list;
		}
Exemplo n.º 10
0
        protected override void OnSceneGUI()
        {
            Handles.color = Blue;
            var constDelta = Mathf.Max(Delta, Delta * HandleUtility.GetHandleSize(Target.transform.position));

            for (float t = 0; t < Target.MaxTime; t += constDelta)
            {
                Handles.DrawLine(Target.GetWorldPoint(t), Target.GetWorldPoint(Mathf.Min(Target.MaxTime, t + constDelta)));
            }

            if (Application.isPlaying)
            {
                return;
            }

            for (int i = 0; i < Target.AnchorsCount; i++)
            {
                var anchorItem = Target.GetAnchorAt(i);
                var handleSize = HandleUtility.GetHandleSize(anchorItem);
                var constSize  = handleSize * AnchorSize;

                if (Event.current.alt)
                {
                    Handles.color = Color.green;
                    if (Handles.Button(anchorItem, Quaternion.identity, constSize, constSize, SphereCap))
                    {
                        var offset = Vector3.forward * handleSize;
                        if (i > 0)
                        {
                            offset = (anchorItem - Target.GetAnchorAt(i - 1)).normalized * handleSize;
                        }

                        Undo.RecordObject(Target, "Insert Anchor");
                        Target.InsertAnchor(i + 1, anchorItem + offset);
                        Target.Rebuild();
                        MarkSceneDirty();
                    }
                }
                else if (Event.current.shift)
                {
                    Handles.color = Color.red;
                    if (Handles.Button(anchorItem, Quaternion.identity, constSize, constSize, SphereCap))
                    {
                        if (Target.AnchorsCount > 1)
                        {
                            Undo.RecordObject(Target, "Remove Anchor");
                            Target.RemoveAnchorAt(i);
                            Target.Rebuild();
                            MarkSceneDirty();
                        }
                    }
                }
                else
                {
                    Handles.color = Blue;
                    EditorGUI.BeginChangeCheck();
                    var position = Handles.FreeMoveHandle(anchorItem, Quaternion.identity, constSize, MoveSnap, SphereCap);
                    if (EditorGUI.EndChangeCheck())
                    {
                        Undo.RecordObject(Target, "Change Anchor Position");
                        Target.SetAnchorAt(i, position);
                        Target.Rebuild();
                        MarkSceneDirty();
                    }
                }
            }
        }
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            //property.isExpanded = EditorGUI.Foldout(new Rect(position.xMin, position.yMin, 15f, EditorGUIUtility.singleLineHeight), property.isExpanded, GUIContent.none);
            position = EditorGUI.PrefixLabel(position, label);


            //START DRAW WITH NO INDENTS
            EditorHelper.SuppressIndentLevel();


            var r0 = new Rect(position.xMin, position.yMin, position.width / 2f, position.height);
            var r1 = new Rect(r0.xMax, r0.yMin, position.width - r0.width, r0.height);

            var matProp      = property.FindPropertyRelative(PROP_MATERIAL);
            var valTypeProp  = property.FindPropertyRelative(PROP_VALUETYPE);
            var memberProp   = property.FindPropertyRelative(PROP_VALUEMEMBER);
            var propNameProp = property.FindPropertyRelative(PROP_PROPERTYNAME);


            EditorGUI.BeginChangeCheck();
            matProp.objectReferenceValue = EditorGUI.ObjectField(r1, matProp.objectReferenceValue, typeof(UnityEngine.Object), true);
            if (EditorGUI.EndChangeCheck())
            {
                if (!MaterialUtil.IsMaterialSource(matProp.objectReferenceValue))
                {
                    var go = GameObjectUtil.GetGameObjectFromSource(matProp.objectReferenceValue);
                    matProp.objectReferenceValue = (go != null) ? go.GetComponent <Renderer>() : null;
                }
            }

            var mat = MaterialUtil.GetMaterialFromSource(matProp.objectReferenceValue);

            if (mat != null && mat.shader != null)
            {
                int cnt = ShaderUtil.GetPropertyCount(mat.shader);
                using (var infoLst = TempCollection.GetList <PropInfo>(cnt))
                    using (var contentLst = TempCollection.GetList <GUIContent>(cnt))
                    {
                        int index = -1;

                        for (int i = 0; i < cnt; i++)
                        {
                            var nm = ShaderUtil.GetPropertyName(mat.shader, i);
                            var tp = ShaderUtil.GetPropertyType(mat.shader, i);

                            switch (tp)
                            {
                            case ShaderUtil.ShaderPropertyType.Float:
                            {
                                if (propNameProp.stringValue == nm)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Float));
                                contentLst.Add(EditorHelper.TempContent(nm + " (float)"));
                            }
                            break;

                            case ShaderUtil.ShaderPropertyType.Range:
                            {
                                if (propNameProp.stringValue == nm)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Float));
                                var min = ShaderUtil.GetRangeLimits(mat.shader, i, 1);
                                var max = ShaderUtil.GetRangeLimits(mat.shader, i, 2);
                                contentLst.Add(EditorHelper.TempContent(string.Format("{0} (Range [{1}, {2}]])", nm, min, max)));
                            }
                            break;

                            case ShaderUtil.ShaderPropertyType.Color:
                            {
                                if (propNameProp.stringValue == nm && memberProp.GetEnumValue <MaterialPropertyValueTypeMember>() == MaterialPropertyValueTypeMember.None)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Color));
                                contentLst.Add(EditorHelper.TempContent(nm + " (color)"));

                                //sub members
                                if (propNameProp.stringValue == nm && memberProp.GetEnumValue <MaterialPropertyValueTypeMember>() == MaterialPropertyValueTypeMember.X)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Color, MaterialPropertyValueTypeMember.X));
                                contentLst.Add(EditorHelper.TempContent(nm + ".r (float)"));

                                if (propNameProp.stringValue == nm && memberProp.GetEnumValue <MaterialPropertyValueTypeMember>() == MaterialPropertyValueTypeMember.Y)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Color, MaterialPropertyValueTypeMember.Y));
                                contentLst.Add(EditorHelper.TempContent(nm + ".g (float)"));

                                if (propNameProp.stringValue == nm && memberProp.GetEnumValue <MaterialPropertyValueTypeMember>() == MaterialPropertyValueTypeMember.Z)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Color, MaterialPropertyValueTypeMember.Z));
                                contentLst.Add(EditorHelper.TempContent(nm + ".b (float)"));

                                if (propNameProp.stringValue == nm && memberProp.GetEnumValue <MaterialPropertyValueTypeMember>() == MaterialPropertyValueTypeMember.W)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Color, MaterialPropertyValueTypeMember.W));
                                contentLst.Add(EditorHelper.TempContent(nm + ".a (float)"));
                            }
                            break;

                            case ShaderUtil.ShaderPropertyType.Vector:
                            {
                                if (propNameProp.stringValue == nm && memberProp.GetEnumValue <MaterialPropertyValueTypeMember>() == MaterialPropertyValueTypeMember.None)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Vector));
                                contentLst.Add(EditorHelper.TempContent(nm + " (vector)"));

                                //sub members
                                if (propNameProp.stringValue == nm && memberProp.GetEnumValue <MaterialPropertyValueTypeMember>() == MaterialPropertyValueTypeMember.X)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Vector, MaterialPropertyValueTypeMember.X));
                                contentLst.Add(EditorHelper.TempContent(nm + ".x (float)"));

                                if (propNameProp.stringValue == nm && memberProp.GetEnumValue <MaterialPropertyValueTypeMember>() == MaterialPropertyValueTypeMember.Y)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Vector, MaterialPropertyValueTypeMember.Y));
                                contentLst.Add(EditorHelper.TempContent(nm + ".y (float)"));

                                if (propNameProp.stringValue == nm && memberProp.GetEnumValue <MaterialPropertyValueTypeMember>() == MaterialPropertyValueTypeMember.Z)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Vector, MaterialPropertyValueTypeMember.Z));
                                contentLst.Add(EditorHelper.TempContent(nm + ".z (float)"));

                                if (propNameProp.stringValue == nm && memberProp.GetEnumValue <MaterialPropertyValueTypeMember>() == MaterialPropertyValueTypeMember.W)
                                {
                                    index = infoLst.Count;
                                }
                                infoLst.Add(new PropInfo(nm, MaterialPropertyValueType.Vector, MaterialPropertyValueTypeMember.W));
                                contentLst.Add(EditorHelper.TempContent(nm + ".w (float)"));
                            }
                            break;
                            }
                        }

                        EditorGUI.BeginChangeCheck();
                        index = EditorGUI.Popup(r0, index, contentLst.ToArray());

                        if (EditorGUI.EndChangeCheck())
                        {
                            if (index < 0)
                            {
                                valTypeProp.SetEnumValue(MaterialPropertyValueType.Float);
                                memberProp.SetEnumValue(MaterialPropertyValueTypeMember.None);
                                propNameProp.stringValue = string.Empty;
                            }
                            else
                            {
                                var info = infoLst[index];
                                valTypeProp.SetEnumValue(info.ValueType);
                                memberProp.SetEnumValue(info.MemberType);
                                propNameProp.stringValue = info.Name;
                            }
                        }
                    }
            }


            //SET INDENT BACK
            EditorHelper.ResumeIndentLevel();
        }
Exemplo n.º 12
0
            public static bool Toggle(bool toggle)
            {
                var rect = EditorGUILayout.GetControlRect(false, 16, Styles.ShurikenToggle, GUILayout.MinWidth(248));

                return(EditorGUI.Toggle(rect, GUIContent.none, toggle, Styles.ShurikenToggle));
            }
Exemplo n.º 13
0
    // Called when updating the Scene view
    void OnSceneGUI(SceneView sceneview)
    {
        if (root == null)
        {
            CreateLevelRoot();
        }

        Event e = Event.current;

        #region KeyDown
        //if (e.type == EventType.KeyDown)
        //{
        //    switch (e.keyCode)
        //    {
        //        case KeyCode.Alpha0:
        //            PlacingMode = PlacingModes.Off;
        //            break;
        //        case KeyCode.Alpha1:
        //            PlacingMode = PlacingModes.Single;
        //            break;
        //        case KeyCode.Alpha2:
        //            PlacingMode = PlacingModes.Arc;
        //            break;
        //        case KeyCode.Alpha3:
        //            PlacingMode = PlacingModes.Wall;
        //            break;
        //        case KeyCode.Alpha4:
        //            PlacingMode = PlacingModes.Ring;
        //            break;
        //        default:
        //            break;
        //    }
        //}
        #endregion KeyDown


        #region MouseMove
        if (e.type == EventType.MouseMove)
        {
            switch (PlacingMode)
            {
            case PlacingModes.Off:
                if (ghost != null)
                {
                    RemoveGhosts();
                }
                break;

            case PlacingModes.Single:
                // Place or move ghost
                if (ghost == null)
                {
                    RemoveGhosts();
                    PlaceSingleGhost(ScreenToWorldSnap(e.mousePosition));
                }
                else
                {
                    UpdateSingleGhost(ScreenToWorldSnap(e.mousePosition));
                }
                break;

            case PlacingModes.Arc:
                if (arcPlacingStarted)
                {
                    if (ghost == null)
                    {
                        arcPlacingStarted = false;
                    }
                    else
                    {
                        UpdateArcGhost(ScreenToWorldSnap(e.mousePosition));

                        if (drawGuides)
                        {
                            Handles.DrawWireDisc(Vector3.zero, Vector3.forward, arcRadius);
                        }
                    }
                }
                else
                {
                    if (ghost == null)
                    {
                        RemoveGhosts();
                        PlaceSingleGhost(ScreenToWorldSnap(e.mousePosition));
                    }
                    else
                    {
                        UpdateSingleGhost(ScreenToWorldSnap(e.mousePosition));
                    }
                }
                break;

            case PlacingModes.Wall:
                if (wallPlacingStarted)
                {
                    if (ghost == null)
                    {
                        wallPlacingStarted = false;
                    }
                    else
                    {
                        UpdateWallGhost(ScreenToWorldSnap(e.mousePosition));
                    }
                }
                else
                {
                    if (ghost == null)
                    {
                        RemoveGhosts();
                        PlaceSingleGhost(ScreenToWorldSnap(e.mousePosition));
                    }
                    else
                    {
                        UpdateSingleGhost(ScreenToWorldSnap(e.mousePosition));
                    }
                }
                break;

            case PlacingModes.Ring:
                if (ghost == null)
                {
                    RemoveGhosts();
                    PlaceSingleGhost(ScreenToWorldSnap(e.mousePosition));
                }
                else
                {
                    UpdateSingleGhost(ScreenToWorldSnap(e.mousePosition));
                }
                break;

            default:
                break;
            }
        }
        #endregion KeyDown


        #region MouseDown
        if (e.type == EventType.MouseDown)
        {
            if (e.button == 0)
            {
                switch (PlacingMode)
                {
                case PlacingModes.Off:
                    break;

                case PlacingModes.Single:
                {
                    InventoryEntry entry     = inventory[selectedItem];
                    Vector3        pos       = ScreenToWorldSnap(e.mousePosition);
                    GameObject     newObject = Instantiate(entry.prefab, pos, GetRotator(pos), rootTransform);
                    if (entry.isArc)
                    {
                        float rad = pos.magnitude;
                        try
                        {
                            newObject.GetComponent <ArcMesh>().SetParams(rad - radialThickness, rad, 1, GetAngularGridDensity(rad), 768, 0);
                        }
                        catch { }
                        Undo.RegisterCreatedObjectUndo(newObject, "Place Segment");
                    }
                    else
                    {
                        Undo.RegisterCreatedObjectUndo(newObject, "Place " + entry.displayName);
                    }
                    break;
                }

                case PlacingModes.Arc:
                {
                    if (arcPlacingStarted)
                    {
                        arcPlacingStarted = false;
                        DestroyImmediate(ghost.GetComponent <GhostPlaceholder>());
                        ghost.hideFlags        = 0;
                        ghost.transform.parent = rootTransform;
                        Undo.RegisterCreatedObjectUndo(ghost, "Place Arc");
                        ghost = null;
                    }
                    else
                    {
                        DestroyImmediate(ghost);
                        RemoveGhosts();

                        arcFirstPosition  = ScreenToWorldSnap(e.mousePosition);
                        arcRadius         = arcFirstPosition.magnitude;
                        arcPlacingStarted = true;
                        PlaceArcGhost();

                        if (drawGuides)
                        {
                            Handles.DrawWireDisc(Vector3.zero, Vector3.back, arcRadius);
                        }
                    }
                    break;
                }

                case PlacingModes.Wall:
                {
                    if (wallPlacingStarted)
                    {
                        // TODO:
                        //PlaceWall(wallFirstPosition, ScreenToWorldSnap(e.mousePosition));
                        wallPlacingStarted = false;
                        DestroyImmediate(ghost.GetComponent <GhostPlaceholder>());
                        ghost.hideFlags        = 0;
                        ghost.transform.parent = rootTransform;
                        Undo.RegisterCreatedObjectUndo(ghost, "Place Wall");
                        ghost = null;
                    }
                    else
                    {
                        DestroyImmediate(ghost);
                        RemoveGhosts();

                        wallFirstPosition  = ScreenToWorldSnap(e.mousePosition);
                        wallFirstRadius    = wallFirstPosition.magnitude;
                        wallPlacingStarted = true;
                        PlaceWallGhost();
                    }
                    break;
                }

                case PlacingModes.Ring:
                    PlaceRing(ScreenToWorldSnap(e.mousePosition));
                    break;

                default:
                    break;
                }
            }
        }
        #endregion MouseDown


        #region Guides
        switch (PlacingMode)
        {
        case PlacingModes.Off:
            break;

        case PlacingModes.Single:
            if (ghost != null)
            {
                float rad = ghost.transform.position.magnitude;
                if (drawGuides)
                {
                    Handles.DrawWireDisc(Vector3.back * 2f, Vector3.back, rad);
                }
                if (drawGuides)
                {
                    Handles.DrawWireDisc(Vector3.back * 2f, Vector3.back, rad - radialThickness);
                }
            }
            break;

        case PlacingModes.Arc:
            if (ghost != null)
            {
                float rad = ghost.transform.position.magnitude;
                if (drawGuides)
                {
                    Handles.DrawWireDisc(Vector3.back * 2f, Vector3.back, rad);
                }
                if (drawGuides)
                {
                    Handles.DrawWireDisc(Vector3.back * 2f, Vector3.back, rad - radialThickness);
                }
            }
            break;

        case PlacingModes.Wall:
            if (ghost != null)
            {
                if (wallPlacingStarted)
                {
                    if (drawGuides)
                    {
                        Handles.DrawWireDisc(Vector3.back * 2f, Vector3.back, wallOuterRadius);
                    }
                    if (drawGuides)
                    {
                        Handles.DrawWireDisc(Vector3.back * 2f, Vector3.back, wallInnerRadius);
                    }
                }
                else
                {
                    float rad = ghost.transform.position.magnitude;
                    if (drawGuides)
                    {
                        Handles.DrawWireDisc(Vector3.back * 2f, Vector3.back, rad);
                    }
                    if (drawGuides)
                    {
                        Handles.DrawWireDisc(Vector3.back * 2f, Vector3.back, rad - radialThickness);
                    }
                }
            }
            break;

        case PlacingModes.Ring:
            if (ghost != null)
            {
                float rad = ghost.transform.position.magnitude;
                if (drawGuides)
                {
                    Handles.DrawWireDisc(Vector3.back * 2f, Vector3.back, rad);
                }
                if (drawGuides)
                {
                    Handles.DrawWireDisc(Vector3.back * 2f, Vector3.back, rad - radialThickness);
                }
            }
            break;

        default:
            break;
        }
        #endregion Guides


        #region Handles
        if (PlacingMode == PlacingModes.Off && Tools.current != Tool.View)
        {
            Object[] objects = Selection.GetFiltered(typeof(GameObject), SelectionMode.Editable | SelectionMode.Deep | SelectionMode.ExcludePrefab);
            if (objects.Length > 0)
            {
                float   tangentialDiscRadius = 0;
                Vector3 centerPosition       = Vector3.zero;
                foreach (GameObject obj in objects)
                {
                    float objRadius = obj.transform.position.magnitude;
                    if (objRadius > tangentialDiscRadius)
                    {
                        tangentialDiscRadius = objRadius;
                    }
                    centerPosition += obj.transform.position.WithZ(0f);
                }
                Vector3 centerDirection = Vector3.Normalize(centerPosition);
                if (tangentialDiscRadius == 0)
                {
                    tangentialDiscRadius = 1;
                    centerDirection      = Vector3.down;
                }
                centerPosition = centerDirection * tangentialDiscRadius;

                Color defColor = Handles.color;
                Handles.color = Color.magenta;

                #region Tangential handle
                EditorGUI.BeginChangeCheck();
                tangentialDiscCurrentRotation = Handles.Disc(tangentialDiscCurrentRotation, Vector3.back * 2f, Vector3.back, tangentialDiscRadius, false, 360f / GetAngularGridDensity(tangentialDiscRadius));
                if (EditorGUI.EndChangeCheck())
                {
                    float angle = tangentialDiscPreviousRotation.eulerAngles.z - tangentialDiscCurrentRotation.eulerAngles.z;
                    MoveSelectionTangential(angle);
                    tangentialDiscPreviousRotation = tangentialDiscCurrentRotation;
                }
                #endregion Tangential handle

                #region Radial handle
                EditorGUI.BeginChangeCheck();
                Vector3 newCenterPosition = Handles.Slider(centerPosition, -centerDirection, HandleUtility.GetHandleSize(centerPosition) * 1.4f, Handles.ArrowHandleCap, radialThickness);
                if (EditorGUI.EndChangeCheck())
                {
                    float deltaRadius = (newCenterPosition - centerPosition).Dot(centerDirection);
                    MoveSelectionRadial(deltaRadius);
                }
                #endregion Radial handle

                Handles.color = defColor;
            }
        }
        #endregion Handles

        //radiusTest = Handles.RadiusHandle(Quaternion.identity, Vector3.zero, radiusTest);
        //doPositionTest = Handles.DoPositionHandle(doPositionTest, FaceAxis.GetRotator(doPositionTest));
        //freeMoveTest = Handles.FreeMoveHandle(freeMoveTest, FaceAxis.GetRotator(freeMoveTest),0.5f, Vector3.one*0.6f, Handles.CylinderHandleCap);
        //positionTest = Handles.PositionHandle(positionTest, FaceAxis.GetRotator(positionTest));
    }
Exemplo n.º 14
0
    /// <summary>
    /// Helper function that draws the suffix after the relative fields.
    /// </summary>

    protected void DrawAnchor(int index, bool targetSelection)
    {
        //if (targetSelection) GUILayout.Space(3f);

        //NGUIEditorTools.SetLabelWidth(16f);
        GUILayout.BeginHorizontal();
        GUILayout.Label(PrefixName[index], GUILayout.Width(NGUISettings.minimalisticLook ? 65f : 56f));

        UIRect myRect = serializedObject.targetObject as UIRect;
        string name   = FieldName[index];

        SerializedProperty tar = serializedObject.FindProperty(name + ".target");
        SerializedProperty rel = serializedObject.FindProperty(name + ".relative");
        SerializedProperty abs = serializedObject.FindProperty(name + ".absolute");

        if (targetSelection)
        {
            Object before = tar.objectReferenceValue;
            NGUIEditorTools.DrawProperty("", tar, false, GUILayout.MinWidth(20f));
            Object after = tar.objectReferenceValue;

            if (after != null || tar.hasMultipleDifferentValues)
            {
                if (before != after && after != null)
                {
                    UpdateAnchor(index, true);
                }
            }

            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Label(" ", GUILayout.Width(NGUISettings.minimalisticLook ? 65f : 56f));
        }

        UIRect targetRect     = GetRect(tar);
        Camera targetCam      = GetCamera(tar);
        float  relative       = rel.floatValue;
        bool   isCommon       = (targetRect == null && targetCam == null) || IsCommon(relative);
        int    previousOrigin = 1;

        if (targetRect != null || targetCam != null)
        {
            if (mCustom[index] || !isCommon)
            {
                previousOrigin = 3;
            }
            else if (relative == 0f)
            {
                previousOrigin = 0;
            }
            else if (relative == 1f)
            {
                previousOrigin = 2;
            }
        }

        // Draw the origin selection list
        EditorGUI.BeginDisabledGroup(targetRect == null && targetCam == null);
        int newOrigin = IsHorizontal[index] ?
                        EditorGUILayout.Popup(previousOrigin, HorizontalList) :
                        EditorGUILayout.Popup(previousOrigin, VerticalList);

        EditorGUI.EndDisabledGroup();

        // "Set to Current" choice
        if (newOrigin == 4)
        {
            newOrigin = 3;

            Vector3[] sides = targetRect.GetSides(myRect.cachedTransform);

            float f0, f1;

            if (IsHorizontal[index])
            {
                f0 = sides[0].x;
                f1 = sides[2].x;
            }
            else
            {
                f0 = sides[3].y;
                f1 = sides[1].y;
            }

            // Final position after both relative and absolute values are taken into consideration
            float final = Mathf.Floor(0.5f + Mathf.Lerp(0f, f1 - f0, rel.floatValue) + abs.intValue);

            rel.floatValue = final / (f1 - f0);
            abs.intValue   = 0;

            serializedObject.ApplyModifiedProperties();
            serializedObject.Update();
        }

        mCustom[index] = (newOrigin == 3);

        // If the origin changes
        if (newOrigin != 3 && previousOrigin != newOrigin)
        {
            // Desired relative value
            if (newOrigin == 0)
            {
                relative = 0f;
            }
            else if (newOrigin == 2)
            {
                relative = 1f;
            }
            else
            {
                relative = 0.5f;
            }

            Vector3[] sides = (targetRect != null) ?
                              targetRect.GetSides(myRect.cachedTransform) :
                              targetCam.GetSides(myRect.cachedTransform);

            // Calculate the current position based from the bottom-left
            float f0, f1;

            if (IsHorizontal[index])
            {
                f0 = sides[0].x;
                f1 = sides[2].x;
            }
            else
            {
                f0 = sides[3].y;
                f1 = sides[1].y;
            }

            // Final position after both relative and absolute values are taken into consideration
            float final = Mathf.Floor(0.5f + Mathf.Lerp(f0, f1, rel.floatValue) + abs.intValue);

            rel.floatValue = relative;
            abs.intValue   = Mathf.FloorToInt(final + 0.5f - Mathf.Lerp(f0, f1, relative));

            serializedObject.ApplyModifiedProperties();
            serializedObject.Update();
        }

        if (mCustom[index])
        {
            // Draw the relative value
            GUILayout.EndHorizontal();
            GUILayout.BeginHorizontal();
            GUILayout.Space(64f);

            relative = rel.floatValue;
            bool isOutside01 = relative <0f || relative> 1f;

            // Horizontal slider for relative values, for convenience
            //EditorGUI.BeginDisabledGroup(isOutside01);
            {
                GUILayout.Space(10f);
                float val = GUILayout.HorizontalSlider(relative, 0f, 1f);

                NGUIEditorTools.DrawProperty("", rel, false, GUILayout.Width(40f));

                if (!isOutside01 && val != relative)
                {
                    Vector3[] sides = (targetRect != null) ?
                                      targetRect.GetSides(myRect.cachedTransform) :
                                      targetCam.GetSides(myRect.cachedTransform);

                    // Calculate the current position based from the bottom-left
                    float f0, f1;

                    if (IsHorizontal[index])
                    {
                        f0 = sides[0].x;
                        f1 = sides[2].x;
                    }
                    else
                    {
                        f0 = sides[3].y;
                        f1 = sides[1].y;
                    }

                    float size   = (f1 - f0);
                    int   intVal = Mathf.FloorToInt(val * size + 0.5f);
                    //intVal = ((intVal >> 1) << 1);
                    rel.floatValue = (size > 0f) ? intVal / size : 0.5f;
                }
            }
            //EditorGUI.EndDisabledGroup();
        }

        // Draw the absolute value
        NGUIEditorTools.SetLabelWidth(16f);
        NGUIEditorTools.DrawProperty("+", abs, false, GUILayout.Width(60f));

        GUILayout.EndHorizontal();
        NGUIEditorTools.SetLabelWidth(NGUISettings.minimalisticLook ? 69f : 62f);
    }
Exemplo n.º 15
0
        bool DrawActionSettings(SerializedProperty property, bool expanded)
        {
            if (mFoldoutStyle == null)
            {
                mFoldoutStyle = new GUIStyle(EditorStyles.foldout)
                {
                    fontStyle = FontStyle.Bold
                }
            }
            ;

            Rect r = EditorGUILayout.GetControlRect();

            expanded = EditorGUI.Foldout(r, expanded, property.displayName, mFoldoutStyle);
            if (expanded)
            {
                SerializedProperty actionProp = property.FindPropertyRelative(() => def.m_Action);
                EditorGUILayout.PropertyField(actionProp);

                SerializedProperty targetProp = property.FindPropertyRelative(() => def.m_Target);
                bool isCustom = (actionProp.intValue == (int)CinemachineTriggerAction.ActionSettings.Mode.Custom);
                if (!isCustom)
                {
                    EditorGUILayout.PropertyField(targetProp);
                }

                bool isBoost = actionProp.intValue == (int)CinemachineTriggerAction.ActionSettings.Mode.PriorityBoost;
                if (isBoost)
                {
                    EditorGUILayout.PropertyField(property.FindPropertyRelative(() => def.m_BoostAmount));
                }

                bool isPlay = actionProp.intValue == (int)CinemachineTriggerAction.ActionSettings.Mode.Play;
                if (isPlay)
                {
                    SerializedProperty[] props = new SerializedProperty[2]
                    {
                        property.FindPropertyRelative(() => def.m_StartTime),
                        property.FindPropertyRelative(() => def.m_Mode)
                    };
                    GUIContent[] sublabels = new GUIContent[2]
                    {
                        GUIContent.none, new GUIContent("s", props[1].tooltip)
                    };
                    InspectorUtility.MultiPropertyOnLine(
                        EditorGUILayout.GetControlRect(), null, props, sublabels);
                }

                if (actionProp.intValue == (int)CinemachineTriggerAction.ActionSettings.Mode.Custom)
                {
                    EditorGUILayout.HelpBox("Use the Event() list below to call custom methods", MessageType.Info);
                }

                if (isBoost)
                {
                    if (GetTargetComponent <CinemachineVirtualCameraBase>(targetProp.objectReferenceValue) == null)
                    {
                        EditorGUILayout.HelpBox("Target must be a CinemachineVirtualCameraBase in order to boost priority", MessageType.Warning);
                    }
                }

                bool isEnableDisable = (actionProp.intValue == (int)CinemachineTriggerAction.ActionSettings.Mode.Enable ||
                                        actionProp.intValue == (int)CinemachineTriggerAction.ActionSettings.Mode.Disable);
                if (isEnableDisable)
                {
                    var value = targetProp.objectReferenceValue;
                    if (value != null && (value as Behaviour) == null)
                    {
                        EditorGUILayout.HelpBox("Target must be a Behaviour in order to Enable/Disable", MessageType.Warning);
                    }
                }

                bool isPlayStop = isPlay ||
                                  actionProp.intValue == (int)CinemachineTriggerAction.ActionSettings.Mode.Stop;
                if (isPlayStop)
                {
                    if (GetTargetComponent <Animator>(targetProp.objectReferenceValue) == null &&
                        GetTargetComponent <PlayableDirector>(targetProp.objectReferenceValue) == null)
                    {
                        EditorGUILayout.HelpBox("Target must have a PlayableDirector or Animator in order to Play/Stop", MessageType.Warning);
                    }
                }

                if (!isCustom && targetProp.objectReferenceValue == null)
                {
                    EditorGUILayout.HelpBox("No action will be taken because target is not valid", MessageType.Info);
                }

                EditorGUILayout.Space();
                EditorGUILayout.LabelField("This event will be invoked.  Add calls to custom methods here:");
                EditorGUILayout.PropertyField(property.FindPropertyRelative(() => def.m_Event));
            }
            property.serializedObject.ApplyModifiedProperties();
            return(expanded);
        }

        T GetTargetComponent <T>(UnityEngine.Object obj) where T : Behaviour
        {
            UnityEngine.Object currentTarget = obj;
            if (currentTarget != null)
            {
                GameObject targetGameObject = currentTarget as GameObject;
                Behaviour  targetBehaviour  = currentTarget as Behaviour;
                if (targetBehaviour != null)
                {
                    targetGameObject = targetBehaviour.gameObject;
                }
                if (targetBehaviour is T)
                {
                    return(targetBehaviour as T);
                }
                if (targetGameObject != null)
                {
                    return(targetGameObject.GetComponent <T>());
                }
            }
            return(null);
        }
    }
Exemplo n.º 16
0
        private void DrawLayerEntry(ImportLayerData layer, DisplayLayerData display)
        {
            bool     isGroup    = display.isGroup;
            bool     isSelected = quickSelect.Contains(layer.indexId);
            GUIStyle entryStyle = isSelected ? styleLayerSelected : styleLayerEntry;

            using (new GUILayout.HorizontalScope(entryStyle, layerHeight))
            {
                Rect rEntry = GUILayoutUtility.GetRect(rTableSize.x, rTableSize.x, rTableSize.y, rTableSize.y);

                Rect rToggle = new Rect(rImportToggle);
                Rect rVis    = new Rect(rVisible);
                Rect rLayer  = new Rect(rLayerDisplay);
                Rect rPiv    = new Rect(rPivot);
                Rect rScale  = new Rect(rScaling);
                Rect rReset  = new Rect(rMakeDefault);
                rToggle.y += rEntry.y;
                rVis.y    += rEntry.y;
                rLayer.y  += rEntry.y;
                rPiv.y    += rEntry.y;
                rScale.y  += rEntry.y;
                rReset.y  += rEntry.y;

                bool parentWillImport = ParentWillImport(layer.indexId);

                using (new EditorGUI.DisabledScope(parentWillImport == false))
                {
                    var displayImport = layer.import && parentWillImport;

                    EditorGUI.BeginChangeCheck();
                    displayImport = GUI.Toggle(rToggle, displayImport, GUIContent.none);

                    if (EditorGUI.EndChangeCheck() && parentWillImport)
                    {
                        layer.import = displayImport;
                        CollateImportList();
                        quickSelect.Clear();
                        selectionCount    = 0;
                        lastSelectedLayer = null;
                    }
                }

                using (new EditorGUI.DisabledScope(true))
                {
                    var visStyle = display.isVisible ? styleVisOn : styleVisOff;
                    GUI.Label(rVis, GUIContent.none, visStyle);
                }

                rLayer.xMin += indentLevel * indentWidth;

                GUIContent layerContent = new GUIContent()
                {
                    image = isGroup ? icnFolder : icnTexture,
                    text  = layer.name
                };

                if (isGroup)
                {
                    float min, max;
                    EditorStyles.popup.CalcMinMaxWidth(layerContent, out min, out max);
                    rLayer.width   = min;
                    display.isOpen = EditorGUI.Foldout(rLayer, display.isOpen, layerContent);
                }
                else
                {
                    EditorGUI.LabelField(rLayer, layerContent);

                    if (isAdvancedMode)
                    {
                        DrawLayerAdvanced(layer, rPiv, rScale, rReset);
                    }
                }
            }

            Rect layerRect = GUILayoutUtility.GetLastRect();

            layerRect.xMin += 40;
            layerRectLookup.Add(layer.indexId, layerRect);
            layerEntryYMax = Mathf.Max(layerEntryYMax, layerRect.yMax);
        }
Exemplo n.º 17
0
        protected override void DrawSelection(Box cardInfo, Components.CharacterSO character)
        {
            EditorGUI.BeginChangeCheck();

            serializedObject.UpdateIfRequiredOrScript();
            SerializedProperty iterator = serializedObject.GetIterator();

            for (bool enterChildren = true; iterator.NextVisible(enterChildren); enterChildren = false)
            {
                if (iterator.name != "id")
                {
                    PropertyField prop = new PropertyField(iterator);
                    prop.Bind(serializedObject);
                    cardInfo.Add(prop);
                }
                else
                {
                    Debug.Log(iterator.propertyPath);
                    _choiceIndex = Array.FindIndex(m_PopulatedList.Keys.ToArray(), idx => idx == character.ID);

                    PopupField <uint> popupField = new PopupField <uint>("ID", m_PopulatedList.Keys.ToList(), _choiceIndex)
                    {
                        bindingPath                 = "id",
                        formatListItemCallback      = i => m_PopulatedList[i],
                        formatSelectedValueCallback = i => m_PopulatedList[i]
                    };

                    popupField.RegisterValueChangedCallback(evt =>
                    {
                        if (evt.newValue >= 0 && ItemListView.Selected != null)
                        {
                            if (ItemListView.Selected.ID != evt.newValue)
                            {
                                // TODO split these two arrays
                                // Update the selected choice in the underlying object
                                character.ID = evt.newValue;

                                OnChanged();

                                serializedObject.Update();
                                serializedObject.ApplyModifiedProperties();

                                EditorUtility.SetDirty(character);
                                SceneView.RepaintAll();
                            }
                        }
                    });

                    popupField.BindProperty(serializedObject);
                    cardInfo.Add(popupField);
                }
                using (new EditorGUI.DisabledScope("m_Script" == iterator.propertyPath))
                    EditorGUILayout.PropertyField(iterator, true);
            }
            serializedObject.ApplyModifiedProperties();
            EditorGUI.EndChangeCheck();

            /*
             * SerializedProperty serializedProperty = serializedObject.GetIterator();
             * serializedProperty.Next(true);
             *
             * while (serializedProperty.NextVisible(false))
             * {
             *      PropertyField prop = new PropertyField(serializedProperty);
             *      prop.SetEnabled(serializedProperty.name != "m_Script");
             *      prop.Bind(serializedObject);
             *      cardInfo.Add(prop);
             * }
             */
        }
        private void CreateToggles(int x, int y, Rect layout, ref GardenTemplate dungeon)
        {
            int index = CalculateCurrentIndex(dungeon, x, y);

            dungeon[index] = EditorGUI.Toggle(layout, dungeon[index]);
        }
Exemplo n.º 19
0
		public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
		{
			var spaceAttribute = attribute as SpaceAttribute;
			return EditorGUI.GetPropertyHeight(property, label) + spaceAttribute.space;
		}
Exemplo n.º 20
0
        /// <summary>Draws the sub-inspector for an Edition.</summary>
        /// <param name="DrawRect">The rect in the list display that this Edition has to be drawn in.</param>
        /// <param name="Index">The index of this Edition in the Track.</param>
        /// <param name="IsActive">If the Edition is actively selected.</param>
        /// <param name="IsFocused">If the Edition is in focus.</param>
        private void DrawEditionInspector(Rect DrawRect, int Index, bool IsActive, bool IsFocused)
        {
            //Shifts rect to create border
            DrawRect.y += 2;

            //Calculates commonly used spacings
            float Spacing      = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
            float LabelWidth   = EditorGUIUtility.labelWidth - 20;
            float FieldPadding = 20f;

            //Starts counter for current displayed property
            int PropertyIndex = 0;

            //Caches serialised properties
            SerializedProperty CurrentEdition           = EditionListDisplay.serializedProperty.GetArrayElementAtIndex(Index);
            SerializedProperty NameProperty             = CurrentEdition.FindPropertyRelative("Name");
            SerializedProperty SoundtrackProperty       = CurrentEdition.FindPropertyRelative("Soundtrack");
            SerializedProperty SoundtrackVolumeProperty = CurrentEdition.FindPropertyRelative("SoundtrackVolume");
            SerializedProperty TransitionSoundProperty  = CurrentEdition.FindPropertyRelative("TransitionSound");
            SerializedProperty TransitionVolumeProperty = CurrentEdition.FindPropertyRelative("TransitionVolume");
            SerializedProperty PlaybackProperty         = CurrentEdition.FindPropertyRelative("KeepPlaybackTime");
            SerializedProperty FadeProperty             = CurrentEdition.FindPropertyRelative("FadeLength");

            //Draws a property with a custom style
            Action <SerializedProperty, string, string, GUIStyle> DrawPropertyStyled = (SerializedProperty Property, string PropertyName, string Tooltip, GUIStyle TextStyle) =>
            {
                //Draws label
                EditorGUI.LabelField(new Rect(DrawRect.x, (PropertyIndex + 1) * Spacing + DrawRect.y, LabelWidth, EditorGUIUtility.singleLineHeight), new GUIContent(PropertyName, Tooltip), TextStyle);

                //Draws property field
                EditorGUI.PropertyField(new Rect(DrawRect.x + LabelWidth, (PropertyIndex + 1) * Spacing + DrawRect.y, DrawRect.width - LabelWidth - FieldPadding, EditorGUIUtility.singleLineHeight), Property, GUIContent.none);

                //Increments property counter
                PropertyIndex++;
            };

            //Draws a slider for a volume property
            Action <SerializedProperty, string, string> DrawVolumeSlider = (SerializedProperty Property, string PropertyName, string Tooltip) =>
            {
                //Draws label
                EditorGUI.LabelField(new Rect(DrawRect.x, (PropertyIndex + 1) * Spacing + DrawRect.y, LabelWidth, EditorGUIUtility.singleLineHeight), new GUIContent(PropertyName, Tooltip));

                //Draws the slider
                Property.floatValue = EditorGUI.Slider(new Rect(DrawRect.x + LabelWidth, (PropertyIndex + 1) * Spacing + DrawRect.y, DrawRect.width - LabelWidth - FieldPadding, EditorGUIUtility.singleLineHeight), Property.floatValue, 0, 1f);

                //Increments property counter
                PropertyIndex++;
            };

            //Draws a property
            Action <SerializedProperty, string, string> DrawProperty = (SerializedProperty Property, string PropertyName, string Tooltip) =>
            {
                DrawPropertyStyled(Property, PropertyName, Tooltip, EditorStyles.label);
            };

            //Gets and draws edition name
            string Name = NameProperty.stringValue;

            if (string.IsNullOrEmpty(Name.Trim()))
            {
                Name = "Untitled";
            }
            EditorGUI.LabelField(new Rect(DrawRect.x, DrawRect.y, DrawRect.width - 90, EditorGUIUtility.singleLineHeight), Name, (TrackInstance.Editions[Index].Soundtrack == null && TrackInstance.CollapseEditions ? InvalidBoldStyle : EditorStyles.boldLabel));

            //Draws main edition if it is the first edition
            if (Index == 0)
            {
                EditorGUI.LabelField(new Rect(DrawRect.x + DrawRect.width - 90, DrawRect.y, 70, EditorGUIUtility.singleLineHeight), "Main Edition", EditorStyles.miniLabel);
            }

            //Draws sountrack length
            if (TrackInstance.Editions[Index].Soundtrack != null)
            {
                EditorGUI.LabelField(new Rect((DrawRect.x + DrawRect.width) / 2 - 40, DrawRect.y, 80, EditorGUIUtility.singleLineHeight), StringFormatting.FormatTime(TrackInstance.Editions[Index].Soundtrack.length), CenteredMiniLabel);
            }

            //Displays basic properties if uncollapsed
            if (!TrackInstance.CollapseEditions)
            {
                DrawProperty(NameProperty, "Edition Name", "(Optional) The name of the Edition.");
                DrawPropertyStyled(SoundtrackProperty, "Soundtrack", "The AudioClip containing the soundtrack for this Edition.", (TrackInstance.Editions[Index].Soundtrack == null ? InvalidStyle : EditorStyles.label));

                //Shows full properties if the sountrack is not null
                if (TrackInstance.Editions[Index].Soundtrack != null)
                {
                    DrawVolumeSlider(SoundtrackVolumeProperty, "Soundtrack Volume", "The volume of the soundtrack in this Edition.");
                    DrawProperty(TransitionSoundProperty, "Transition Sound", "(Optional) The AudioClip for the transition sound to be played when switching to this Edition of the Track.");

                    //Displays transiton sound properties
                    if (TrackInstance.Editions[Index].TransitionSound != null)
                    {
                        EditorGUI.LabelField(new Rect(DrawRect.x + 96, PropertyIndex * Spacing + DrawRect.y, LabelWidth - 96, EditorGUIUtility.singleLineHeight), StringFormatting.FormatTime(TrackInstance.Editions[Index].TransitionSound.length), CenteredMiniLabel);
                        DrawVolumeSlider(TransitionVolumeProperty, "Transition Volume", "The volume of the transition sound to this Edition.");
                    }

                    DrawProperty(PlaybackProperty, "Keep Playback Time", "Whether to play the soundtrack from the beginning when switching to this Edition or whether to retain the playback time from the previous Edition.");
                    DrawProperty(FadeProperty, "Fade Duration", "The duration of the cross-fade when switching to this Edition.");
                    FadeProperty.floatValue = Mathf.Max(0, FadeProperty.floatValue);
                }
                else
                {
                    //Displays error if no soundtrack is selected
                    EditorGUI.HelpBox(new Rect(DrawRect.x, (PropertyIndex + 1) * Spacing + DrawRect.y + 2f, DrawRect.width - FieldPadding, 30), "Soundtrack required. Please assign an AudioClip to this Edition.", MessageType.Error);
                }
            }
        }
        public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
        {
#if !UNITY_5_0_PLUS
            EditorGUI.LabelField(position, label.text + " [works in Unity 5+]");
        }
    public override void OnInspectorGUI()
    {
        Camera[] cams           = Camera.allCameras;
        bool     sceneHasCamera = cams.Length > 0;

        if (Camera.main)
        {
            sceneCamera = Camera.main;
        }
        else if (sceneHasCamera)
        {
            sceneCamera = cams[0];
        }

        if (sceneCamera != null)
        {
            if (sceneCameraSkybox == null)
            {
                sceneCameraSkybox = sceneCamera.GetComponent <Skybox>();
            }
        }

        if (pointPreviewTexture == null)
        {
            pointPreviewTexture = new RenderTexture(400, Mathf.RoundToInt(400 / aspect), 24);
        }

        if (animator.animationTarget == null)
        {
            EditorGUILayout.HelpBox("No animation target has been specified so there is nothing to animate. Select an animation target in the Camera Path Bezier Animator Component in the parent clip", MessageType.Warning);
        }
        else
        {
            if ((EditorGUIUtility.isProSkin) && bezier.numberOfCurves > 0 && pointPreviewTexture != null)
            {
                bool cameraPathPreview = EditorPrefs.GetBool("CameraPathPreview");
                GUILayout.Space(7);
                EditorGUILayout.BeginHorizontal();
                GUILayout.Label("Animation Preview");
                if (cameraPathPreview)
                {
                    if (GUILayout.Button("Hide", GUILayout.Width(50)))
                    {
                        EditorPrefs.SetBool("CameraPathPreview", false);
                    }
                }
                else
                {
                    if (GUILayout.Button("Show", GUILayout.Width(50)))
                    {
                        EditorPrefs.SetBool("CameraPathPreview", true);
                    }
                }
                EditorGUILayout.Space();
                EditorGUILayout.EndHorizontal();

                if (!Application.isPlaying && cameraPathPreview)
                {
                    float usePercentage = animator.normalised? animator.RecalculatePercentage(animator.editorTime): animator.editorTime;

                    //Get animation values and apply them to the preview camera
                    previewCamPos = bezier.GetPathPosition(usePercentage);
                    previewCamRot = Quaternion.identity;
                    previewCamFOV = bezier.GetPathFOV(usePercentage);

                    //Assign rotation to preview camera
                    Vector3 plusPoint, minusPoint;
                    switch (bezier.mode)
                    {
                    case CameraPathBezier.viewmodes.usercontrolled:
                        previewCamRot = bezier.GetPathRotation(usePercentage);
                        break;

                    case CameraPathBezier.viewmodes.target:

                        if (bezier.target != null)
                        {
                            previewCamRot = Quaternion.LookRotation(bezier.target.transform.position - previewCamPos);
                        }
                        else
                        {
                            EditorGUILayout.HelpBox("No target has been specified in the bezier path", MessageType.Warning);
                            previewCamRot = Quaternion.identity;
                        }
                        break;

                    case CameraPathBezier.viewmodes.followpath:

                        minusPoint    = bezier.GetPathPosition(Mathf.Clamp01(usePercentage - 0.05f));
                        plusPoint     = bezier.GetPathPosition(Mathf.Clamp01(usePercentage + 0.05f));
                        previewCamRot = Quaternion.LookRotation(plusPoint - minusPoint);
                        break;

                    case CameraPathBezier.viewmodes.reverseFollowpath:

                        minusPoint    = bezier.GetPathPosition(Mathf.Clamp01(usePercentage - 0.05f));
                        plusPoint     = bezier.GetPathPosition(Mathf.Clamp01(usePercentage + 0.05f));
                        previewCamRot = Quaternion.LookRotation(minusPoint - plusPoint);
                        break;

                    case CameraPathBezier.viewmodes.mouselook:

                        Vector3 minusPointb = bezier.GetPathPosition(Mathf.Clamp01(usePercentage - 0.05f));
                        Vector3 plusPointb  = bezier.GetPathPosition(Mathf.Clamp01(usePercentage + 0.05f));
                        previewCamRot = Quaternion.LookRotation(plusPointb - minusPointb);
                        break;
                    }

                    //Render the camera preview
                    GameObject cam = new GameObject("Point Preview");
                    cam.transform.parent = bezier.transform;
                    cam.AddComponent <Camera>();
                    //Retreive camera settings from the main camera
                    if (sceneCamera != null)
                    {
                        cam.GetComponent <Camera>().backgroundColor = sceneCamera.backgroundColor;
                        if (sceneCameraSkybox != null)
                        {
                            cam.AddComponent <Skybox>().material = sceneCameraSkybox.material;
                        }
                        else
                        if (RenderSettings.skybox != null)
                        {
                            cam.AddComponent <Skybox>().material = RenderSettings.skybox;
                        }
                    }
                    cam.transform.position = previewCamPos;
                    cam.transform.rotation = previewCamRot;
                    cam.GetComponent <Camera>().fieldOfView   = previewCamFOV;
                    cam.GetComponent <Camera>().targetTexture = pointPreviewTexture;
                    cam.GetComponent <Camera>().Render();
                    cam.GetComponent <Camera>().targetTexture = null;
                    DestroyImmediate(cam);

                    //Display the camera preview

                    Rect previewRect = new Rect(0, 0, Screen.width, Screen.width / aspect);
                    Rect layoutRect  = EditorGUILayout.BeginVertical();
                    previewRect.x = layoutRect.x;
                    previewRect.y = layoutRect.y + 5;
                    EditorGUI.DrawPreviewTexture(previewRect, pointPreviewTexture);
                    GUILayout.Space(previewRect.height + 10);
                    pointPreviewTexture.Release();

                    EditorGUILayout.BeginHorizontal();
                    float time = EditorGUILayout.Slider(animator.editorTime * animator.pathTime, 0, animator.pathTime);
                    animator.editorTime = time / animator.pathTime;
                    EditorGUILayout.LabelField("sec", GUILayout.Width(25));
                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.EndVertical();
                }
            }
        }

        animator.showScenePreview = EditorGUILayout.Toggle("Show Scene Preview Info", animator.showScenePreview);

        animator.playOnStart = EditorGUILayout.Toggle("Play on start", animator.playOnStart);

        EditorGUILayout.BeginHorizontal();
        animator.pathTime = EditorGUILayout.FloatField("Animation Time", animator.pathTime);
        EditorGUILayout.LabelField("sec", GUILayout.Width(25));
        EditorGUILayout.EndHorizontal();

        bool noPath = bezier.numberOfControlPoints < 2;

        EditorGUI.BeginDisabledGroup(noPath);
        EditorGUILayout.BeginHorizontal();
        float newPathSpeed = EditorGUILayout.FloatField("Animation Speed", animator.pathSpeed);

        if (!noPath)
        {
            animator.pathSpeed = newPathSpeed;
        }
        EditorGUILayout.LabelField("m/sec", GUILayout.Width(25));
        EditorGUILayout.EndHorizontal();
        EditorGUI.EndDisabledGroup();

        animator.pathTime = Mathf.Max(animator.pathTime, 0.001f);       //ensure it's a real number

        animator.animationTarget = (Transform)EditorGUILayout.ObjectField("Animate Object", animator.animationTarget, typeof(Transform), true);
        EditorGUILayout.HelpBox("This toggle can be used to specify what kind of object you are animating. If it isn't a camera, we recommend you uncheck this box", MessageType.Info);
        animator.isCamera = EditorGUILayout.Toggle("Is Camera", animator.isCamera);

        animator.mode = (CameraPathBezierAnimator.modes)EditorGUILayout.EnumPopup("Animation Mode", animator.mode);

        animator.normalised = EditorGUILayout.Toggle("Normalised Path", animator.normalised);

        EditorGUILayout.HelpBox("Set this if you want to start another camera path animation once this has completed", MessageType.Info);
        animator.nextAnimation = (CameraPathBezierAnimator)EditorGUILayout.ObjectField("Next Camera Path", animator.nextAnimation, typeof(CameraPathBezierAnimator), true);

        if (bezier.mode == CameraPathBezier.viewmodes.mouselook)
        {
            EditorGUILayout.HelpBox("Alter the mouse sensitivity here", MessageType.Info);
            animator.sensitivity = EditorGUILayout.Slider("Mouse Sensitivity", animator.sensitivity, 0.1f, 2.0f);
            EditorGUILayout.HelpBox("Restrict the vertical viewable area here.", MessageType.Info);
            EditorGUILayout.LabelField("Mouse Y Restriction");
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField(((int)animator.minX).ToString(), GUILayout.Width(30));
            EditorGUILayout.MinMaxSlider(ref animator.minX, ref animator.maxX, -180, 180);
            EditorGUILayout.LabelField(((int)animator.maxX).ToString(), GUILayout.Width(30));
            EditorGUILayout.EndHorizontal();
        }

        if (GUI.changed)
        {
            bezier.RecalculateStoredValues();
            EditorUtility.SetDirty(animator);
            EditorUtility.SetDirty(bezier);
        }
    }
Exemplo n.º 23
0
    void DisplayMatches()
    {
        Rect rect = fieldRect;


        if (lastMatchKey != script.StringID)
        {
            matchedKeys = new List <string>();
            matchedIDs  = new List <int>();
            for (int i = 0; i < StringIds.Length; i++)
            {
                if (StringIds[i].ToLower().Contains(script.StringID))
                {
                    matchedKeys.Add(StringIds[i]);
                    matchedIDs.Add(i);
                }
            }
            lastMatchKey = script.StringID;
        }

        rect.y += EditorGUIUtility.singleLineHeight + 2;
        if (matchedKeys.Count > 0 && !string.IsNullOrEmpty(script.StringID))
        {
            rect.height = 125;
            EditorGUI.DrawRect(rect, new Color(0, 0, 0, 0.7f));
            lisScroll = GUI.BeginScrollView(rect, lisScroll, new Rect(0, 0, rect.width - 80, EditorGUIUtility.singleLineHeight * matchedKeys.Count), false, true);

            rect.height = EditorGUIUtility.singleLineHeight;
            for (int i = 0; i < matchedKeys.Count; i++)
            {
                Rect r = rect;
                r.x     = 0; r.y = EditorGUIUtility.singleLineHeight * i;
                r.width = 140;
                GUI.Label(r, matchedKeys[i]);
                r.x    += 142;
                r.width = 75;
                if (GUI.Button(r, new GUIContent("Set String", StringTexts[matchedIDs[i]]), EditorStyles.toolbarButton))
                {
                    EditorGUI.FocusTextInControl("");
                    GUI.FocusControl("");
                    script.StringID = matchedKeys[i];
                    showMatches     = false;
                    EditorUtility.SetDirty(target);
                }
                r.x += 76;

                if (GUI.Button(r, new GUIContent("Set ID", StringTexts[matchedIDs[i]]), EditorStyles.toolbarButton))
                {
                    EditorGUI.FocusTextInControl("");
                    GUI.FocusControl("");
                    script._arrayID         = matchedIDs[i];
                    script.StringID         = matchedKeys[i];
                    script.ManuallyAssignId = false;
                    showMatches             = false;
                    EditorUtility.SetDirty(target);
                }
                rect.y += EditorGUIUtility.singleLineHeight;
            }
            GUI.EndScrollView();
        }
        else
        {
            GUI.Box(rect, "No matches");
        }
    }
        protected void AdvancedOptions(MaterialEditor materialEditor, Material material)
        {
            EditorGUILayout.Space();
            GUILayout.Label(Styles.advancedOptionsTitle, EditorStyles.boldLabel);

            EditorGUI.BeginChangeCheck();

            materialEditor.ShaderProperty(renderQueueOverride, BaseStyles.renderQueueOverride);

            if (EditorGUI.EndChangeCheck())
            {
                MaterialChanged(material);
            }

            // Show the RenderQueueField but do not allow users to directly manipulate it. That is done via the renderQueueOverride.
            GUI.enabled = false;
            materialEditor.RenderQueueField();

            // Enable instancing to disable batching. Static and dynamic batching will normalize the object scale, which breaks 
            // features which utilize object scale.
            GUI.enabled = !ScaleRequired();

            if (!GUI.enabled && !material.enableInstancing)
            {
                material.enableInstancing = true;
            }

            materialEditor.EnableInstancingField();

            if (material.enableInstancing)
            {
                GUI.enabled = true;
                materialEditor.ShaderProperty(instancedColor, Styles.instancedColor, 2);
            }
            else
            {
                // When instancing is disable, disable instanced color.
                SetShaderFeatureActive(material, Styles.instancedColorFeatureName, Styles.instancedColorName, 0.0f);
            }

            materialEditor.ShaderProperty(stencil, Styles.stencil);

            if (PropertyEnabled(stencil))
            {
                materialEditor.ShaderProperty(stencilReference, Styles.stencilReference, 2);
                materialEditor.ShaderProperty(stencilComparison, Styles.stencilComparison, 2);
                materialEditor.ShaderProperty(stencilOperation, Styles.stencilOperation, 2);
            }
            else
            {
                // When stencil is disable, revert to the default stencil operations. Note, when tested on D3D11 hardware the stencil state 
                // is still set even when the CompareFunction.Disabled is selected, but this does not seem to affect performance.
                material.SetInt(Styles.stencilComparisonName, (int)CompareFunction.Disabled);
                material.SetInt(Styles.stencilOperationName, (int)StencilOp.Keep);
            }

            if (ScaleRequired())
            {
                materialEditor.ShaderProperty(ignoreZScale, Styles.ignoreZScale);
            }
        }
	void OnGUI() {
		GUILayout.Label ("Android Manifest Manager", EditorStyles.boldLabel);

		if (!AN_ManifestManager.HasManifest ) {
			GUILayout.BeginHorizontal();
			EditorGUILayout.Space();
			GUILayout.Label("You have NO AndroidManifest file in your project!", GUILayout.Width(300.0f));
			EditorGUILayout.Space();
			GUILayout.EndHorizontal();

			EditorGUILayout.Space();
			GUILayout.BeginHorizontal();
			EditorGUILayout.Space();
			if (GUILayout.Button("Create Default Manifest", new GUILayoutOption[]{GUILayout.Width(200.0f), GUILayout.Height(50.0f)})) {
				AN_ManifestManager.CreateDefaultManifest();
			}
			EditorGUILayout.Space();
			GUILayout.EndHorizontal();
		} else {


			string[] toolbarButtons = new string[]{"Manifest", "Application", "Permissions"};
			toolbarButtonIndex = GUILayout.Toolbar(toolbarButtonIndex, toolbarButtons, new GUILayoutOption[]{GUILayout.Height(30.0f)});

			switch (toolbarButtons[toolbarButtonIndex]) {
			case "Manifest" : {
				AN_ManifestTemplate manifest = AN_ManifestManager.GetManifest();

				if (manifest != null) {
					GUILayout.Label ("Values", EditorStyles.boldLabel);
					foreach (string key in manifest.Values.Keys) {
						EditorGUILayout.BeginHorizontal();
						
						GUILayout.Label(key);
						if (key.Equals("xmlns:android") ||
						    key.Equals("android:installLocation") ||
						    key.Equals("package") ||
						    key.Equals("android:versionName") ||
						    key.Equals("android:versionCode") ||
						    key.Equals("android:theme")) {
							
							GUI.enabled = false;
							GUILayout.TextField(AN_ManifestManager.GetManifest().Values[key], GUILayout.Width(300.0f));
						} else {
							GUI.enabled = true;
							
							string input = AN_ManifestManager.GetManifest().Values[key];
							EditorGUI.BeginChangeCheck();
							input = GUILayout.TextField(AN_ManifestManager.GetManifest().Values[key], GUILayout.Width(276.0f));
							if(EditorGUI.EndChangeCheck()) {
								AN_ManifestManager.GetManifest().SetValue(key, input);
								return;
							}
							
							if(GUILayout.Button("X", GUILayout.Width(20.0f))) {
								AN_ManifestManager.GetManifest().RemoveValue(key);
								return;
							}
						}
						GUI.enabled = true;
						EditorGUILayout.EndHorizontal();
					}
					
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.Space();
					if (GUILayout.Button("Add Value", GUILayout.Width(100.0f))) {
						AddValueDialog(AN_ManifestManager.GetManifest());
					}
					EditorGUILayout.Space();
					EditorGUILayout.EndHorizontal();
					
					GUILayout.Label ("Properties", EditorStyles.boldLabel);
					DrawProperties(AN_ManifestManager.GetManifest());
					
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.Space();
					if (GUILayout.Button("Add Property", GUILayout.Width(100.0f))) {
						AddPropertyDialog(AN_ManifestManager.GetManifest());
					}
					EditorGUILayout.Space();
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.Space();
					
					EditorGUILayout.Space();
					if(GUILayout.Button("Save Manifest", GUILayout.Height(22.0f))) {
						AN_ManifestManager.SaveManifest();
					}
				} else {
					EditorGUILayout.HelpBox("Selected build platform DOESN'T support AndroidManifest.xml file", MessageType.Info);
				}
			} break;
			case "Application" : {
				AN_ManifestTemplate manifest = AN_ManifestManager.GetManifest();
				
				if (manifest != null) {
					scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Width (position.width), GUILayout.Height (position.height - 50f));
					
					GUILayout.Label ("Values", EditorStyles.boldLabel);
					foreach (string key in manifest.ApplicationTemplate.Values.Keys) {
						EditorGUILayout.BeginHorizontal();
						
						GUILayout.Label(key);
						
						string input = AN_ManifestManager.GetManifest().ApplicationTemplate.Values[key];
						EditorGUI.BeginChangeCheck();
						input = GUILayout.TextField(AN_ManifestManager.GetManifest().ApplicationTemplate.Values[key], GUILayout.Width(200.0f));
						if(EditorGUI.EndChangeCheck()) {
							AN_ManifestManager.GetManifest().ApplicationTemplate.SetValue(key, input);
							return;
						}
						
						if(GUILayout.Button("X", GUILayout.Width(20.0f))) {
							AN_ManifestManager.GetManifest().ApplicationTemplate.RemoveValue(key);
							return;
						}
						
						EditorGUILayout.EndHorizontal();
					}
					
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.Space();
					if (GUILayout.Button("Add Value", GUILayout.Width(100.0f))) {
						AddValueDialog(AN_ManifestManager.GetManifest().ApplicationTemplate);
					}
					EditorGUILayout.Space();
					EditorGUILayout.EndHorizontal();
					
					GUILayout.Label ("Activities", EditorStyles.boldLabel);
					
					int launcherActivities = 0;
					foreach (int id in AN_ManifestManager.GetManifest().ApplicationTemplate.Activities.Keys) {
						AN_ActivityTemplate activity = AN_ManifestManager.GetManifest().ApplicationTemplate.Activities[id];
						
						if (activity.IsLauncher) {
							launcherActivities++;
						}
						
						EditorGUILayout.BeginVertical(GUI.skin.box);
						EditorGUILayout.BeginHorizontal();
						activity.IsOpen = EditorGUILayout.Foldout(activity.IsOpen, activity.Name);
						if(GUILayout.Button("X", GUILayout.Width(20.0f))) {
							AN_ManifestManager.GetManifest().ApplicationTemplate.RemoveActivity(activity);
							return;
						}
						EditorGUILayout.EndHorizontal();
						
						if (activity.IsOpen) {
							EditorGUILayout.BeginVertical();
							
							bool isLauncher = activity.IsLauncher;
							EditorGUI.BeginChangeCheck();
							isLauncher = EditorGUILayout.Toggle("Is Launcher", activity.IsLauncher);
							if (EditorGUI.EndChangeCheck()) {
								activity.SetAsLauncher(isLauncher);
							}
							
							foreach (string k in activity.Values.Keys) {
								EditorGUILayout.BeginHorizontal();
								
								GUILayout.Label(k);
								EditorGUILayout.Space();
								
								string input = activity.Values[k];
								EditorGUI.BeginChangeCheck();
								
								if (k.Equals("android:name")) {
									input = GUILayout.TextField(activity.Values[k], GUILayout.Width(224.0f));
								} else {
									input = GUILayout.TextField(activity.Values[k], GUILayout.Width(200.0f));
								}
								
								if(EditorGUI.EndChangeCheck()) {
									activity.SetValue(k, input);
									return;
								}
								
								if (!k.Equals("android:name")) {
									if(GUILayout.Button("X", GUILayout.Width(20.0f))) {
										activity.RemoveValue(k);
										return;
									}
								}
								
								EditorGUILayout.EndHorizontal();
								EditorGUILayout.Space();
							}
							
							DrawProperties(activity);
							
							EditorGUILayout.BeginHorizontal();
							EditorGUILayout.Space();
							if (GUILayout.Button("Add Value", GUILayout.Width(100.0f))) {
								AddValueDialog(activity);
							}
							if (GUILayout.Button("Add Property", GUILayout.Width(100.0f))) {
								AddPropertyDialog(activity);
							}
							EditorGUILayout.Space();
							EditorGUILayout.EndHorizontal();
							EditorGUILayout.Space();
							
							EditorGUILayout.EndVertical();
						}
						EditorGUILayout.EndVertical();
					}
					
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.Space();
					if (GUILayout.Button("Add Activity", GUILayout.Width(100.0f))) {
						AddPermissionDialog dlg = EditorWindow.CreateInstance<AddPermissionDialog>();
						dlg.onClose += OnPermissionDlgClose;
						dlg.onAddClick += OnAddActivityClick;
						
						#if UNITY_5
						dlg.titleContent.text = "Add Activity";
						#else
						dlg.title = "Add Activity";
						#endif
						
						dlg.ShowAuxWindow();
					}
					EditorGUILayout.Space();
					EditorGUILayout.EndHorizontal();
					
					if (launcherActivities > 1) {
						EditorGUILayout.HelpBox("There is MORE THAN ONE Launcher Activity in Manifest", MessageType.Warning);
					} else if (launcherActivities < 1){
						EditorGUILayout.HelpBox("There is NO Launcher Activities in Manifest", MessageType.Warning);
					}
					
					GUILayout.Label ("Properties", EditorStyles.boldLabel);
					DrawProperties(AN_ManifestManager.GetManifest().ApplicationTemplate);
					
					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.Space();
					if (GUILayout.Button("Add Property", GUILayout.Width(100.0f))) {
						AddPropertyDialog(AN_ManifestManager.GetManifest().ApplicationTemplate);
					}
					EditorGUILayout.Space();
					EditorGUILayout.EndHorizontal();
					
					EditorGUILayout.Space();
					EditorGUILayout.EndScrollView();
				} else {
					EditorGUILayout.HelpBox("Selected build platform DOESN'T support AndroidManifest.xml file", MessageType.Info);
				}				
			} break;
			case "Permissions" : {
				AN_ManifestTemplate manifest = AN_ManifestManager.GetManifest();
				
				if (manifest != null) {
					scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Width (position.width), GUILayout.Height (position.height - 50f));
					EditorGUILayout.BeginVertical();
					
					foreach (AN_PropertyTemplate permission in AN_ManifestManager.GetManifest().Permissions) {
						EditorGUILayout.BeginHorizontal(GUI.skin.box);
						EditorGUILayout.LabelField(permission.Values["android:name"]);
						if(GUILayout.Button("X", GUILayout.Width(20.0f))) {
							AN_ManifestManager.GetManifest().RemovePermission(permission);
							return;
						}
						EditorGUILayout.EndHorizontal();
					}
					
					EditorGUILayout.BeginHorizontal();
					if(GUILayout.Button("Add Android Permission")) {
						GenericMenu permissionsMenu = new GenericMenu();
						foreach (string pStr in PermissionsStrings) {
							permissionsMenu.AddItem(new GUIContent(pStr), false, SelectPermission, pStr);
						}
						permissionsMenu.ShowAsContext();
					}
					
					if (GUILayout.Button("Add Other Permission")) {
						AddPermissionDialog dlg = EditorWindow.CreateInstance<AddPermissionDialog>();
						dlg.onClose += OnPermissionDlgClose;
						dlg.onAddClick += OnAddPermissionClick;
						
						#if UNITY_5
						dlg.titleContent.text = "Add Permission";
						#else
						dlg.title = "Add Permission";
						#endif
						
						
						dlg.ShowAuxWindow();
					}
					EditorGUILayout.EndHorizontal();
					
					EditorGUILayout.Space();
					EditorGUILayout.EndVertical();
					EditorGUILayout.EndScrollView();
				} else {
					EditorGUILayout.HelpBox("Selected build platform DOESN'T support AndroidManifest.xml file", MessageType.Info);
				}				
			} break;
			default: break;
			}


			AboutGUI();
		}
	}
 public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
 {
     EditorGUI.EndDisabledGroup();
     EditorGUI.PropertyField(position, property, label, true);
     GUI.enabled = true;
 }
	private void DrawProperties(AN_BaseTemplate parent) {
		foreach (string key in parent.Properties.Keys) {
			foreach (AN_PropertyTemplate property in parent.Properties[key]) {

				if(parent is AN_ActivityTemplate) {
					AN_ActivityTemplate activity = parent as AN_ActivityTemplate;
					if (activity.IsLauncherProperty(property)) {
						continue;
					}
				}

				EditorGUILayout.Space ();
				EditorGUILayout.BeginVertical(GUI.skin.box, GUILayout.Height(27.0f));
				EditorGUILayout.BeginHorizontal ();

				if (property.Values.ContainsKey("android:name")) {
					property.IsOpen = EditorGUILayout.Foldout(property.IsOpen, "[" + property.Tag + "] " + property.Values["android:name"]);
				} else {
					if (key.Equals("intent-filter")) {
						property.IsOpen = EditorGUILayout.Foldout(property.IsOpen, "[" + property.Tag + "] " + property.GetIntentFilterName(property));
					} else {
						property.IsOpen = EditorGUILayout.Foldout(property.IsOpen, "[" + property.Tag + "]");
					}
				}

				if (GUILayout.Button ("X", GUILayout.Width(20.0f))) {
					parent.RemoveProperty(property);
					return;
				}
				EditorGUILayout.EndHorizontal ();
				
				if (property.IsOpen) {
					EditorGUILayout.BeginVertical();
					
					foreach (string k in property.Values.Keys) {
						EditorGUILayout.Space();
						EditorGUILayout.BeginHorizontal();
						
						GUILayout.Label(k);
						EditorGUILayout.Space();

						string input = property.Values[k];
						EditorGUI.BeginChangeCheck();
						if (k.Equals("android:name")) {
							input = GUILayout.TextField(property.Values[k], GUILayout.Width(224.0f));
						} else {
							input = GUILayout.TextField(property.Values[k], GUILayout.Width(200.0f));
						}
						if(EditorGUI.EndChangeCheck()) {
							property.SetValue(k, input);
							return;
						}

						if (GUILayout.Button ("X", GUILayout.Width(20.0f))) {
							property.RemoveValue(k);
							return;
						}
						
						EditorGUILayout.EndHorizontal();
					}
					
					DrawProperties(property);
					EditorGUILayout.Space();
					EditorGUILayout.EndVertical();

					EditorGUILayout.BeginHorizontal();
					EditorGUILayout.Space();
					if (GUILayout.Button("Add Value", GUILayout.Width(100.0f))) {
						AddValueDialog(property);
					}
					if (GUILayout.Button("Add Property", GUILayout.Width(100.0f))) {
						AddPropertyDialog(property);
					}
					EditorGUILayout.Space();
					EditorGUILayout.EndHorizontal();
					EditorGUILayout.Space();
				}
				EditorGUILayout.EndVertical();
			}
		}
	}
        private void OnGUI()
        {
            GUI.skin.label.richText = true;
            GUILayout.BeginHorizontal();
            {
                GUILayout.FlexibleSpace();
            }
            GUILayout.EndHorizontal();

            GameObject prefab = EditorGUILayout.ObjectField("Asset to Generate", generatedPrefab, typeof(GameObject), true) as GameObject;
            if (prefab != generatedPrefab)
            {
                generateAnims.Clear();
                customClips.Clear();
                generatedPrefab = prefab;

                SkinnedMeshRenderer[] meshRender = generatedPrefab.GetComponentsInChildren<SkinnedMeshRenderer>();
                List<Matrix4x4> bindPose = new List<Matrix4x4>(150);
                boneTransform = RuntimeHelper.MergeBone(meshRender, bindPose);
            }

            bool error = false;
            if (generatedPrefab)
            {
                exposeAttachments = EditorGUILayout.Toggle("Enable Attachments", exposeAttachments);
                if (exposeAttachments)
                {
                    showAttachmentSetting = EditorGUILayout.Foldout(showAttachmentSetting, "Attachment setting");
                    if (showAttachmentSetting)
                    {
                        EditorGUI.BeginChangeCheck();
                        GameObject fbx = EditorGUILayout.ObjectField("FBX refrenced by Prefab:", generatedFbx, typeof(GameObject), false) as GameObject;
                        if (EditorGUI.EndChangeCheck())
                        {
                            if (fbx != generatedFbx)
                            {
                                SkinnedMeshRenderer[] meshRender = generatedPrefab.GetComponentsInChildren<SkinnedMeshRenderer>();
                                List<Matrix4x4> bindPose = new List<Matrix4x4>(150);
                                boneTransform = RuntimeHelper.MergeBone(meshRender, bindPose);

                                generatedFbx = fbx;
                                var allTrans = generatedPrefab.GetComponentsInChildren<Transform>().ToList();
                                allTrans.RemoveAll(q => boneTransform.Contains(q));

                                //var allTrans = boneTransform;
                                selectExtraBone.Clear();
                                for (int i = 0; i != allTrans.Count; ++i)
                                {
                                    selectExtraBone.Add(allTrans[i].name, false);
                                }
                            }
                            else if (fbx == null)
                            {
                                selectExtraBone.Clear();
                            }
                        }
                        if (selectExtraBone.Count > 0)
                        {
                            var temp = new Dictionary<string, bool>();
                            foreach (var obj in selectExtraBone)
                            {
                                temp[obj.Key] = obj.Value;
                            }
                            scrollPosition2 = GUILayout.BeginScrollView(scrollPosition2);
                            foreach (var obj in temp)
                            {
                                bool value = EditorGUILayout.Toggle(string.Format("   {0}", obj.Key), obj.Value);
                                selectExtraBone[obj.Key] = value;
                            }
                            GUILayout.EndScrollView();
                        }
                    }
                }
                else
                    generatedFbx = null;

                aniFps = EditorGUILayout.IntSlider("FPS", aniFps, 1, 120);

                Animator animator = generatedPrefab.GetComponentInChildren<Animator>();
                if (animator == null)
                {
                    EditorGUILayout.LabelField("Error: The prefab should have a Animator Component.");
                    return;
                }
                if (animator.runtimeAnimatorController == null)
                {
                    EditorGUILayout.LabelField("Error: The prefab's Animator should have a Animator Controller.");
                    return;
                }
                var clips = GetClips(animator);
                string[] clipNames = generateAnims.Keys.ToArray();
                int totalFrames = 0;
                List<int> frames = new List<int>();
                foreach (var clipName in clipNames)
                {
                    if (!generateAnims[clipName])
                        continue;

					AnimationClip clip = clips.Find(delegate(AnimationClip c) {
						if (c != null)
							return c.name == clipName;
						return false;
					});
                    int framesToBake = clip ? (int)(clip.length * aniFps / 1.0f) : 1;
					framesToBake = Mathf.Clamp(framesToBake, 1, framesToBake);
                    totalFrames += framesToBake;
                    frames.Add(framesToBake);
                }

                int textureCount = 1;
                int textureWidth = CalculateTextureSize(out textureCount, frames.ToArray(), boneTransform);
                error = textureCount == 0;
                if (textureCount == 0)
                    EditorGUILayout.LabelField("Error: There is certain animation's frames which is larger than a whole texture.");
                else if (textureCount == 1)
                    EditorGUILayout.LabelField(string.Format("Animation Texture will be one {0} X {1} texture", textureWidth, textureWidth));
                else
                    EditorGUILayout.LabelField(string.Format("Animation Texture will be {2} 1024 X 1024 and one {0} X {1} textures", textureWidth, textureWidth, textureCount - 1));

                scrollPosition = GUILayout.BeginScrollView(scrollPosition);
                foreach (var clipName in clipNames)
                {
					AnimationClip clip = clips.Find(delegate(AnimationClip c) {
						if (c != null)
							return c.name == clipName;
						return false;
					});
                    int framesToBake = clip ? (int)(clip.length * aniFps / 1.0f) : 1;
					framesToBake = Mathf.Clamp(framesToBake, 1, framesToBake);
                    GUILayout.BeginHorizontal();
                    {
                        generateAnims[clipName] = EditorGUILayout.Toggle(string.Format("({0}) {1} ", framesToBake, clipName), generateAnims[clipName]);
                        GUI.enabled = generateAnims[clipName];
                        //frameSkips[clipName] = Mathf.Clamp(EditorGUILayout.IntField(frameSkips[clipName]), 1, fps);
                        GUI.enabled = true;
                    }
                    GUILayout.EndHorizontal();
                    if (framesToBake > 5000)
                    {
                        GUI.skin.label.richText = true;
                        EditorGUILayout.LabelField("<color=red>Long animations degrade performance, consider using a higher frame skip value.</color>", GUI.skin.label);
                    }
                }
                GUILayout.EndScrollView();
            }

            if (generatedPrefab && !error)
            {
                if (GUILayout.Button(string.Format("Generate")))
                {
                    //BakeAnimation();
                    BakeWithAnimator();
                }
            }
        }
Exemplo n.º 29
0
        private void DrawImportSettings()
        {
            using (var check = new EditorGUI.ChangeCheckScope())
            {
                showImportSettings = EditorGUILayout.Foldout(showImportSettings, labelShowImport, styleBoldFoldout);
                if (check.changed)
                {
                    Rect window = position;
                    int  expand = 165;
                    window.yMax += showImportSettings ? expand : -expand;
                    position     = window;
                }
            }

            if (showImportSettings == false)
            {
                return;
            }

            EditorGUI.indentLevel++;
            EditorGUI.BeginDisabledGroup(importFile == null);

            EditorGUILayout.Space();

            EditorGUI.BeginChangeCheck();

            DrawPathPicker();

            importSettings.fileNaming = (NamingConvention)EditorGUILayout.EnumPopup(labelFileNaming, importSettings.fileNaming);

            if (importSettings.fileNaming != NamingConvention.LayerNameOnly)
            {
                EditorGUI.indentLevel++;
                importSettings.groupMode = (GroupMode)EditorGUILayout.EnumPopup(labelGrpMode, importSettings.groupMode);
                EditorGUI.indentLevel--;
            }

            EditorGUILayout.Space();

            importSettings.PackingTag = EditorGUILayout.TextField(labelPackTag, importSettings.PackingTag);
            importPPU = EditorGUILayout.FloatField(labelPixelUnit, importPPU);

            SpriteAlignUI.DrawGUILayout(labelAlignment, importSettings.DefaultAlignment, newAlign =>
            {
                importSettings.DefaultAlignment = newAlign;
                settingsChanged = true;
                ApplyDefaultSettings();
            });

            if (importSettings.DefaultAlignment == SpriteAlignment.Custom)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    GUILayout.Space(EditorGUIUtility.labelWidth);
                    importSettings.DefaultPivot = EditorGUILayout.Vector2Field(GUIContent.none, importSettings.DefaultPivot);
                }
            }

            importSettings.ScaleFactor = (ScaleFactor)EditorGUILayout.EnumPopup(labelScale, importSettings.ScaleFactor);
            //importSettings.AutoImport = EditorGUILayout.Toggle(labelAutoImport, importSettings.AutoImport);

            if (EditorGUI.EndChangeCheck())
            {
                settingsChanged = true;
                var pivot = importSettings.DefaultPivot;
                pivot.x = Mathf.Clamp01(importSettings.DefaultPivot.x);
                pivot.y = Mathf.Clamp01(importSettings.DefaultPivot.y);
                importSettings.DefaultPivot = pivot;
                ApplyDefaultSettings();
            }

            using (new EditorGUI.DisabledGroupScope(settingsChanged == false))
            {
                if (GUILayout.Button("Apply"))
                {
                    WriteImportSettings();
                }
            }

            EditorGUI.EndDisabledGroup();
            EditorGUI.indentLevel--;
        }
Exemplo n.º 30
0
        public override void OnStart(PartModule.StartState state)
        {
            if ((!HighLogic.LoadedSceneIsEditor && !HighLogic.LoadedSceneIsFlight) || !CompatibilityChecker.IsAllCompatible()) { return; }
            //Identification of the RealChuteModule
            if (this.part.Modules.Contains("RealChuteModule")) { this.rcModule = this.part.Modules["RealChuteModule"] as RealChuteModule; }
            else { return; }
            this.secondaryChute = this.rcModule.secondaryChute;
            if (!string.IsNullOrEmpty(this.textureLibrary)) { this.textureLib.TryGetConfig(this.textureLibrary, ref this.textures); }
            this.bodies = AtmoPlanets.fetch;
            this.body = this.bodies.GetBody(this.planets);

            //Initializes ChuteTemplates
            if (this.chutes.Count <= 0)
            {
                if (this.node == null && !PersistentManager.instance.TryGetNode<ProceduralChute>(this.part.name, ref this.node)) { return; }
                LoadChutes();
            }
            this.chutes.ForEach(c => c.Initialize());
            if (this.sizes.Count <= 0) { this.sizes = this.sizeLib.GetSizes(this.part.partInfo.name); }

            //Creates an instance of the texture library
            this.editorGUI = new EditorGUI(this);
            if (HighLogic.LoadedSceneIsEditor)
            {
                //Windows initiation
                this.editorGUI.window = new Rect(5, 370, 420, Screen.height - 375);
                this.chutes.ForEach(c =>
                {
                    c.templateGUI.materialsWindow = new Rect(this.editorGUI.matX, this.editorGUI.matY, 375, 275);
                    c.templateGUI.drag = new Rect(0, 0, 375, 25);
                });
                this.editorGUI.failedWindow = new Rect(Screen.width / 2 - 150, Screen.height / 2 - 150, 300, 300);
                this.editorGUI.successfulWindow = new Rect(Screen.width / 2 - 150, Screen.height / 2 - 25, 300, 50);
                this.editorGUI.presetsWindow = new Rect(Screen.width / 2 - 200, Screen.height / 2 - 250, 400, 500);
                this.editorGUI.presetsSaveWindow = new Rect(Screen.width / 2 - 175, Screen.height / 2 - 110, 350, 220);
                this.editorGUI.presetsWarningWindow = new Rect(Screen.width / 2 - 100, Screen.height / 2 - 50, 200, 100);

                if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
                {
                    float level = 0;
                    switch (EditorDriver.editorFacility)
                    {
                        case EditorFacility.VAB:
                            level = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.VehicleAssemblyBuilding); break;

                        case EditorFacility.SPH:
                            level = ScenarioUpgradeableFacilities.GetFacilityLevel(SpaceCenterFacility.SpaceplaneHangar); break;

                        default:
                            break;
                    }
                    if (GameVariables.Instance.UnlockedActionGroupsStock(level))
                    {
                        Events.ForEach(e => e.guiActiveEditor = false);
                    }
                }
                else
                {
                    Events.ForEach(e => e.guiActiveEditor = false);
                }

                //Gets the original part state
                if (this.textures != null && this.caseID == -1)
                {
                    if (this.caseID == -1)
                    {
                        if (this.textures.TryGetCase(this.currentCase, ref this.parachuteCase)) { this.caseID = this.textures.GetCaseIndex(this.parachuteCase.name); }
                    }
                    else
                    {
                        this.textures.TryGetCase(this.caseID, this.type, ref this.parachuteCase);
                    }
                    this.lastCaseID = this.caseID;
                }

                if (!this.initiated)
                {
                    if (!this.bodies.TryGetBodyIndex("Kerbin", ref this.planets)) { this.planets = 0; }
                    this.body = this.bodies.GetBody(planets);

                    //Identification of the values from the RealChuteModule
                    this.mustGoDown = this.rcModule.mustGoDown;
                    this.deployOnGround = this.rcModule.deployOnGround;
                    this.timer = this.rcModule.timer + "s";
                    this.cutSpeed = this.rcModule.cutSpeed.ToString();
                    if (this.rcModule.spareChutes != -1) { this.spares = this.rcModule.spareChutes.ToString(); }
                    this.originalSize = this.part.transform.GetChild(0).localScale;
                    this.initiated = true;
                }
            }
            else  if (this.textures != null)
            {
                this.textures.TryGetCase(this.caseID, this.type, ref this.parachuteCase);
                this.lastCaseID = this.caseID;
            }

            if (this.parent == null) { this.parent = this.part.FindModelTransform(this.rcModule.parachutes[0].parachuteName).parent; }

            //Updates the part
            if (this.textures != null)
            {
                UpdateCaseTexture(this.part, this.rcModule);
                this.editorGUI.cases = this.textures.caseNames;
                this.editorGUI.canopies = this.textures.canopyNames;
                this.editorGUI.models = this.textures.modelNames;
            }
            UpdateScale(this.part, this.rcModule);
        }
Exemplo n.º 31
0
    public void DrawAnchorTransform()
    {
        if (NGUIEditorTools.DrawHeader("Anchors"))
        {
            NGUIEditorTools.BeginContents();
            NGUIEditorTools.SetLabelWidth(NGUISettings.minimalisticLook ? 69f : 62f);

            EditorGUI.BeginDisabledGroup(!((target as UIRect).canBeAnchored));
            GUILayout.BeginHorizontal();
            AnchorType type = (AnchorType)EditorGUILayout.EnumPopup("Type", mAnchorType);
            NGUIEditorTools.DrawPadding();
            GUILayout.EndHorizontal();

            SerializedProperty[] tg = new SerializedProperty[4];
            for (int i = 0; i < 4; ++i)
            {
                tg[i] = serializedObject.FindProperty(FieldName[i] + ".target");
            }

            if (mAnchorType == AnchorType.None && type != AnchorType.None)
            {
                if (type == AnchorType.Unified)
                {
                    if (mTarget[0] == null && mTarget[1] == null && mTarget[2] == null && mTarget[3] == null)
                    {
                        UIRect rect   = target as UIRect;
                        UIRect parent = NGUITools.FindInParents <UIRect>(rect.cachedTransform.parent);

                        if (parent != null)
                        {
                            for (int i = 0; i < 4; ++i)
                            {
                                mTarget[i] = parent.cachedTransform;
                            }
                        }
                    }
                }

                for (int i = 0; i < 4; ++i)
                {
                    tg[i].objectReferenceValue = mTarget[i];
                    mTarget[i] = null;
                }
                UpdateAnchors(true);
            }

            if (type != AnchorType.None)
            {
                NGUIEditorTools.DrawPaddedProperty("Execute", serializedObject, "updateAnchors");
            }

            if (type == AnchorType.Advanced)
            {
                DrawAnchor(0, true);
                DrawAnchor(1, true);
                DrawAnchor(2, true);
                DrawAnchor(3, true);
            }
            else if (type == AnchorType.Unified)
            {
                DrawSingleAnchorSelection();

                DrawAnchor(0, false);
                DrawAnchor(1, false);
                DrawAnchor(2, false);
                DrawAnchor(3, false);
            }
            else if (type == AnchorType.None && mAnchorType != type)
            {
                // Save values to make it easy to "go back"
                for (int i = 0; i < 4; ++i)
                {
                    mTarget[i] = tg[i].objectReferenceValue as Transform;
                    tg[i].objectReferenceValue = null;
                }

                serializedObject.FindProperty("leftAnchor.relative").floatValue   = 0f;
                serializedObject.FindProperty("bottomAnchor.relative").floatValue = 0f;
                serializedObject.FindProperty("rightAnchor.relative").floatValue  = 1f;
                serializedObject.FindProperty("topAnchor.relative").floatValue    = 1f;
            }

            mAnchorType = type;
            OnDrawFinalProperties();
            EditorGUI.EndDisabledGroup();
            NGUIEditorTools.EndContents();
        }
    }