public override void OnInspectorGUI()
        {
            if (_scriptCreater == null)
            {
                _scriptCreater = this.target as ScriptCreater;
            }
            _scriptCreater = this.target as ScriptCreater;

            this.Space(10)
            .ETextField("Script Name", ref _scriptCreater.ScriptName)
            .Pan(() => {
                if (!_scriptCreater.ScriptName.IsLegalFieldName())
                {
                    _scriptCreater.ScriptName = _scriptCreater.name.Replace(" ", "").Replace("(", "").Replace(")", "");
                }
            })
            .Label("Description")
            .TextArea(ref _scriptCreater.description, GUILayout.Height(40))
            .Space(10)
            .DrawHorizontal(() => {
                GUILayout.Label(new GUIContent("Create Path:", "Drag Floder To Box"));
                Rect rect = EditorGUILayout.GetControlRect();
                rect.DrawOutLine(2, Color.black);
                EditorGUI.LabelField(rect, _scriptCreater.CreatePath);
                if (!rect.Contains(Event.current.mousePosition))
                {
                    return;
                }
                var info = DragAndDropUtil.Drag(Event.current, rect);
                if (info.paths.Length > 0 && info.compelete && info.enterArera && info.paths[0].IsDirectory())
                {
                    _scriptCreater.CreatePath = info.paths[0];
                }
            })
            .Space(10)
            .Toggle("Create Prefab", ref _scriptCreater.isCreatePrefab)
            .Pan(() => {
                if (_scriptCreater.isCreatePrefab)
                {
                    this.ETextField("Prefab Name", ref _scriptCreater.prefabName);
                    this.DrawHorizontal(() =>
                    {
                        GUILayout.Label(new GUIContent("Prefab Path:", "Drag Floder To Box"));
                        Rect rect = EditorGUILayout.GetControlRect();
                        rect.DrawOutLine(2, Color.black);
                        EditorGUI.LabelField(rect, _scriptCreater.prefabDirectory);
                        if (!rect.Contains(Event.current.mousePosition))
                        {
                            return;
                        }
                        var info = DragAndDropUtil.Drag(Event.current, rect);
                        if (info.paths.Length > 0 && info.compelete && info.enterArera && info.paths[0].IsDirectory())
                        {
                            _scriptCreater.prefabDirectory = info.paths[0];
                        }
                    });
                }
            })
            .Space(10)
            .DrawHorizontal(() => {
                if (GUILayout.Button("Build", GUILayout.Height(25)))
                {
                    if (BuildCheck())
                    {
                        Selection.objects = new Object[] { AssetDatabase.LoadAssetAtPath <Object>(_scriptCreater.CreatePath) };
                        CopyAsset.CopyNewAsset(_scriptCreater.ScriptName.Append(".cs"), originScriptPath);
                    }
                }
                if (GUILayout.Button("Remove", GUILayout.Height(25)))
                {
                    _scriptCreater.GetComponentsInChildren <ScriptMark>(true).ToList().ForEach((sm) => {
                        DestroyImmediate(sm);
                    });
                    DestroyImmediate(_scriptCreater);
                }
            });
            serializedObject.Update();
        }
Esempio n. 2
0
        public static void Texture(Texture texture, Vector2 textureSize)
        {
            var rect = EditorGUILayout.GetControlRect(false, GUILayout.Width(textureSize.x), GUILayout.Height(textureSize.y));

            GUI.DrawTexture(rect, texture);
        }
Esempio n. 3
0
        public override void Draw(InspectorField field, GUIStyle style)
        {
            IPicker picker = field.GetAttribute <IPicker>();

            if (picker != null && !picker.IsPickingAvailable(field.Instances, field.GetValues()))
            {
                object obj = field.GetValue();
                if (field.Mixed)
                {
                    GUILayout.Label("---");
                }
                else if (obj == null)
                {
                    GUILayout.Label("None");
                }
                else if (field.OverloadToString)
                {
                    GUILayout.Label(obj.ToString());
                }
                else if (field.Type != null)
                {
                    GUILayout.Label(field.Type.Name);
                }

                return;
            }

            if (validator == null)
            {
                validator = typeof(EditorGUI).GetNestedType("ObjectFieldValidator", BindingFlags.NonPublic);
            }

            if (doObjectField == null)
            {
                doObjectField = typeof(EditorGUI).GetMethod("DoObjectField", BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(Rect), typeof(Rect), typeof(int),
                                                                                                                                              typeof(UnityEngine.Object), typeof(Type), typeof(SerializedProperty), validator, typeof(bool), typeof(GUIStyle) }, null);
            }

            DontAllowSceneObjectAttribute dontAllow = field.GetAttribute <DontAllowSceneObjectAttribute>();;

            UnityEngine.Object value = (UnityEngine.Object)GetValue(field);

            EditorGUILayout.BeginHorizontal();
            EditorGUI.BeginChangeCheck();

            Type type = field.Type;

            if (value != null && AdvancedInspectorControl.ShowIconPreview)
            {
                if (previewIconStyle == null)
                {
                    previewIconStyle         = new GUIStyle();
                    previewIconStyle.margin  = new RectOffset(4, 2, 2, 2);
                    previewIconStyle.padding = new RectOffset(0, 0, 0, 0);
                }

                Texture2D preview = AssetPreview.GetAssetPreview(value);
                if (preview != null)
                {
                    int previewSize;
                    switch (AdvancedInspectorControl.IconPreviewSize)
                    {
                    case IconPreviewSize.Smallest:
                        previewSize = 16;
                        break;

                    case IconPreviewSize.Small:
                        previewSize = 24;
                        break;

                    case IconPreviewSize.Normal:
                        previewSize = 32;
                        break;

                    case IconPreviewSize.Large:
                        previewSize = 48;
                        break;

                    case IconPreviewSize.Largest:
                        previewSize = 64;
                        break;

                    default:
                        previewSize = 16;
                        break;
                    }

                    GUILayout.Label(preview, previewIconStyle, GUILayout.Width(previewSize), GUILayout.Height(previewSize));
                }
            }

            UnityEngine.Object result = null;

            if (type.IsInterface)
            {
                Rect position = EditorGUILayout.GetControlRect(false, 16f);

#if UNITY_5_6 || UNITY_2017
                int id = GUIUtility.GetControlID(s_ObjectFieldHash, FocusType.Passive, position);
#else
                int id = GUIUtility.GetControlID(s_ObjectFieldHash, EditorGUIUtility.native, position);
#endif
                Delegate validation = Delegate.CreateDelegate(validator, typeof(ObjectEditor).GetMethod("ValidateObjectFieldAssignment", BindingFlags.NonPublic | BindingFlags.Static));

                result = doObjectField.Invoke(null, new object[] { position, position, id, value, type, null, validation, dontAllow == null, EditorStyles.objectField }) as UnityEngine.Object;
            }
            else
            {
                result = EditorGUILayout.ObjectField(value, type, dontAllow == null);
            }

            if (EditorGUI.EndChangeCheck())
            {
                field.SetValue(result);
            }

            if (dontAllow == null && (field.Type == typeof(GameObject) ||
                                      typeof(Component).IsAssignableFrom(field.Type) || field.Type.IsAssignableFrom(typeof(Component))))
            {
                if (GUILayout.Button(Picker, GUIStyle.none, GUILayout.Width(18), GUILayout.Height(18)))
                {
                    InspectorEditor.StartPicking(Picked, field);
                }
            }

            EditorGUILayout.EndHorizontal();

            DrawObjectSelector(field);
        }
            void DrawMaterialMask(int materialCount)
            {
                int count = 0;

                if (target.allMaterialSelected) _builder.Append("All (Apply to Renderer)");
                else if (target.noneMaterialSelected) _builder.Append("None");
                else
                {
                    for (int i = 0; i < materialCount; i++)
                    {
                        if (target.IsMaterialSelected(i))
                        {
                            count++;

                            if (count > 1)
                            {
                                _builder.Append(", ");
                                if (count == 4)
                                {
                                    _builder.Append("...");
                                    break;
                                }
                            }

                            _builder.Append(i);
                            _builder.Append(": ");
                            _builder.Append(_materials[i] ? _materials[i].name : "(None)");
                        }
                    }
                }

                var rect = EditorGUILayout.GetControlRect();
                rect = EditorGUI.PrefixLabel(rect, EditorGUIKit.TempContent("Materials"));

                if (GUI.Button(rect, _builder.ToString(), EditorStyles.layerMaskField))
                {
                    GenericMenu menu = new GenericMenu();

                    menu.AddItem(new GUIContent("All (Apply to Renderer)"), target.allMaterialSelected, () =>
                    {
                        Undo.RecordObject(target, "Select Material");
                        target.SelectAllMaterials();
                    });

                    menu.AddItem(new GUIContent("None"), target.noneMaterialSelected, () =>
                    {
                        Undo.RecordObject(target, "Select Material");
                        target.DeselectAllMaterials();
                    });

                    if (materialCount > 0) menu.AddSeparator(string.Empty);

                    for (int i = 0; i < materialCount; i++)
                    {
                        int index = i;

                        menu.AddItem(new GUIContent(index + ": " + (_materials[index] ? _materials[index].name : "(None)")),
                            target.IsMaterialSelected(index),
                            () =>
                            {
                                Undo.RecordObject(target, "Select Material");
                                target.SetMaterialSelected(index, !target.IsMaterialSelected(index));
                            });
                    }

                    menu.DropDown(rect);
                }

                _builder.Clear();
            }
Esempio n. 5
0
        public virtual void DrawButtonToolbar()
        {
            GUILayout.BeginHorizontal();


            // Previous Command
            if ((Event.current.type == EventType.KeyDown) && (Event.current.keyCode == KeyCode.PageUp))
            {
                SelectPrevious();
                GUI.FocusControl("dummycontrol");
                Event.current.Use();
            }
            // Next Command
            if ((Event.current.type == EventType.KeyDown) && (Event.current.keyCode == KeyCode.PageDown))
            {
                SelectNext();
                GUI.FocusControl("dummycontrol");
                Event.current.Use();
            }

            if (GUILayout.Button(upIcon))
            {
                SelectPrevious();
            }

            // Down Button
            if (GUILayout.Button(downIcon))
            {
                SelectNext();
            }

            GUILayout.FlexibleSpace();


            //using false to prevent forcing a longer row than will fit on smallest inspector
            var pos = EditorGUILayout.GetControlRect(false, 0, EditorStyles.objectField);

            if (pos.x != 0)
            {
                lastCMDpopupPos    = pos;
                lastCMDpopupPos.x += EditorGUIUtility.labelWidth;
                lastCMDpopupPos.y += EditorGUIUtility.singleLineHeight * 2;
            }
            // Add Button
            if (GUILayout.Button(addIcon))
            {
                //this may be less reliable for HDPI scaling but previous method using editor window height is now returning
                //  null in 2019.2 suspect ongoing ui changes, so default to screen.height and then attempt to get the better result
                int h = Screen.height;
                if (EditorWindow.focusedWindow != null)
                {
                    h = (int)EditorWindow.focusedWindow.position.height;
                }
                else if (EditorWindow.mouseOverWindow != null)
                {
                    h = (int)EditorWindow.mouseOverWindow.position.height;
                }

                CommandSelectorPopupWindowContent.ShowCommandMenu(lastCMDpopupPos, "", target as Block,
                                                                  (int)(EditorGUIUtility.currentViewWidth),
                                                                  (int)(h - lastCMDpopupPos.y));
            }

            // Duplicate Button
            if (GUILayout.Button(duplicateIcon))
            {
                Copy();
                Paste();
            }

            // Delete Button
            if (GUILayout.Button(deleteIcon))
            {
                Delete();
            }

            GUILayout.EndHorizontal();
        }
Esempio n. 6
0
        public sealed override void OnInspectorGUI()
        {
            if (Utils.KeyHandler.HandleDetectKeyOnGUI(this.targets, Event.current))
            {
                return;
            }

            if (IsMainEditor && !typeof(ScriptableObject).IsAssignableFrom(target.GetType()))
            {
                var controlRect = EditorGUILayout.GetControlRect(false, 0.0f);
                if (m_icon == null)
                {
                    m_icon = IconManager.GetIcon("algoryx_white_shadow_icon");
                }

                if (m_icon != null)
                {
                    if (m_hideTexture == null)
                    {
#if UNITY_2019_3_OR_NEWER
                        var hideColor = Color.Lerp(InspectorGUI.BackgroundColor, Color.white, 0.03f);
#else
                        var hideColor = InspectorGUI.BackgroundColor;
#endif

                        m_hideTexture = GUI.CreateColoredTexture(1, 1, hideColor);
                    }

                    var hideRect = new Rect(controlRect.x,
#if UNITY_2019_3_OR_NEWER
                                            controlRect.y - 1.25f * EditorGUIUtility.singleLineHeight - 2,
#else
                                            controlRect.y - 1.00f * EditorGUIUtility.singleLineHeight - 1,
#endif
                                            18,
                                            EditorGUIUtility.singleLineHeight + 2);
                    UnityEngine.GUI.DrawTexture(hideRect, m_hideTexture);

                    var iconRect = new Rect(hideRect);
                    iconRect.height = 14.0f;
                    iconRect.width  = 14.0f;
#if UNITY_2019_3_OR_NEWER
                    iconRect.y += 2.5f;
#else
                    iconRect.y += 1.5f;
#endif
                    iconRect.x += 3.0f;
                    UnityEngine.GUI.DrawTexture(iconRect, m_icon);
                }

                InspectorGUI.BrandSeparator();
            }

            GUILayout.BeginVertical();

            ToolManager.OnPreTargetMembers(this.targets);

            DrawMembersGUI(this.targets, null, serializedObject);

            ToolManager.OnPostTargetMembers(this.targets);

            GUILayout.EndVertical();
        }
Esempio n. 7
0
    private void DrawPerf(PerfBasic perfData)
    {
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);

        var options = new string[perfData.RunData.Length + 1];

        options[0] = "Smooth all runs";
        for (int i = 1; i < perfData.RunData.Length + 1; i++)
        {
            options[i] = $"Run {i.ToString()}";
        }

        resultDataHeader = EditorGUILayout.BeginFoldoutHeaderGroup(resultDataHeader, "Data");
        if (resultDataHeader)
        {
            EditorGUILayout.Space(4);

            RunData runData;
            var     runtime = 0.0f;
            var     avg     = 0.0f;
            var     min     = new FrameData(-1, 0f);
            var     max     = new FrameData(-1, 0f);
            if (currentRun > 0)
            {
                runData = perfData.RunData[currentRun - 1];
                runtime = runData.RunTime;
                avg     = runData.AvgMs;
                min     = runData.MinFrame;
                max     = runData.MaxFrame;
            }
            else
            {
                avg     += perfData.RunData.Sum(data => data.AvgMs / perfData.RunData.Length);
                runtime += perfData.RunData.Sum(data => data.RunTime / perfData.RunData.Length);
            }

            EditorGUILayout.BeginHorizontal();
            {
                EditorGUI.BeginChangeCheck();
                var index = EditorGUILayout.Popup("Display", currentRun, options);
                if (EditorGUI.EndChangeCheck())
                {
                    currentRun = Mathf.Clamp(index, 0, options.Length + 1);
                }
            }
            EditorGUILayout.EndHorizontal();

            var graphRect = EditorGUILayout.GetControlRect(false, 500f);
            DrawGraph(graphRect, perfData, 0, avg * 2f);

            EditorGUILayout.BeginHorizontal();
            {
                EditorGUILayout.LabelField($"<b>Runtime:</b> {runtime:F2}s", Styles.richDefault,
                                           GUILayout.MaxWidth(120.0f));
                EditorGUILayout.LabelField($"<b>Average:</b> {avg:F2}ms", Styles.richDefault,
                                           GUILayout.MaxWidth(120.0f));
                EditorGUILayout.LabelField($"<b>Minimum(fastest):</b> {min.ms:F2}ms (@frame: {min.frameIndex})",
                                           Styles.richDefault);
                EditorGUILayout.LabelField($"<b>Maximum(slowest):</b> {max.ms:F2}ms (@frame: {max.frameIndex})",
                                           Styles.richDefault);
            }
            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Space(4f);
        }
        EditorGUILayout.EndFoldoutHeaderGroup();

        EditorGUILayout.EndVertical();
    }
Esempio n. 8
0
        public override void OnInspectorGUI()
        {
            if (s_Styles == null)
            {
                s_Styles = new Styles();
            }

            serializedObject.Update();

            var bs = NavMesh.GetSettingsByID(m_AgentTypeID.intValue);

            if (bs.agentTypeID != -1)
            {
                // Draw image
                const float diagramHeight    = 80.0f;
                Rect        agentDiagramRect = EditorGUILayout.GetControlRect(false, diagramHeight);
                NavMeshEditorHelpers.DrawAgentDiagram(agentDiagramRect, bs.agentRadius, bs.agentHeight, bs.agentClimb, bs.agentSlope);
            }
            NavMeshComponentsGUIUtility.AgentTypePopup("Agent Type", m_AgentTypeID);

            EditorGUILayout.Space();

            EditorGUILayout.PropertyField(m_CollectObjects);
            if ((CollectObjects)m_CollectObjects.enumValueIndex == CollectObjects.Volume)
            {
                EditorGUI.indentLevel++;

                EditMode.DoEditModeInspectorModeButton(EditMode.SceneViewEditMode.Collider, "Edit Volume",
                                                       EditorGUIUtility.IconContent("EditCollider"), GetBounds, this);
                EditorGUILayout.PropertyField(m_Size);
                EditorGUILayout.PropertyField(m_Center);

                EditorGUI.indentLevel--;
            }
            else
            {
                if (editingCollider)
                {
                    EditMode.QuitEditMode();
                }
            }

            EditorGUILayout.PropertyField(m_LayerMask, s_Styles.m_LayerMask);
            EditorGUILayout.PropertyField(m_UseGeometry);

            EditorGUILayout.Space();
            EditorGUILayout.PropertyField(m_OverrideByGrid);
            EditorGUILayout.PropertyField(m_UseMeshPrefab);
            EditorGUILayout.PropertyField(m_CompressBounds);
            EditorGUILayout.PropertyField(m_OverrideVector);

            EditorGUILayout.Space();

            m_OverrideVoxelSize.isExpanded = EditorGUILayout.Foldout(m_OverrideVoxelSize.isExpanded, "Advanced");
            if (m_OverrideVoxelSize.isExpanded)
            {
                EditorGUI.indentLevel++;

                NavMeshComponentsGUIUtility.AreaPopup("Default Area", m_DefaultArea);

                // Override voxel size.
                EditorGUILayout.PropertyField(m_OverrideVoxelSize);

                using (new EditorGUI.DisabledScope(!m_OverrideVoxelSize.boolValue || m_OverrideVoxelSize.hasMultipleDifferentValues))
                {
                    EditorGUI.indentLevel++;

                    EditorGUILayout.PropertyField(m_VoxelSize);

                    if (!m_OverrideVoxelSize.hasMultipleDifferentValues)
                    {
                        if (!m_AgentTypeID.hasMultipleDifferentValues)
                        {
                            float voxelsPerRadius = m_VoxelSize.floatValue > 0.0f ? (bs.agentRadius / m_VoxelSize.floatValue) : 0.0f;
                            EditorGUILayout.LabelField(" ", voxelsPerRadius.ToString("0.00") + " voxels per agent radius", EditorStyles.miniLabel);
                        }
                        if (m_OverrideVoxelSize.boolValue)
                        {
                            EditorGUILayout.HelpBox("Voxel size controls how accurately the navigation mesh is generated from the level geometry. A good voxel size is 2-4 voxels per agent radius. Making voxel size smaller will increase build time.", MessageType.None);
                        }
                    }
                    EditorGUI.indentLevel--;
                }

                // Override tile size
                EditorGUILayout.PropertyField(m_OverrideTileSize);

                using (new EditorGUI.DisabledScope(!m_OverrideTileSize.boolValue || m_OverrideTileSize.hasMultipleDifferentValues))
                {
                    EditorGUI.indentLevel++;

                    EditorGUILayout.PropertyField(m_TileSize);

                    if (!m_TileSize.hasMultipleDifferentValues && !m_VoxelSize.hasMultipleDifferentValues)
                    {
                        float tileWorldSize = m_TileSize.intValue * m_VoxelSize.floatValue;
                        EditorGUILayout.LabelField(" ", tileWorldSize.ToString("0.00") + " world units", EditorStyles.miniLabel);
                    }

                    if (!m_OverrideTileSize.hasMultipleDifferentValues)
                    {
                        if (m_OverrideTileSize.boolValue)
                        {
                            EditorGUILayout.HelpBox("Tile size controls the how local the changes to the world are (rebuild or carve). Small tile size allows more local changes, while potentially generating more data in overal.", MessageType.None);
                        }
                    }
                    EditorGUI.indentLevel--;
                }


                // Height mesh
                using (new EditorGUI.DisabledScope(true))
                {
                    EditorGUILayout.PropertyField(m_BuildHeightMesh);
                }

                EditorGUILayout.Space();
                EditorGUI.indentLevel--;
            }

            EditorGUILayout.Space();

            // Hide editor logs
            EditorGUILayout.PropertyField(m_HideEditorLogs);

            EditorGUILayout.Space();

            serializedObject.ApplyModifiedProperties();

            var hadError        = false;
            var multipleTargets = targets.Length > 1;

            foreach (NavMeshSurface2d navSurface in targets)
            {
                var settings = navSurface.GetBuildSettings();
                // Calculating bounds is potentially expensive when unbounded - so here we just use the center/size.
                // It means the validation is not checking vertical voxel limit correctly when the surface is set to something else than "in volume".
                var bounds = new Bounds(Vector3.zero, Vector3.zero);
                if (navSurface.collectObjects == CollectObjects2d.Volume)
                {
                    bounds = new Bounds(navSurface.center, navSurface.size);
                }

                var errors = settings.ValidationReport(bounds);
                if (errors.Length > 0)
                {
                    if (multipleTargets)
                    {
                        EditorGUILayout.LabelField(navSurface.name);
                    }
                    foreach (var err in errors)
                    {
                        EditorGUILayout.HelpBox(err, MessageType.Warning);
                    }
                    GUILayout.BeginHorizontal();
                    GUILayout.Space(EditorGUIUtility.labelWidth);
                    if (GUILayout.Button("Open Agent Settings...", EditorStyles.miniButton))
                    {
                        NavMeshEditorHelpers.OpenAgentSettings(navSurface.agentTypeID);
                    }
                    GUILayout.EndHorizontal();
                    hadError = true;
                }
            }

            if (hadError)
            {
                EditorGUILayout.Space();
            }

#if NAVMESHCOMPONENTS_SHOW_NAVMESHDATA_REF
            var nmdRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight);

            EditorGUI.BeginProperty(nmdRect, GUIContent.none, m_NavMeshData);
            var rectLabel = EditorGUI.PrefixLabel(nmdRect, GUIUtility.GetControlID(FocusType.Passive), new GUIContent(m_NavMeshData.displayName));
            EditorGUI.EndProperty();

            using (new EditorGUI.DisabledScope(true))
            {
                EditorGUI.BeginProperty(nmdRect, GUIContent.none, m_NavMeshData);
                EditorGUI.ObjectField(rectLabel, m_NavMeshData, GUIContent.none);
                EditorGUI.EndProperty();
            }
#endif
            using (new EditorGUI.DisabledScope(Application.isPlaying || m_AgentTypeID.intValue == -1))
            {
                GUILayout.BeginHorizontal();
                GUILayout.Space(EditorGUIUtility.labelWidth);
                if (GUILayout.Button("Clear"))
                {
                    NavMeshAssetManager2d.instance.ClearSurfaces(targets);
                    SceneView.RepaintAll();
                }

                if (GUILayout.Button("Bake"))
                {
                    NavMeshAssetManager2d.instance.StartBakingSurfaces(targets);
                }

                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                GUILayout.Space(EditorGUIUtility.labelWidth);
                if (GUILayout.Button("Rotate Surface to XY"))
                {
                    foreach (var item in targets)
                    {
                        var o = item as NavMeshSurface2d;
                        o.transform.rotation = Quaternion.Euler(-90f, 0f, 0f);
                    }
                }
                GUILayout.EndHorizontal();
            }

            // Show progress for the selected targets
            var bakeOperations = NavMeshAssetManager2d.instance.GetBakeOperations();
            for (int i = bakeOperations.Count - 1; i >= 0; --i)
            {
                if (!targets.Contains(bakeOperations[i].surface))
                {
                    continue;
                }

                var oper = bakeOperations[i].bakeOperation;
                if (oper == null)
                {
                    continue;
                }

                var p = oper.progress;
                if (oper.isDone)
                {
                    SceneView.RepaintAll();
                    continue;
                }

                GUILayout.BeginHorizontal();

                if (GUILayout.Button("Cancel", EditorStyles.miniButton))
                {
                    var bakeData = bakeOperations[i].bakeData;
                    UnityEngine.AI.NavMeshBuilder.Cancel(bakeData);
                    bakeOperations.RemoveAt(i);
                }

                EditorGUI.ProgressBar(EditorGUILayout.GetControlRect(), p, "Baking: " + (int)(100 * p) + "%");
                if (p <= 1)
                {
                    Repaint();
                }

                GUILayout.EndHorizontal();
            }
        }
Esempio n. 9
0
 public static vec3 vec3Field(string label, vec3 value, bool showLength = false, params GUILayoutOption[] options)
 {
     return(MathExGUI.vec3Field(MathExGUILayout.s_LastRect = EditorGUILayout.GetControlRect(false, 16f, EditorStyles.numberField, options), label, value, showLength));
 }
Esempio n. 10
0
        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            VRTK_SDKManager sdkManager          = (VRTK_SDKManager)target;
            const string    manageNowButtonText = "Manage Now";

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Scripting Define Symbols", false);

                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUI.BeginChangeCheck();
                    bool autoManage = EditorGUILayout.Toggle(
                        VRTK_EditorUtilities.BuildGUIContent <VRTK_SDKManager>("autoManageScriptDefines", "Auto Manage"),
                        sdkManager.autoManageScriptDefines,
                        GUILayout.ExpandWidth(false)
                        );
                    if (EditorGUI.EndChangeCheck())
                    {
                        serializedObject.FindProperty("autoManageScriptDefines").boolValue = autoManage;
                        serializedObject.ApplyModifiedProperties();
                        sdkManager.ManageScriptingDefineSymbols(false, true);
                    }

                    using (new EditorGUI.DisabledGroupScope(sdkManager.autoManageScriptDefines))
                    {
                        GUIContent manageNowGUIContent = new GUIContent(
                            manageNowButtonText,
                            "Manage the scripting define symbols defined by the installed SDKs."
                            + (sdkManager.autoManageScriptDefines
                                   ? "\n\nThis button is disabled because the SDK Manager is set up to manage the scripting define symbols automatically."
                               + " Disable the checkbox on the left to allow managing them manually instead."
                                   : "")
                            );
                        if (GUILayout.Button(manageNowGUIContent, GUILayout.MaxHeight(GUI.skin.label.CalcSize(manageNowGUIContent).y)))
                        {
                            sdkManager.ManageScriptingDefineSymbols(true, true);
                        }
                    }
                }

                using (new EditorGUILayout.VerticalScope("Box"))
                {
                    VRTK_EditorUtilities.AddHeader("Active Symbols Without SDK Classes", false);

                    VRTK_SDKInfo[] availableSDKInfos = VRTK_SDKManager
                                                       .AvailableSystemSDKInfos
                                                       .Concat(VRTK_SDKManager.AvailableBoundariesSDKInfos)
                                                       .Concat(VRTK_SDKManager.AvailableHeadsetSDKInfos)
                                                       .Concat(VRTK_SDKManager.AvailableControllerSDKInfos)
                                                       .ToArray();
                    HashSet <string> sdkSymbols = new HashSet <string>(availableSDKInfos.Select(info => info.description.symbol));
                    IGrouping <BuildTargetGroup, VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo>[] availableGroupedPredicateInfos = VRTK_SDKManager
                                                                                                                                        .AvailableScriptingDefineSymbolPredicateInfos
                                                                                                                                        .GroupBy(info => info.attribute.buildTargetGroup)
                                                                                                                                        .ToArray();
                    foreach (IGrouping <BuildTargetGroup, VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo> grouping in availableGroupedPredicateInfos)
                    {
                        VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo[] possibleActiveInfos = grouping
                                                                                                   .Where(info => !sdkSymbols.Contains(info.attribute.symbol) &&
                                                                                                          grouping.Except(new[] { info })
                                                                                                          .All(predicateInfo => !(predicateInfo.methodInfo == info.methodInfo &&
                                                                                                                                  sdkSymbols.Contains(predicateInfo.attribute.symbol))))
                                                                                                   .OrderBy(info => info.attribute.symbol)
                                                                                                   .ToArray();
                        if (possibleActiveInfos.Length == 0)
                        {
                            continue;
                        }

                        EditorGUI.indentLevel++;

                        BuildTargetGroup targetGroup = grouping.Key;
                        isBuildTargetActiveSymbolsFoldOut[targetGroup] = EditorGUI.Foldout(
                            EditorGUILayout.GetControlRect(),
                            isBuildTargetActiveSymbolsFoldOut[targetGroup],
                            targetGroup.ToString(),
                            true
                            );

                        if (isBuildTargetActiveSymbolsFoldOut[targetGroup])
                        {
                            foreach (VRTK_SDKManager.ScriptingDefineSymbolPredicateInfo predicateInfo in possibleActiveInfos)
                            {
                                int symbolIndex = sdkManager
                                                  .activeScriptingDefineSymbolsWithoutSDKClasses
                                                  .FindIndex(attribute => attribute.symbol == predicateInfo.attribute.symbol);
                                string symbolLabel = predicateInfo.attribute.symbol.Remove(
                                    0,
                                    SDK_ScriptingDefineSymbolPredicateAttribute.RemovableSymbolPrefix.Length
                                    );

                                if (!(bool)predicateInfo.methodInfo.Invoke(null, null))
                                {
                                    symbolLabel += " (not installed)";
                                }

                                EditorGUI.BeginChangeCheck();
                                bool isSymbolActive = EditorGUILayout.ToggleLeft(symbolLabel, symbolIndex != -1);
                                if (EditorGUI.EndChangeCheck())
                                {
                                    Undo.RecordObject(sdkManager, "Active Symbol Change");
                                    if (isSymbolActive)
                                    {
                                        sdkManager.activeScriptingDefineSymbolsWithoutSDKClasses.Add(predicateInfo.attribute);
                                    }
                                    else
                                    {
                                        sdkManager.activeScriptingDefineSymbolsWithoutSDKClasses.RemoveAt(symbolIndex);
                                    }
                                    sdkManager.ManageScriptingDefineSymbols(false, true);
                                }
                            }
                        }

                        EditorGUI.indentLevel--;
                    }
                }

                VRTK_EditorUtilities.DrawUsingDestructiveStyle(GUI.skin.button, style =>
                {
                    GUIContent clearSymbolsGUIContent = new GUIContent(
                        "Remove All Symbols",
                        "Remove all scripting define symbols of VRTK. This is handy if you removed the SDK files from your project but still have"
                        + " the symbols defined which results in compile errors."
                        + "\nIf you have the above checkbox enabled the symbols will be managed automatically after clearing them. Otherwise hit the"
                        + " '" + manageNowButtonText + "' button to add the symbols for the currently installed SDKs again."
                        );

                    if (GUILayout.Button(clearSymbolsGUIContent, style))
                    {
                        BuildTargetGroup[] targetGroups = VRTK_SharedMethods.GetValidBuildTargetGroups();

                        foreach (BuildTargetGroup targetGroup in targetGroups)
                        {
                            string[] currentSymbols = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup)
                                                      .Split(';')
                                                      .Distinct()
                                                      .OrderBy(symbol => symbol, StringComparer.Ordinal)
                                                      .ToArray();
                            string[] newSymbols = currentSymbols
                                                  .Where(symbol => !symbol.StartsWith(SDK_ScriptingDefineSymbolPredicateAttribute.RemovableSymbolPrefix, StringComparison.Ordinal))
                                                  .ToArray();

                            if (currentSymbols.SequenceEqual(newSymbols))
                            {
                                continue;
                            }

                            PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", newSymbols));

                            string[] removedSymbols = currentSymbols.Except(newSymbols).ToArray();
                            if (removedSymbols.Length > 0)
                            {
                                VRTK_Logger.Info(VRTK_Logger.GetCommonMessage(VRTK_Logger.CommonMessageKeys.SCRIPTING_DEFINE_SYMBOLS_REMOVED, targetGroup, string.Join(", ", removedSymbols)));
                            }
                        }
                    }
                });
            }

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Script Aliases", false);
                EditorGUILayout.PropertyField(
                    serializedObject.FindProperty("scriptAliasLeftController"),
                    VRTK_EditorUtilities.BuildGUIContent <VRTK_SDKManager>("scriptAliasLeftController", "Left Controller")
                    );
                EditorGUILayout.PropertyField(
                    serializedObject.FindProperty("scriptAliasRightController"),
                    VRTK_EditorUtilities.BuildGUIContent <VRTK_SDKManager>("scriptAliasRightController", "Right Controller")
                    );
            }

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Setups", false);

                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUI.BeginChangeCheck();
                    bool autoManage = EditorGUILayout.Toggle(
                        VRTK_EditorUtilities.BuildGUIContent <VRTK_SDKManager>("autoManageVRSettings"),
                        sdkManager.autoManageVRSettings,
                        GUILayout.ExpandWidth(false)
                        );
                    if (EditorGUI.EndChangeCheck())
                    {
                        serializedObject.FindProperty("autoManageVRSettings").boolValue = autoManage;
                        serializedObject.ApplyModifiedProperties();
                        sdkManager.ManageVRSettings(false);
                    }

                    using (new EditorGUI.DisabledGroupScope(sdkManager.autoManageVRSettings))
                    {
                        GUIContent manageNowGUIContent = new GUIContent(
                            manageNowButtonText,
                            "Manage the VR settings of the Player Settings to allow for all the installed SDKs."
                            + (sdkManager.autoManageVRSettings
                                   ? "\n\nThis button is disabled because the SDK Manager is set up to manage the VR Settings automatically."
                               + " Disable the checkbox on the left to allow managing them manually instead."
                                   : "")
                            );
                        if (GUILayout.Button(manageNowGUIContent, GUILayout.MaxHeight(GUI.skin.label.CalcSize(manageNowGUIContent).y)))
                        {
                            sdkManager.ManageVRSettings(true);
                        }
                    }
                }

                EditorGUILayout.PropertyField(
                    serializedObject.FindProperty("autoLoadSetup"),
                    VRTK_EditorUtilities.BuildGUIContent <VRTK_SDKManager>("autoLoadSetup", "Auto Load")
                    );

                setupsList.DoLayoutList();

                GUIContent autoPopulateGUIContent = new GUIContent("Auto Populate", "Automatically populates the list of SDK Setups with Setups in the scene.");
                if (GUILayout.Button(autoPopulateGUIContent))
                {
                    SerializedProperty serializedProperty = setupsList.serializedProperty;
                    serializedProperty.ClearArray();
                    VRTK_SDKSetup[] setups = sdkManager.GetComponentsInChildren <VRTK_SDKSetup>(true)
                                             .Concat(VRTK_SharedMethods.FindEvenInactiveComponents <VRTK_SDKSetup>(true))
                                             .Distinct()
                                             .ToArray();

                    for (int index = 0; index < setups.Length; index++)
                    {
                        VRTK_SDKSetup setup = setups[index];
                        serializedProperty.InsertArrayElementAtIndex(index);
                        serializedProperty.GetArrayElementAtIndex(index).objectReferenceValue = setup;
                    }
                }

                if (sdkManager.setups.Length > 1)
                {
                    EditorGUILayout.HelpBox("Duplicated setups are removed automatically.", MessageType.Info);
                }

                if (Enumerable.Range(0, sdkManager.setups.Length).Any(IsSDKSetupNeverUsed))
                {
                    EditorGUILayout.HelpBox("Gray setups will never be loaded because either the SDK Setup isn't valid or there"
                                            + " is a valid Setup before it that uses any non-VR SDK.",
                                            MessageType.Warning);
                }
            }

            using (new EditorGUILayout.VerticalScope("Box"))
            {
                VRTK_EditorUtilities.AddHeader("Target Platform Group Exclusions", false);
                SerializedProperty excludeTargetGroups = serializedObject.FindProperty("excludeTargetGroups");
                excludeTargetGroups.arraySize = EditorGUILayout.IntField("Size", excludeTargetGroups.arraySize);
                for (int i = 0; i < excludeTargetGroups.arraySize; i++)
                {
                    EditorGUILayout.PropertyField(excludeTargetGroups.GetArrayElementAtIndex(i));
                }
            }

            EditorGUILayout.PropertyField(serializedObject.FindProperty("persistOnLoad"));

            serializedObject.ApplyModifiedProperties();
        }
Esempio n. 11
0
    public override void OnInspectorGUI()
    {
        SetupAFS = new SerializedObject(target);
        GetProperties();
        SetupAfs script = (SetupAfs)target;

        //if(icnLight == null) {
        getIcons();
        //}


//	///////////////////////////////////////////////////
//	Style Settings
        // Colors for Pro
        Color myCol        = new Color(.5f, .8f, .0f, 1f); // Light Green // new Color(.6f, .9f, .22f, 1f); // Light Green
        Color myBgCol      = myCol;                        //new Color(.5f, .75f, .24f, 1f);
        Color SplitterCol  = new Color(1f, 1f, 1f, 0.075f);
        Color SplitterCol1 = new Color(.6f, .9f, .22f, .005f);
        Color myCol01      = new Color(0.30f, 0.47f, 1.0f, 1.0f);

        // Colors for Indie
        if (!EditorGUIUtility.isProSkin)
        {
            myCol        = new Color(0.05f, 0.45f, 0.0f, 1.0f);   // Dark Green
            myBgCol      = new Color(0.94f, 0.94f, 0.94f, 1.0f);
            SplitterCol  = new Color(0f, 0f, 0f, 0.125f);
            SplitterCol1 = new Color(1f, 1f, 1f, 0.5f);
            myCol01      = Color.blue;
        }
        //Color myBlue = new Color(0.5f,0.7f,1.0f,1.0f);

        // Custom Foldout
        GUIStyle myFoldoutStyle = new GUIStyle(EditorStyles.foldout);

        myFoldoutStyle.fontStyle = FontStyle.Bold;
        myFoldoutStyle.fontSize  = 12;

        myFoldoutStyle.normal.textColor   = myCol;
        myFoldoutStyle.onNormal.textColor = myCol;
        //myFoldoutStyle.hover.textColor = Color.white;
        //myFoldoutStyle.onHover.textColor = Color.white;
        myFoldoutStyle.active.textColor    = myCol;
        myFoldoutStyle.onActive.textColor  = myCol;
        myFoldoutStyle.focused.textColor   = myCol;
        myFoldoutStyle.onFocused.textColor = myCol;

        GUIStyle myRegularFoldoutStyle = new GUIStyle(myFoldoutStyle);

        myRegularFoldoutStyle.fontStyle = FontStyle.Normal;

        // Custom Label
        GUIStyle myLabel = new GUIStyle(EditorStyles.label);

        myLabel.normal.textColor   = myCol;
        myLabel.onNormal.textColor = myCol;

        // Default icon Size
        EditorGUIUtility.SetIconSize(new Vector2(16, 16));

        GUIStyle myMiniHelpBtn = new GUIStyle(EditorStyles.miniButton);

        myMiniHelpBtn.padding             = new RectOffset(0, 0, 2, 2);
        myMiniHelpBtn.normal.background   = null;
        myMiniHelpBtn.normal.textColor    = myCol01;
        myMiniHelpBtn.onNormal.textColor  = myCol01;
        myMiniHelpBtn.active.textColor    = myCol01;
        myMiniHelpBtn.onActive.textColor  = myCol01;
        myMiniHelpBtn.focused.textColor   = myCol01;
        myMiniHelpBtn.onFocused.textColor = myCol01;

        GUILayout.Space(8);

//	///////////////////////////////////////////////////
//	Wind settings
        GUILayout.Space(4);
        GUI.backgroundColor = myBgCol;
        EditorGUILayout.BeginVertical("Box");
        // Foldout incl. Icon
        EditorGUILayout.BeginHorizontal();
        GUILayout.Space(-2);
        EditorGUI.indentLevel++;
        EditorGUILayout.BeginVertical();
        script.FoldWind = EditorGUILayout.Foldout(script.FoldWind, "Wind Settings", myFoldoutStyle);
        EditorGUILayout.EndVertical();
        EditorGUI.indentLevel--;

        if (GUILayout.Button("Help", myMiniHelpBtn, GUILayout.Width(40)))
        {
            Application.OpenURL(baseURL + "h.rxwg5xlcsukv");
        }

        EditorGUILayout.BeginVertical(GUILayout.Width(20));
        // Label needs width!
        EditorGUILayout.LabelField(new GUIContent(icnWind), GUILayout.Width(20), GUILayout.Height(20));
        EditorGUILayout.EndVertical();
        GUI.backgroundColor = Color.white;
        EditorGUILayout.EndHorizontal();
        GUILayout.Space(-2);
        EditorGUILayout.EndVertical();
        // FoldoutContent
        if (script.FoldWind)
        {
            GUILayout.Space(-5);
            EditorGUILayout.BeginVertical("Box");
            DrawSplitter1(EditorGUILayout.GetControlRect(false, 4), SplitterCol1);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(13);
            EditorGUILayout.BeginVertical();

            //	Foliage
            GUILayout.Label("Wind Settings for Foliage Shaders", myLabel);
            GUILayout.Space(2);
            toolTip = "Multiplier to adjust the Bending of Foliage independently from Grass and Trees.";
            EditorGUILayout.PropertyField(Foliage_WindPrimaryStrength, new GUIContent("Main Strength", toolTip));
            EditorGUILayout.PropertyField(Foliage_WindSecondaryStrength, new GUIContent("Turbulence Strength", toolTip));
            GUILayout.Space(4);
            toolTip = "Factor the original frequency of the secondary bending gets multiplied with. It determines the max frequency leaves might bend in when effected by strong winds.";
            EditorGUILayout.PropertyField(Foliage_LeafTurbulence, new GUIContent("Leaf Turbulence*", toolTip));
            toolTip = "The shader adds some variation to the bending taking the vertex position in world space and the 'Wave Size Foliage' " +
                      "parameter into account. So smaller wave sizes will add more variety to a given area but also lead to slightly different amounts of bending on each vertex even of a single mesh. This might cause some strange distortion of your models – especially large models. " +
                      "For this reason you should set the 'Wave Size' to at least 2 or even 3 times the bounding box size of the largest model.";
            EditorGUILayout.PropertyField(Foliage_WaveSize, new GUIContent("Wave Size*", toolTip));

            //	Grass
            GUILayout.Space(6);
            GUILayout.Label("Wind Settings for Grass Shaders", myLabel);
            GUILayout.Space(2);
            toolTip = "Multiplier to adjust the Bending of Grass independently from Foliage and Trees.";
            EditorGUILayout.PropertyField(Grass_WindStrength, new GUIContent("Strength", toolTip));
            toolTip = "Defines the Speed of the wind animation on grass.";
            EditorGUILayout.PropertyField(Grass_WindSpeed, new GUIContent("Speed", toolTip));
            toolTip = "Similar to the terrain's original 'Size' parameter: The size of the 'ripples' on grassy areas as the wind blows over them.\n*Do not change at run time.";
            EditorGUILayout.PropertyField(Grass_WaveSize, new GUIContent("Wave Size*", toolTip));

            GUILayout.Space(4);
            toolTip = "Breaks up the uniform movement defined by 'Size'.\n*Do not change at run time.";
            EditorGUILayout.PropertyField(Grass_WindJitterVariation, new GUIContent("Turbulence*", toolTip));
            toolTip = "Defines the Strength of the second wind animation.";
            EditorGUILayout.PropertyField(Grass_WindJitterScale, new GUIContent("Jitter", toolTip));

            //	Trees
            GUILayout.Space(6);
            GUILayout.Label("Wind Settings for Tree Creator Shaders", myLabel);
            GUILayout.Space(2);
            toolTip = "Multiplier to adjust the Bending of the Tree Creator Shaders independently from Foliage and Grass.";
            EditorGUILayout.PropertyField(Trees_WindPrimaryStrength, new GUIContent("Main Strength", toolTip));
            EditorGUILayout.PropertyField(Trees_WindSecondaryStrength, new GUIContent("Turbulence Strength", toolTip));

            GUILayout.Space(4);
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();
            EditorGUILayout.EndVertical();
        }

//	///////////////////////////////////////////////////
//	Terrain Vegetation Settings
        GUILayout.Space(4);
        GUI.backgroundColor = myBgCol;
        EditorGUILayout.BeginVertical("Box");
        // Foldout incl. Icon
        EditorGUILayout.BeginHorizontal();
        GUILayout.Space(-2);
        EditorGUI.indentLevel++;
        EditorGUILayout.BeginVertical();
        script.FoldVegTerrain = EditorGUILayout.Foldout(script.FoldVegTerrain, "Terrain Vegetation Settings", myFoldoutStyle);
        EditorGUILayout.EndVertical();
        EditorGUI.indentLevel--;

        if (GUILayout.Button("Help", myMiniHelpBtn, GUILayout.Width(40)))
        {
            Application.OpenURL(baseURL + "h.fh0ejrtye3qo");
        }

        EditorGUILayout.BeginVertical(GUILayout.Width(20));
        // GUILayout.Space(2);
        // Label needs width!
        EditorGUILayout.LabelField(new GUIContent(icnTerr), GUILayout.Width(20), GUILayout.Height(20));
        EditorGUILayout.EndVertical();
        GUI.backgroundColor = Color.white;
        EditorGUILayout.EndHorizontal();
        GUILayout.Space(-2);
        EditorGUILayout.EndVertical();

        // FoldoutContent
        if (script.FoldVegTerrain)
        {
            GUILayout.Space(-5);
            EditorGUILayout.BeginVertical("Box");
            DrawSplitter1(EditorGUILayout.GetControlRect(false, 4), SplitterCol1);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(13);

            EditorGUILayout.BeginVertical();
            // General Billboard settings
            EditorGUILayout.LabelField("Sync Settings with Terrain", myLabel);
            GUILayout.Space(2);

            EditorGUILayout.BeginHorizontal();
            //script.AutoSyncToTerrain = EditorGUILayout.Toggle("", script.AutoSyncToTerrain, GUILayout.Width(14) );
            EditorGUILayout.PropertyField(AutoSyncToTerrain, GUIContent.none, GUILayout.Width(14));
            EditorGUILayout.LabelField("Automatically sync with Terrain");
            EditorGUILayout.EndHorizontal();

            if (AutoSyncToTerrain.boolValue)
            {
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(SyncedTerrain, new GUIContent(" Specify Terrain"));
                EditorGUI.indentLevel--;
                if (SyncedTerrain.objectReferenceValue != null)
                {
                    GUI.enabled = false;
                }
                else
                {
                    EditorGUILayout.HelpBox("Please assign a terrain.", MessageType.Warning, true);
                }
            }
            else
            {
                GUILayout.Space(4);
                EditorGUILayout.HelpBox("Please make sure that the parameters marked with * match those in your terrain settings. Otherwise shading might look corrupted.\nYou may also check: 'Automatically sync with Terrain'. ", MessageType.Warning, true);
            }
            GUI.enabled = true;

            GUILayout.Space(6);
            EditorGUILayout.LabelField("Grass and Detail Settings", myLabel);
            GUILayout.Space(2);
            if (AutoSyncToTerrain.boolValue)
            {
                GUI.enabled = false;
            }
            toolTip = "The distance (from camera) towards which grass will fade out (should fit your terrain’s settings).";
            EditorGUILayout.PropertyField(DetailDistanceForGrassShader, new GUIContent("Detail Distance*", toolTip));
            toolTip = "Overall color tint applied to grass objects (should fit your terrain’s settings).";
            EditorGUILayout.PropertyField(GrassWavingTint, new GUIContent("Grass Waving Tint*", toolTip));
            GUI.enabled = true;

            //	Tree and Billboard Render settings
            GUILayout.Space(6);
            EditorGUILayout.LabelField("Tree and Billboard Settings", myLabel);
            GUILayout.Space(2);
            if (AutoSyncToTerrain.boolValue)
            {
                GUI.enabled = false;
            }
            //
            toolTip = "The distance (from camera) at which 3D tree objects will be replaced by billboard images (should fit your terrain’s settings).";
            EditorGUILayout.PropertyField(BillboardStart, new GUIContent("Billboard Start*", toolTip));
            toolTip = "Fade length for translucency and real time shadows.";
            EditorGUILayout.PropertyField(BillboardFadeLenght, new GUIContent("Fade Length*", toolTip));
            GUI.enabled = true;

            EditorGUILayout.BeginHorizontal();
            toolTip = "Usually tree are simply tinted with black if you set the „color variation“ > 0 while painting trees. You may replace this color by any one you like using this color field.";
            EditorGUILayout.PropertyField(TreeColor, new GUIContent("Tint Color", toolTip));
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(2);
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PropertyField(BillboardAdjustToCamera, GUIContent.none, GUILayout.Width(14));
            EditorGUILayout.LabelField("Align Billboards to Camera");
            EditorGUILayout.EndHorizontal();
            if (BillboardAdjustToCamera.boolValue)
            {
                EditorGUI.indentLevel++;
                toolTip = "Defines the angle (when viewed from above) the billboard shader will fade to the 'classical' upright oriented billboards in order to reduce distortion artifacts. The standard value is '30'.";
                EditorGUILayout.PropertyField(BillboardAngleLimit, new GUIContent(" Angle Limit", toolTip));
                EditorGUI.indentLevel--;
            }
            GUILayout.Space(2);
            toolTip = "Instead of simply culling the billboards beyond the 'Tree distance' specified in the terrain settings you may define a length over which the billboards will smoothly fade out. Please note: This only works if you use the alpha blending Billboardshader.";
            EditorGUILayout.PropertyField(BillboardFadeOutLength, new GUIContent("Billboard Fade Length", toolTip));
            GUILayout.Space(4);

            //	General Vegetation settings
            GUILayout.Space(6);
            EditorGUILayout.LabelField("Terrain Detail Vegetation Settings", myLabel);

            GUILayout.Space(6);
            toolTip = "Enable legacy bending on 'detail meshes' using the built in vertexLit shader.";
            EditorGUILayout.PropertyField(TerrainLegacyBending, new GUIContent("Legacy Bending", toolTip));

            GUILayout.Space(6);

            toolTip = "Lets you you define a color which gets multiplied on top of the albedo and varies from instance to instance. Alpha defines the maximum strength.";
            EditorGUILayout.PropertyField(VertexLitColorVariation, new GUIContent("Color Variation", toolTip));
            toolTip = "Cutoff value for all models placed as 'detail mesh' using the built in terrain engine.";
            EditorGUILayout.PropertyField(VertexLitAlphaCutOff, new GUIContent("Alpha Cutoff", toolTip));

            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PrefixLabel("Combined Detail Atlas");
            EditorGUI.BeginChangeCheck();
            tempTex = (Texture2D)EditorGUILayout.ObjectField(TerrainFoliageNrmSpecMap.objectReferenceValue, typeof(Texture2D), false, GUILayout.MinHeight(64), GUILayout.MinWidth(64), GUILayout.MaxWidth(64));
            if (EditorGUI.EndChangeCheck())
            {
                if (tempTex != null)
                {
                    TerrainFoliageNrmSpecMap.objectReferenceValue = tempTex;
                }
                else
                {
                    string[] guIDS = AssetDatabase.FindAssets("Afs default Terrain [Normal] [Smoothness] [Trans]");
                    if (guIDS.Length > 0)
                    {
                        TerrainFoliageNrmSpecMap.objectReferenceValue = (Texture2D)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guIDS[0]), typeof(Texture2D));
                    }
                }
            }
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(4);

            toolTip = "Specular Color for all models placed as 'detail mesh' using the built in terrain engine.";
            EditorGUILayout.PropertyField(VertexLitSpecularReflectivity, new GUIContent("Specular Color", toolTip));
            toolTip = "Translucency multiplier for all models placed as 'detail mesh' using the built in terrain engine.";
            EditorGUILayout.PropertyField(VertexLitTranslucency, new GUIContent("Translucency Strength", toolTip));
            toolTip = "Lets you adjust the smoothness on backfaces. This feature only works with single sided leaf geometry.";
            EditorGUILayout.PropertyField(VertexLitBackfaceSmoothness, new GUIContent("Backface Smoothness", toolTip));
            toolTip = "Lets you suppress 'wrong' ambient specular reflections on all models placed as 'detail mesh' using the built in terrain engine.";
            EditorGUILayout.PropertyField(VertexLitHorizonFade, new GUIContent("Horizon Fade", toolTip));

            GUILayout.Space(6);

            toolTip = "Global factor for all plants using the vertex lit shader. Increasing Leaf Turbulence will make those parts of the plants which are affected by secondary bending sway faster if the wind blows stronger.\n*Do not change at run time.";
            EditorGUILayout.PropertyField(VertexLitLeafTurbulence, new GUIContent("Leaf Turbulence*", toolTip));
            toolTip = "Larger Terrains need larger values.";
            EditorGUILayout.PropertyField(VertexLitVariationMultipilier, new GUIContent("Variation", toolTip));

            GUILayout.Space(6);
            EditorGUILayout.LabelField("Grass Settings", myLabel);
            GUILayout.Space(6);

            toolTip = "Base Smoothness of Grass masked by Translucency.";
            EditorGUILayout.PropertyField(GrassMinSmoothness, new GUIContent("Min Smoothness", toolTip));
            toolTip = "Max Smoothness of wet Grass masked by Translucency.";
            EditorGUILayout.PropertyField(GrassMaxSmoothness, new GUIContent("Max Smoothness", toolTip));

            GUILayout.Space(2);

            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();
            GUILayout.Space(4);
            EditorGUILayout.EndVertical();
        }

//	///////////////////////////////////////////////////
//	Rain settings
        GUILayout.Space(4);
        GUI.backgroundColor = myBgCol;
        EditorGUILayout.BeginVertical("Box");
        // Foldout incl. Icon
        EditorGUILayout.BeginHorizontal();
        GUILayout.Space(-2);
        EditorGUI.indentLevel++;
        EditorGUILayout.BeginVertical();
        script.FoldRain = EditorGUILayout.Foldout(script.FoldRain, "Rain Settings", myFoldoutStyle);
        EditorGUILayout.EndVertical();
        EditorGUI.indentLevel--;

        if (GUILayout.Button("Help", myMiniHelpBtn, GUILayout.Width(40)))
        {
            Application.OpenURL(baseURL + "h.bgp2x18s4scm");
        }

        EditorGUILayout.BeginVertical(GUILayout.Width(20));
        // Label needs width!
        EditorGUILayout.LabelField(new GUIContent(icnRain), GUILayout.Width(20), GUILayout.Height(20));
        EditorGUILayout.EndVertical();
        GUI.backgroundColor = Color.white;
        EditorGUILayout.EndHorizontal();
        GUILayout.Space(-2);
        EditorGUILayout.EndVertical();
        // FoldoutContent
        if (script.FoldRain)
        {
            GUILayout.Space(-5);
            EditorGUILayout.BeginVertical("Box");
            DrawSplitter1(EditorGUILayout.GetControlRect(false, 4), SplitterCol1);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(13);
            EditorGUILayout.PropertyField(RainAmount, new GUIContent("Rain Amount"));
            EditorGUILayout.EndHorizontal();
            GUILayout.Space(4);
            EditorGUILayout.EndVertical();
        }

//	///////////////////////////////////////////////////
//	Lighting settings
        GUILayout.Space(4);
        GUI.backgroundColor = myBgCol;
        EditorGUILayout.BeginVertical("Box");
        // Foldout incl. Icon
        EditorGUILayout.BeginHorizontal();
        GUILayout.Space(-2);
        EditorGUI.indentLevel++;
        EditorGUILayout.BeginVertical();
        script.FoldLighting = EditorGUILayout.Foldout(script.FoldLighting, "Lighting Settings", myFoldoutStyle);
        EditorGUILayout.EndVertical();
        EditorGUI.indentLevel--;

        if (GUILayout.Button("Help", myMiniHelpBtn, GUILayout.Width(40)))
        {
            Application.OpenURL(baseURL + "h.ak1o9whdfzet");
        }

        EditorGUILayout.BeginVertical(GUILayout.Width(20));
        // Label needs width!
        EditorGUILayout.LabelField(new GUIContent(icnLight), GUILayout.Width(20), GUILayout.Height(20));
        EditorGUILayout.EndVertical();
        GUI.backgroundColor = Color.white;
        EditorGUILayout.EndHorizontal();
        GUILayout.Space(-2);
        EditorGUILayout.EndVertical();
        // FoldoutContent
        if (script.FoldLighting)
        {
            GUILayout.Space(-5);
            EditorGUILayout.BeginVertical("Box");
            DrawSplitter1(EditorGUILayout.GetControlRect(false, 4), SplitterCol1);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(13);
            EditorGUILayout.BeginVertical();
            EditorGUILayout.LabelField("Foliage specular and translucent Lighting Settings", myLabel);
            GUILayout.Space(2);
            EditorGUI.BeginChangeCheck();
            specFade.x = EditorGUILayout.Slider("Range", AfsSpecFade.vector2Value.x, 0.0f, 100.0f);
            specFade.y = EditorGUILayout.Slider("Fade Lenght", AfsSpecFade.vector2Value.y, 0.0f, 100.0f);
            if (EditorGUI.EndChangeCheck())
            {
                AfsSpecFade.vector2Value = specFade;
            }
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();
            GUILayout.Space(4);
            EditorGUILayout.EndVertical();
        }

//	///////////////////////////////////////////////////
//	Layer Culling Settings
        GUILayout.Space(4);
        EditorGUILayout.BeginVertical("Box");
        // Foldout incl. Icon
        EditorGUILayout.BeginHorizontal();
        GUILayout.Space(-2);
        EditorGUI.indentLevel++;
        EditorGUILayout.BeginVertical();
        script.FoldCulling = EditorGUILayout.Foldout(script.FoldCulling, "Layer Culling Settings", myRegularFoldoutStyle);
        EditorGUILayout.EndVertical();
        EditorGUI.indentLevel--;

        if (GUILayout.Button("Help", myMiniHelpBtn, GUILayout.Width(40)))
        {
            Application.OpenURL(baseURL + "h.7u07x8g4ibkg");
        }

        EditorGUILayout.BeginVertical(GUILayout.Width(20));
        // Label needs width!
        EditorGUILayout.LabelField(new GUIContent(icnCulling), GUILayout.Width(20), GUILayout.Height(20));
        EditorGUILayout.EndVertical();
        EditorGUILayout.EndHorizontal();
        // FoldoutContent
        if (script.FoldCulling)
        {
            DrawSplitter(EditorGUILayout.GetControlRect(false, 4), SplitterCol);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(13);
            EditorGUILayout.BeginVertical();
            EditorGUILayout.BeginHorizontal();
            EditorGUI.BeginChangeCheck();
            bool shallEnableCameraLayerCulling = EnableCameraLayerCulling.boolValue;
            shallEnableCameraLayerCulling = EditorGUILayout.Toggle("", shallEnableCameraLayerCulling, GUILayout.Width(14));
            EditorGUILayout.LabelField("Enable Layer Culling");
            if (EditorGUI.EndChangeCheck())
            {
                EnableCameraLayerCulling.boolValue = shallEnableCameraLayerCulling;
                if (!EnableCameraLayerCulling.boolValue)
                {
                    script.afsResetCameraLayerCulling();
                }
            }
            EditorGUILayout.EndHorizontal();
            if (EnableCameraLayerCulling.boolValue)
            {
                GUILayout.Space(4);
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(SmallDetailsDistance, new GUIContent("Small Details Distance"));
                EditorGUILayout.PropertyField(SmallDetailsLayer, new GUIContent("Small Details Layer"));
                GUILayout.Space(4);
                EditorGUILayout.PropertyField(MediumDetailsDistance, new GUIContent("Medium Detail Distance"));
                EditorGUILayout.PropertyField(MediumDetailsLayer, new GUIContent("Medium Details Layer"));
                if (EditorGUI.EndChangeCheck())
                {
                    script.afsSetupCameraLayerCulling();
                }
            }
            GUILayout.Space(4);
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();
        }
        EditorGUILayout.EndVertical();

//	Special Render Settings
        GUILayout.Space(4);
        EditorGUILayout.BeginVertical("Box");
        // Foldout incl. Icon
        EditorGUILayout.BeginHorizontal();
        GUILayout.Space(-2);
        EditorGUI.indentLevel++;
        EditorGUILayout.BeginVertical();
        script.FoldRender = EditorGUILayout.Foldout(script.FoldRender, "Special Render Settings", myRegularFoldoutStyle);
        EditorGUILayout.EndVertical();
        EditorGUI.indentLevel--;

        if (GUILayout.Button("Help", myMiniHelpBtn, GUILayout.Width(40)))
        {
            Application.OpenURL(baseURL + "h.sbfb1qqv5amh");
        }

        EditorGUILayout.BeginVertical(GUILayout.Width(20));
        // Label needs width!
        EditorGUILayout.LabelField(new GUIContent(icnCamera), GUILayout.Width(20), GUILayout.Height(20));
        EditorGUILayout.EndVertical();
        EditorGUILayout.EndHorizontal();
        // FoldoutContent
        if (script.FoldRender)
        {
            DrawSplitter(EditorGUILayout.GetControlRect(false, 4), SplitterCol);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(13);
            EditorGUILayout.BeginVertical();
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.PropertyField(AllGrassObjectsCombined, GUIContent.none, GUILayout.Width(14));
            EditorGUILayout.LabelField("All Grass Objects Combined");
            EditorGUILayout.EndHorizontal();
            GUILayout.Space(4);
            EditorGUILayout.EndVertical();
            EditorGUILayout.EndHorizontal();
        }
        EditorGUILayout.EndVertical();
        GUILayout.Space(4);

        //	Do another check for detail texture atlas
        if (TerrainFoliageNrmSpecMap.objectReferenceValue == null)
        {
            string[] guIDS = AssetDatabase.FindAssets("Afs default Terrain [Normal] [Smoothness] [Trans]");
            if (guIDS.Length > 0)
            {
                TerrainFoliageNrmSpecMap.objectReferenceValue = (Texture2D)AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guIDS[0]), typeof(Texture2D));
            }
        }

//	////////////////////////
        SetupAFS.ApplyModifiedProperties();
    }
        public override void OnInspectorGUI()
        {
            //Debug.Log("OnInspectorGUI Called.");
            Event  evt     = Event.current;
            string evt_cmd = evt.commandName; // Get Current Event CommandName to check for Undo Events

            serializedObject.Update();

            EditorGUIUtility.labelWidth = 135;

            // HEADER
            GUILayout.Label("<b>TextMeshPro - Sprite Asset</b>", TMP_UIStyleManager.Section_Label);


            // TEXTMESHPRO SPRITE INFO PANEL
            GUILayout.Label("Sprite Info", TMP_UIStyleManager.Section_Label);
            EditorGUI.indentLevel = 1;

            GUI.enabled = false; // Lock UI

            EditorGUILayout.PropertyField(m_spriteAtlas_prop, new GUIContent("Sprite Atlas"));

            // SPRITE LIST
            GUI.enabled = true; // Unlock UI
            GUILayout.Space(10);
            EditorGUI.indentLevel = 0;


            if (GUILayout.Button("Sprite List\t\t" + (UI_PanelState.spriteInfoPanel ? uiStateLabel[1] : uiStateLabel[0]), TMP_UIStyleManager.Section_Label))
            {
                UI_PanelState.spriteInfoPanel = !UI_PanelState.spriteInfoPanel;
            }

            if (UI_PanelState.spriteInfoPanel)
            {
                int arraySize    = m_spriteInfoList_prop.arraySize;
                int itemsPerPage = (Screen.height - 292) / 80;

                if (arraySize > 0)
                {
                    // Display each SpriteInfo entry using the SpriteInfo property drawer.
                    for (int i = itemsPerPage * m_page; i < arraySize && i < itemsPerPage * (m_page + 1); i++)
                    {
                        EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label, GUILayout.Height(60));

                        SerializedProperty spriteInfo = m_spriteInfoList_prop.GetArrayElementAtIndex(i);
                        EditorGUI.BeginChangeCheck();
                        EditorGUILayout.PropertyField(spriteInfo);
                        EditorGUILayout.EndVertical();
                    }
                }

                int shiftMultiplier = evt.shift ? 10 : 1; // Page + Shift goes 10 page forward

                Rect pagePos = EditorGUILayout.GetControlRect(false, 20);
                pagePos.width /= 3;

                // Previous Page
                if (m_page > 0)
                {
                    GUI.enabled = true;
                }
                else
                {
                    GUI.enabled = false;
                }

                if (GUI.Button(pagePos, "Previous"))
                {
                    m_page -= 1 * shiftMultiplier;
                }

                // PAGE COUNTER
                GUI.enabled = true;
                pagePos.x  += pagePos.width;
                int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f);
                GUI.Label(pagePos, "Page " + (m_page + 1) + " / " + totalPages, GUI.skin.button);

                // Next Page
                pagePos.x += pagePos.width;
                if (itemsPerPage * (m_page + 1) < arraySize)
                {
                    GUI.enabled = true;
                }
                else
                {
                    GUI.enabled = false;
                }

                if (GUI.Button(pagePos, "Next"))
                {
                    m_page += 1 * shiftMultiplier;
                }

                // Clamp page range
                if (itemsPerPage > 0)
                {
                    m_page = Mathf.Clamp(m_page, 0, arraySize / itemsPerPage);
                }
                else
                {
                    m_page = 0;
                }

                // Global Settings

                EditorGUIUtility.labelWidth = 40f;
                EditorGUIUtility.fieldWidth = 20f;

                GUI.enabled = true;
                EditorGUILayout.BeginVertical(TMP_UIStyleManager.Group_Label);
                Rect rect = EditorGUILayout.GetControlRect(false, 40);

                float width = (rect.width - 75f) / 4;
                EditorGUI.LabelField(rect, "Global Offsets & Scale", EditorStyles.boldLabel);


                rect.x += 70;
                bool old_ChangedState = GUI.changed;

                GUI.changed = false;
                m_xOffset   = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 0, rect.y + 20, width - 5f, 18), new GUIContent("OX:"), m_xOffset);
                if (GUI.changed)
                {
                    UpdateGlobalProperty("xOffset", m_xOffset);
                }

                m_yOffset = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 1, rect.y + 20, width - 5f, 18), new GUIContent("OY:"), m_yOffset);
                if (GUI.changed)
                {
                    UpdateGlobalProperty("yOffset", m_yOffset);
                }

                m_xAdvance = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 2, rect.y + 20, width - 5f, 18), new GUIContent("ADV."), m_xAdvance);
                if (GUI.changed)
                {
                    UpdateGlobalProperty("xAdvance", m_xAdvance);
                }

                m_scale = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 3, rect.y + 20, width - 5f, 18), new GUIContent("SF."), m_scale);
                if (GUI.changed)
                {
                    UpdateGlobalProperty("scale", m_scale);
                }

                EditorGUILayout.EndVertical();

                GUI.changed = old_ChangedState;
            }

            //Rect rect = EditorGUILayout.GetControlRect(false, 20);



            if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty)
            {
                //Debug.Log("Serialized properties have changed.");
                //TMPro_EventManager.ON_FONT_PROPERTY_CHANGED(true, m_fontAsset);

                isAssetDirty = false;
                EditorUtility.SetDirty(target);
                //TMPro_EditorUtility.RepaintAll(); // Consider SetDirty
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Renders the control at the current location in the layout, akin to EditorGUILayout calls.
        /// </summary>
        /// <param name="text">The value to populate in the TextField portion of the control.</param>
        /// <returns>The new value of the text field based on user input in the text field or in the dropdown suggestion list.</returns>
        public string OnGUI(string text)
        {
            const bool isFirstRenderPass = true;

            EnforceRenderPassOrdering(isFirstRenderPass);

            if (Event.current.type == EventType.KeyDown && _isFocused && _cachedSuggestions.Any())
            {
                if (Event.current.keyCode == KeyCode.Return)
                {
                    SetCurrentSelectedIndexToTextField();
                }
                else
                {
                    OnKeyPressed();
                }
            }

            string controlName = _keyFieldNamePrefix + _controlId;

            if (_setSelectedSuggestionToTextField && _cachedSuggestions.Any())
            {
                // When setting the text on the control, in order to get it to render correctly, we must set focus off of it, render it, then set focus back on it again.
                text = _cachedSuggestions[_selectedIndex].Value;
            }

            // Draw the text field
            // Note: We assign a name to the field so we can later check if it is focused
            string newText;

            using (var horizontalScope = new GUILayout.HorizontalScope())
            {
                GUI.SetNextControlName(controlName);
                newText = EditorGUILayout.TextField(_label, text);
            }

            if (Event.current.type == EventType.Repaint)
            {
                // The name of the focused control is not set properly on Layout.  Wait until Repaint to check.
                _isFocused = (GUI.GetNameOfFocusedControl() == controlName);
            }

            if (_setSelectedSuggestionToTextField)
            {
                GUI.FocusControl(controlName);
                _isFocused = true;
                _setSelectedSuggestionToTextField = false;
            }

            if (newText != _textForCachedSuggestions ||
                _isFocused != _focusedForCachedSuggestions ||
                ThreadSafeCacheInvalid)
            {
                if (Event.current.type == EventType.Layout)
                {
                    _textForCachedSuggestions    = newText;
                    _focusedForCachedSuggestions = _isFocused;
                    ThreadSafeCacheInvalid       = false;

                    var suggestions = _suggestionProvider.GetSuggestions(newText, _isFocused);
                    _cachedSuggestions = (suggestions != null) ? suggestions.ToList() : new List <Suggestion>();
                    _selectedIndex     = 0;
                    _scrolledIndex     = 0;
                }
                else
                {
                    EditorWindow.focusedWindow?.Repaint();
                }
            }

            // Capture the position of the text field for later rendering of the drop-down
            _textFieldPosition = EditorGUILayout.GetControlRect(false, 0);

            // Draw the auto-suggestion overlay.
            DrawAutoSuggestionOverlay(_textFieldPosition, isFirstRenderPass);

            return(newText);
        }
        /// <summary>
        /// Call this from OnInspectorGUI.  Will draw the asset reference field, and
        /// the embedded editor, or a Create Asset button, if no asset is set.
        /// </summary>
        public void DrawEditorCombo(
            string title, string defaultName, string extension, string message,
            string showLabel, bool indent)
        {
            SerializedProperty property = m_Owner.serializedObject.FindProperty(m_PropertyName);

            if (m_Editor == null)
            {
                UpdateEditor();
            }
            if (m_Editor == null)
            {
                AssetFieldWithCreateButton(property, title, defaultName, extension, message);
            }
            else
            {
                EditorGUILayout.BeginVertical(GUI.skin.box);
                Rect rect = EditorGUILayout.GetControlRect(true);
                rect.height = EditorGUIUtility.singleLineHeight;
                EditorGUI.BeginChangeCheck();
                EditorGUI.PropertyField(rect, property);
                if (EditorGUI.EndChangeCheck())
                {
                    m_Owner.serializedObject.ApplyModifiedProperties();
                    UpdateEditor();
                }
                if (m_Editor != null)
                {
                    Rect foldoutRect = new Rect(
                        rect.x - kIndentOffset, rect.y, rect.width + kIndentOffset, rect.height);
                    property.isExpanded = EditorGUI.Foldout(
                        foldoutRect, property.isExpanded, GUIContent.none);

                    UnityEditor.VersionControl.Asset targetAsset
                        = UnityEditor.VersionControl.Provider.GetAssetByPath(
                              AssetDatabase.GetAssetPath(m_Editor.target));
                    bool isLockedFile = m_DoVersionControlChecks &&
                                        !targetAsset.IsOneOfStates(new[] {
                        UnityEditor.VersionControl.Asset.States.CheckedOutLocal,
                        UnityEditor.VersionControl.Asset.States.AddedLocal,
                    });

                    GUI.enabled = !isLockedFile;
                    if (property.isExpanded)
                    {
                        EditorGUILayout.Separator();
                        EditorGUILayout.HelpBox(
                            "This is a shared asset.  Changes made here will apply to all users of this asset.",
                            MessageType.Info);
                        EditorGUI.BeginChangeCheck();
                        if (indent)
                        {
                            ++EditorGUI.indentLevel;
                        }
                        m_Editor.OnInspectorGUI();
                        if (indent)
                        {
                            --EditorGUI.indentLevel;
                        }
                        if (EditorGUI.EndChangeCheck() && (OnChanged != null))
                        {
                            OnChanged(property.objectReferenceValue as T);
                        }
                    }
                    GUI.enabled = true;
                    if (isLockedFile && GUILayout.Button("Check out"))
                    {
                        UnityEditor.VersionControl.Provider.Checkout(
                            targetAsset, UnityEditor.VersionControl.CheckoutMode.Both);
                    }
                }
                EditorGUILayout.EndVertical();
            }
        }
Esempio n. 15
0
        public override void OnInspectorGUI()
        {
            if (target == null || serializedObject == null)
            {
                return;
            }

            serializedObject.Update();

            var  script = target as PoseEaser;
            Rect layoutRect;

            GUI.enabled = false;
            EditorGUILayout.PropertyField(scriptProp);
            GUI.enabled = true;

            EditorGUI.BeginChangeCheck();

            EditorGUILayout.PropertyField(priorityProp);
            EditorGUILayout.PropertyField(durationProp);

            var fieldWidth = (EditorGUIUtility.currentViewWidth - EditorGUIUtility.labelWidth) / 3f;

            // ease position
            layoutRect = EditorGUILayout.GetControlRect();

            layoutRect.width = EditorGUIUtility.labelWidth;
            EditorGUI.LabelField(layoutRect, "Ease Position");
            layoutRect.x += layoutRect.width;

            layoutRect.width     = fieldWidth;
            script.easePositionX = EditorGUI.ToggleLeft(layoutRect, "X", script.easePositionX);
            layoutRect.x        += layoutRect.width;

            layoutRect.width     = fieldWidth;
            script.easePositionY = EditorGUI.ToggleLeft(layoutRect, "Y", script.easePositionY);
            layoutRect.x        += layoutRect.width;

            layoutRect.width     = fieldWidth;
            script.easePositionZ = EditorGUI.ToggleLeft(layoutRect, "Z", script.easePositionZ);

            // ease rotation
            layoutRect = EditorGUILayout.GetControlRect();

            layoutRect.width = EditorGUIUtility.labelWidth;
            EditorGUI.LabelField(layoutRect, "Ease Rotation");
            layoutRect.x += layoutRect.width;

            layoutRect.width     = fieldWidth;
            script.easeRotationX = EditorGUI.ToggleLeft(layoutRect, "X", script.easeRotationX);
            layoutRect.x        += layoutRect.width;

            layoutRect.width     = fieldWidth;
            script.easeRotationY = EditorGUI.ToggleLeft(layoutRect, "Y", script.easeRotationY);
            layoutRect.x        += layoutRect.width;

            layoutRect.width     = fieldWidth;
            script.easeRotationZ = EditorGUI.ToggleLeft(layoutRect, "Z", script.easeRotationZ);

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(target, "Pose Easer Changed");
            }

            serializedObject.ApplyModifiedProperties();
        }
        public override void OnInspectorGUI()
        {
            if (anchoredPanelGUIStyle == null)
            {
                anchoredPanelGUIStyle = new GUIStyle("box")
                {
                    alignment = TextAnchor.MiddleCenter,
                    clipping  = TextClipping.Clip
                };
            }

            if (justClickedAnchoredPanel != null && Event.current.type == EventType.Layout)
            {
                selectedAnchoredPanel     = justClickedAnchoredPanel;
                selectedAnchoredPanelTabs = selectedAnchoredPanel.panel.tabs;

                justClickedAnchoredPanel = null;
            }

            serializedObject.Update();
            reorderableListIndex = 0;

            bool multiObjectEditing = targets.Length > 1;
            bool guiEnabled         = !EditorApplication.isPlaying || AssetDatabase.Contains(((DynamicPanelsCanvas)serializedObject.targetObject).gameObject);

            GUI.enabled = guiEnabled;
            GUILayout.BeginVertical();

            EditorGUILayout.LabelField("= Properties =", EditorStyles.boldLabel);
            EditorGUILayout.PropertyField(leaveFreeSpace);
            EditorGUI.indentLevel++;
            GUI.enabled = guiEnabled && leaveFreeSpace.boolValue;
            EditorGUILayout.PropertyField(minimumFreeSpace);
            GUI.enabled = guiEnabled;
            EditorGUI.indentLevel--;
            EditorGUILayout.PropertyField(preventDetachingLastDockedPanel);
            EditorGUILayout.PropertyField(panelResizableAreaLength);
            EditorGUILayout.PropertyField(canvasAnchorZoneLength);
            EditorGUILayout.PropertyField(panelAnchorZoneLength);

            GUILayout.Space(10f);

            EditorGUILayout.LabelField("= Free Panels =", EditorStyles.boldLabel);
            if (multiObjectEditing)
            {
                GUILayout.Label("Multi-object editing not supported");
            }
            else if (!guiEnabled)
            {
                GUILayout.Label("Can't edit in Play mode");
            }
            else
            {
                List <DynamicPanelsCanvas.PanelProperties> initialPanelsUnanchored = settings.InitialPanelsUnanchored;
                int selectedReorderableListIndex = -1;
                for (int i = 0; i < initialPanelsUnanchored.Count; i++)
                {
                    if (DrawReorderableListFor(initialPanelsUnanchored[i]))
                    {
                        selectedReorderableListIndex = i;
                    }

                    if (i < initialPanelsUnanchored.Count - 1)
                    {
                        // Draw a horizontal line to separate the panels
                        GUILayout.Space(5f);
                        GUILayout.Box(GUIContent.none, GUILayout.ExpandWidth(true), GUILayout.Height(2f));
                    }

                    GUILayout.Space(5f);
                }

                GUILayout.BeginHorizontal();

                if (GUILayout.Button("Add New", GUILayout.Height(1.35f * EditorGUIUtility.singleLineHeight)))
                {
                    Undo.IncrementCurrentGroup();
                    Undo.RecordObject((DynamicPanelsCanvas)target, "Add Free Panel");

                    initialPanelsUnanchored.Add(new DynamicPanelsCanvas.PanelProperties());
                }

                if (selectedReorderableListIndex < 0)
                {
                    GUI.enabled = false;
                }

                if (GUILayout.Button("Remove Selected", GUILayout.Height(1.35f * EditorGUIUtility.singleLineHeight)))
                {
                    Undo.IncrementCurrentGroup();
                    Undo.RecordObject((DynamicPanelsCanvas)target, "Remove Free Panel");

                    initialPanelsUnanchored.RemoveAt(selectedReorderableListIndex);
                }

                GUI.enabled = guiEnabled;

                GUILayout.EndHorizontal();
            }

            GUILayout.Space(13f);

            EditorGUILayout.LabelField("= Docked Panels =", EditorStyles.boldLabel);
            if (multiObjectEditing)
            {
                GUILayout.Label("Multi-object editing not supported");
            }
            else if (!guiEnabled)
            {
                GUILayout.Label("Can't edit in Play mode");
            }
            else
            {
                DynamicPanelsCanvas.AnchoredPanelProperties initialPanelsAnchored = settings.InitialPanelsAnchored;

                Rect previewRect = EditorGUILayout.GetControlRect(false, ANCHORED_PANELS_PREVIEW_HEIGHT);
                DrawAnchoredPanelsPreview(previewRect, initialPanelsAnchored);

                if (selectedAnchoredPanel != null)
                {
                    GUILayout.BeginVertical(EditorStyles.helpBox);
                    GUILayout.Space(5f);
                    EditorGUILayout.LabelField("Selected panel:", EditorStyles.boldLabel);

                    if (selectedAnchoredPanelTabs != settings.InitialPanelsAnchored.panel.tabs)
                    {
                        string initialSizeLabel = selectedAnchoredPanel.initialSize == Vector2.zero ? "Initial Size (not set):" : "Initial Size:";

                        EditorGUI.BeginChangeCheck();
                        Vector2 panelInitialSize = EditorGUILayout.Vector2Field(initialSizeLabel, selectedAnchoredPanel.initialSize);
                        if (EditorGUI.EndChangeCheck())
                        {
                            Undo.RecordObject((DynamicPanelsCanvas)target, "Change Initial Size");
                            selectedAnchoredPanel.initialSize = panelInitialSize;
                        }

                        DrawReorderableListFor(selectedAnchoredPanel.panel);
                    }
                    else
                    {
                        GUILayout.Label("- nothing -");
                    }

                    Direction direction = ShowDirectionButtons("Dock new panel inside: ");
                    if (direction != Direction.None)
                    {
                        Undo.IncrementCurrentGroup();
                        Undo.RecordObject((DynamicPanelsCanvas)target, "Dock New Panel");

                        selectedAnchoredPanel.subPanels.Add(new DynamicPanelsCanvas.AnchoredPanelProperties()
                        {
                            anchorDirection = direction
                        });
                    }

                    if (selectedAnchoredPanelTabs != settings.InitialPanelsAnchored.panel.tabs)
                    {
                        GUILayout.Space(5f);
                        if (GUILayout.Button("Remove Selected", GUILayout.Height(1.35f * EditorGUIUtility.singleLineHeight)))
                        {
                            RemoveAnchoredPanel(settings.InitialPanelsAnchored, selectedAnchoredPanel);
                        }
                    }

                    GUILayout.EndVertical();
                }

                GUILayout.Space(6f);

                Direction rootDirection = ShowDirectionButtons("Dock new panel to canvas: ");
                if (rootDirection != Direction.None)
                {
                    Undo.IncrementCurrentGroup();
                    Undo.RecordObject((DynamicPanelsCanvas)target, "Dock New Panel");

                    settings.InitialPanelsAnchored.subPanels.Insert(0, new DynamicPanelsCanvas.AnchoredPanelProperties()
                    {
                        anchorDirection = rootDirection
                    });
                }
            }

            GUI.enabled = true;
            GUILayout.EndVertical();

            serializedObject.ApplyModifiedProperties();
        }
Esempio n. 17
0
        public override void OnInspectorGUI()
        {
            if (CanvasScalerEditor.s_Styles == null)
            {
                CanvasScalerEditor.s_Styles = new CanvasScalerEditor.Styles();
            }
            bool flag1 = true;
            bool flag2 = false;
            bool flag3 = (this.target as CanvasScaler).GetComponent <Canvas>().renderMode == UnityEngine.RenderMode.WorldSpace;

            for (int index = 0; index < this.targets.Length; ++index)
            {
                Canvas component = (this.targets[index] as CanvasScaler).GetComponent <Canvas>();
                if (!component.isRootCanvas)
                {
                    flag1 = false;
                    break;
                }
                if (flag3 && component.renderMode != UnityEngine.RenderMode.WorldSpace || !flag3 && component.renderMode == UnityEngine.RenderMode.WorldSpace)
                {
                    flag2 = true;
                    break;
                }
            }
            if (!flag1)
            {
                EditorGUILayout.HelpBox("Non-root Canvases will not be scaled.", MessageType.Warning);
            }
            else
            {
                this.serializedObject.Update();
                EditorGUI.showMixedValue = flag2;
                EditorGUI.BeginDisabledGroup(flag3 || flag2);
                if (flag3 || flag2)
                {
                    EditorGUILayout.Popup(CanvasScalerEditor.s_Styles.uiScaleModeContent.text, 0, new string[1] {
                        "World"
                    }, new GUILayoutOption[0]);
                }
                else
                {
                    EditorGUILayout.PropertyField(this.m_UiScaleMode, CanvasScalerEditor.s_Styles.uiScaleModeContent, new GUILayoutOption[0]);
                }
                EditorGUI.EndDisabledGroup();
                EditorGUI.showMixedValue = false;
                if (!flag2 && (flag3 || !this.m_UiScaleMode.hasMultipleDifferentValues))
                {
                    EditorGUILayout.Space();
                    if (flag3)
                    {
                        EditorGUILayout.PropertyField(this.m_DynamicPixelsPerUnit);
                    }
                    else if (this.m_UiScaleMode.enumValueIndex == 0)
                    {
                        EditorGUILayout.PropertyField(this.m_ScaleFactor);
                    }
                    else if (this.m_UiScaleMode.enumValueIndex == 1)
                    {
                        EditorGUILayout.PropertyField(this.m_ReferenceResolution);
                        EditorGUILayout.PropertyField(this.m_ScreenMatchMode);
                        if (this.m_ScreenMatchMode.enumValueIndex == 0 && !this.m_ScreenMatchMode.hasMultipleDifferentValues)
                        {
                            CanvasScalerEditor.DualLabeledSlider(EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight + 12f, new GUILayoutOption[0]), this.m_MatchWidthOrHeight, CanvasScalerEditor.s_Styles.matchContent, CanvasScalerEditor.s_Styles.widthContent, CanvasScalerEditor.s_Styles.heightContent);
                        }
                    }
                    else if (this.m_UiScaleMode.enumValueIndex == 2)
                    {
                        EditorGUILayout.PropertyField(this.m_PhysicalUnit);
                        EditorGUILayout.PropertyField(this.m_FallbackScreenDPI);
                        EditorGUILayout.PropertyField(this.m_DefaultSpriteDPI);
                    }
                    EditorGUILayout.PropertyField(this.m_ReferencePixelsPerUnit);
                }
                this.serializedObject.ApplyModifiedProperties();
            }
        }
Esempio n. 18
0
        public override void OnInspectorGUI()
        {
            var instance = serializedObject.targetObject as WebCamPlayer;

            EditorGUILayout.Space();

            //Source
            EditorGUILayout.PropertyField(_sourceModeProperty);

            var sourceMode = (WebCamPlayer.SourceMode)_sourceModeProperty.enumValueIndex;

            _showSourceWebCamStreamProperty.target = (!_sourceModeProperty.hasMultipleDifferentValues && sourceMode == WebCamPlayer.SourceMode.WebCamStream);

            ++EditorGUI.indentLevel;
            {
                if (EditorGUILayout.BeginFadeGroup(_showSourceWebCamStreamProperty.faded))
                {
                    EditorGUILayout.PropertyField(_sourceWebCamStreamProperty);
                }
                EditorGUILayout.EndFadeGroup();
            }
            --EditorGUI.indentLevel;

            //Render
            EditorGUILayout.PropertyField(_renderModeProperty);

            var renderMode = (WebCamPlayer.RenderMode)_renderModeProperty.enumValueIndex;

            _showTargetTexture.target = (!_renderModeProperty.hasMultipleDifferentValues && renderMode == WebCamPlayer.RenderMode.RenderTexture);
            _showRenderer.target      = (!_renderModeProperty.hasMultipleDifferentValues && renderMode == WebCamPlayer.RenderMode.MaterialOverride);

            ++EditorGUI.indentLevel;
            {
                if (EditorGUILayout.BeginFadeGroup(_showTargetTexture.faded))
                {
                    EditorGUILayout.PropertyField(_targetTextureProperty);
                }
                EditorGUILayout.EndFadeGroup();

                if (EditorGUILayout.BeginFadeGroup(_showRenderer.faded))
                {
                    var renderer = _targetRendererProperty.objectReferenceValue as Renderer;
                    if (renderer == null)
                    {
                        renderer = (target as WebCamPlayer).GetComponent <Renderer>();
                        _targetRendererProperty.objectReferenceValue = renderer;
                    }
                    EditorGUILayout.PropertyField(_targetRendererProperty);
                }
                EditorGUILayout.EndFadeGroup();
            }
            --EditorGUI.indentLevel;

            EditorGUI.BeginDisabledGroup(EditorApplication.isPlaying);
            {
                EditorGUILayout.PropertyField(_playOnAwakeProperty);
            }
            EditorGUI.EndDisabledGroup();

            //Buttons
            bool isEnablePlayButton = EditorApplication.isPlaying && !instance.isPlaying;
            bool isEnableStopButton = EditorApplication.isPlaying && instance.isPlaying;

            var  rect       = EditorGUILayout.GetControlRect();
            Rect buttonRect = rect;

            EditorGUI.BeginDisabledGroup(!isEnablePlayButton);
            {
                buttonRect.xMin = rect.xMin;
                buttonRect.xMax = rect.width * 0.5f;
                if (GUI.Button(buttonRect, "Play", EditorStyles.miniButtonLeft))
                {
                    instance.Play();
                }
            }
            EditorGUI.EndDisabledGroup();
            EditorGUI.BeginDisabledGroup(!isEnableStopButton);
            {
                buttonRect.xMin  = buttonRect.xMax;
                buttonRect.xMax += rect.width * 0.5f;
                if (GUI.Button(buttonRect, "Stop", EditorStyles.miniButtonRight))
                {
                    instance.Stop();
                }
            }
            EditorGUI.EndDisabledGroup();

            EditorGUILayout.Space();

            //Setters
            if (EditorApplication.isPlaying)
            {
                if (instance.sourceMode != (WebCamPlayer.SourceMode)_sourceModeProperty.enumValueIndex)
                {
                    instance.sourceMode = (WebCamPlayer.SourceMode)_sourceModeProperty.enumValueIndex;
                }
                if (instance.sourceWebCamStream != _sourceWebCamStreamProperty.objectReferenceValue)
                {
                    instance.sourceWebCamStream = _sourceWebCamStreamProperty.objectReferenceValue as WebCamStream;
                }
                if (instance.renderMode != (WebCamPlayer.RenderMode)_renderModeProperty.enumValueIndex)
                {
                    instance.renderMode = (WebCamPlayer.RenderMode)_renderModeProperty.enumValueIndex;
                }
                if (instance.targetRenderer != _targetRendererProperty.objectReferenceValue)
                {
                    instance.targetRenderer = _targetRendererProperty.objectReferenceValue as Renderer;
                }
                if (instance.targetTexture != _targetTextureProperty.objectReferenceValue)
                {
                    instance.targetTexture = _targetTextureProperty.objectReferenceValue as RenderTexture;
                }
            }

            serializedObject.ApplyModifiedProperties();
        }
Esempio n. 19
0
        protected sealed override void Editor_OnInspectorGUI()
        {
            // Edit Button

            _rect       = EditorGUILayout.GetControlRect(true, _editButtonHeight);
            _rect.x    += EditorGUIUtility.labelWidth;
            _rect.width = _editButtonWidth;

            EditorGUI.BeginChangeCheck();
            EditorKit.RecordAndSetGUIContentColor(EditorKit.defaultContentColor);
            bool edit = GUI.Toggle(_rect, _currentEditing == this, EditorAssets.editTexture, EditorKit.buttonStyle);

            EditorKit.RestoreGUIContentColor();
            if (EditorGUI.EndChangeCheck())
            {
                SetCurrentEditing(edit ? this : null);
            }

            // Edit Label

            _rect.x     = _rect.xMax + _horizontalInterval;
            _rect.width = 128f;
            EditorGUI.LabelField(_rect, "Edit Path", middleLeftLabel);

            // Circular

            editor.DrawToggleLayout(circular, value => circular = value, "Circular");

            // World Scale

            EditorGUI.BeginChangeCheck();
            float scale = EditorGUILayout.FloatField(_worldScaleContent, worldScale);

            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(this, editor.undoString);
                worldScale = scale;
                EditorUtility.SetDirty(this);
            }

            // Length Error

            editor.DrawFloatFieldLayout(lengthError, value => lengthError = value, "Length Error");

            // Length

            if (isSamplesValid)
            {
                EditorGUILayout.FloatField("Length", length);
            }
            else
            {
                _rect = EditorGUILayout.GetControlRect();
                EditorGUI.LabelField(_rect, "Length");
                _rect.xMin += EditorGUIUtility.labelWidth;

                // Calculate Button

                if (GUI.Button(_rect, "Calculate", EditorStyles.miniButton))
                {
                    Undo.RecordObject(this, editor.undoString);
                    ValidateSamples();
                    EditorUtility.SetDirty(this);
                }
            }

            // Always Visible Button
            _alwaysVisible = EditorKit.IndentedToggle("Always Visible", _alwaysVisible);
        }
Esempio n. 20
0
    public override void OnInspectorGUI()
    {
        Font defaultFont = EditorStyles.label.font;

        serializedObject.Update();
        SerializedProperty assetProp = serializedObject.FindProperty("overrideAsset");

        EditorGUILayout.PropertyField(assetProp, new GUIContent("Override Asset"));

        MaterialOverride overrideComponent = (target as MaterialOverride);

        if (overrideComponent != null)
        {
            MaterialOverrideAsset overrideAsset = overrideComponent.overrideAsset;
            if (overrideAsset != null)
            {
                SerializedProperty overrideListProp = serializedObject.FindProperty("overrideList");
                for (int i = 0; i < overrideListProp.arraySize; i++)
                {
                    SerializedProperty overrideProp = overrideListProp.GetArrayElementAtIndex(i);
                    string             displayName  = overrideProp.FindPropertyRelative("displayName").stringValue;
                    ShaderPropertyType type         = (ShaderPropertyType)overrideProp.FindPropertyRelative("type").intValue;
                    SerializedProperty instanceProp = overrideProp.FindPropertyRelative("instanceOverride");

                    Rect fieldRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight);
                    GUI.skin.font = defaultFont;
                    if (instanceProp.boolValue)
                    {
                        DrawOverrideMargin(fieldRect);
                        GUI.skin.font = EditorStyles.boldFont;
                    }

                    EditorGUI.BeginChangeCheck();
                    if (type == ShaderPropertyType.Color)
                    {
                        SerializedProperty colorProp = overrideProp.FindPropertyRelative("value");

                        Color   color    = new Color(colorProp.vector4Value.x, colorProp.vector4Value.y, colorProp.vector4Value.z, colorProp.vector4Value.w);
                        Color   newColor = EditorGUI.ColorField(fieldRect, new GUIContent(displayName), color);
                        Vector4 vec4     = new Vector4(newColor.r, newColor.g, newColor.b, newColor.a);
                        colorProp.vector4Value = vec4;
                    }
                    else if (type == ShaderPropertyType.Vector)
                    {
                        SerializedProperty vector4Prop = overrideProp.FindPropertyRelative("value");

                        Vector4 vec4    = vector4Prop.vector4Value;
                        Vector4 newVec4 = EditorGUI.Vector4Field(fieldRect, new GUIContent(displayName), vec4);
                        vector4Prop.vector4Value = newVec4;
                    }
                    else if (type == ShaderPropertyType.Float || type == ShaderPropertyType.Range)
                    {
                        SerializedProperty floatProp = overrideProp.FindPropertyRelative("value");

                        float f    = floatProp.vector4Value.x;
                        float newF = EditorGUI.FloatField(fieldRect, new GUIContent(displayName), f);
                        floatProp.vector4Value = new Vector4(newF, 0.0f, 0.0f, 0.0f);
                    }
                    else
                    {
                        Debug.Log("Property " + displayName + " is of unsupported type " + type + " for material override.");
                    }
                    if (EditorGUI.EndChangeCheck())
                    {
                        instanceProp.boolValue = true;
                    }


                    if (instanceProp.boolValue)
                    {
                        if (fieldRect.Contains(Event.current.mousePosition) && Event.current.type == EventType.ContextClick)
                        {
                            GenericMenu menu = new GenericMenu();
                            menu.AddItem(new GUIContent("Apply to MaterialOverride '" + overrideComponent.overrideAsset.name + "'"),
                                         false, ApplyToOverrideAsset, i);
                            menu.AddItem(new GUIContent("Revert"), false, RevertGameobjectOverride, i);
                            menu.ShowAsContext();
                            Event.current.Use();
                        }
                    }
                }
            }
        }
        serializedObject.ApplyModifiedProperties();
    }
 public static void Draw(SerializedProperty property, GUIContent label)
 {
     Draw(EditorGUILayout.GetControlRect(), property, label);
 }
Esempio n. 22
0
        /// <summary>
        /// 画横线 支持进度条
        /// </summary>
        /// <param name="height"></param>
        /// <param name="color"></param>
        /// <param name="progress"></param>
        public static void HLine(float height, Color color, float progress = 1.0f)
        {
            var rect = EditorGUILayout.GetControlRect(false, height);

            EditorGUI.DrawRect(new Rect(rect.x, rect.y, rect.width * progress, rect.height), color);
        }
            void DrawProperty(int materialCount)
            {
                var rect = EditorGUILayout.GetControlRect();
                rect = EditorGUI.PrefixLabel(rect, EditorGUIKit.TempContent("Property"));

                if (!string.IsNullOrEmpty(target.propertyName))
                {
                    _builder.Append(target.propertyName);
                    _builder.Append(" (");
                    _builder.Append(target._propertyType);
                    _builder.Append(')');
                }

                if (GUI.Button(rect, _builder.ToString(), EditorStyles.layerMaskField))
                {
                    var properties = new HashSet<Property>();
                    var menu = new GenericMenu();

                    for (int i = 0; i < materialCount; i++)
                    {
                        if (target.IsMaterialSelected(i) && _materials[i] && _materials[i].shader)
                        {
                            var shader = _materials[i].shader;
                            int count = ShaderUtil.GetPropertyCount(shader);

                            for (int idx = 0; idx < count; idx++)
                            {
                                if (!ShaderUtil.IsShaderPropertyHidden(shader, idx))
                                {
                                    var prop = new Property
                                    {
                                        name = ShaderUtil.GetPropertyName(shader, idx),
                                        type = ShaderUtil.GetPropertyType(shader, idx)
                                    };

                                    if (properties.Contains(prop)) continue;
                                    properties.Add(prop);

                                    string description = ShaderUtil.GetPropertyDescription(shader, idx);

                                    if (prop.type == ShaderUtil.ShaderPropertyType.TexEnv)
                                    {
                                        prop.name += "_ST";
                                        prop.type = ShaderUtil.ShaderPropertyType.Vector;
                                        description += " Scale and Offest";
                                    }

                                    _builder.Clear();
                                    _builder.Append(prop.name);
                                    _builder.Append(" (\"");
                                    _builder.Append(description);
                                    _builder.Append("\", ");
                                    _builder.Append(prop.type);
                                    _builder.Append(')');

                                    menu.AddItem(new GUIContent(_builder.ToString()),
                                        target._propertyName == prop.name && target._propertyType == (Type)(int)prop.type,
                                        () =>
                                        {
                                            Undo.RecordObject(target, "Select Property");
                                            Type oldType = target.propertyType;
                                            target.SetProperty(prop.name, (Type)(int)prop.type);

                                            if (oldType != target.propertyType)
                                            {
                                                if (target.propertyType == Type.Color)
                                                    target._from = target._to = Color.white;

                                                if (target.propertyType == Type.Float || target.propertyType == Type.Range)
                                                    target._from.x = target._to.x = 1f;

                                                if (target.propertyType == Type.Vector)
                                                {
                                                    if (prop.name.EndsWith("_ST"))
                                                        target._from = target._to = new Vector4(1, 1, 0, 0);
                                                    else
                                                        target._from = target._to = new Vector4(1, 1, 1, 1);
                                                }
                                            }
                                        });

                                    _builder.Clear();
                                }
                            }
                        }
                    }

                    if (properties.Count == 0) menu.AddItem(new GUIContent("(No Valid Property)"), false, () => { });

                    menu.DropDown(rect);
                }

                _builder.Clear();
            }
Esempio n. 24
0
        public void OnInspectorGUI(Rect rect, bool drawInInspector = false)
        {
            if (m_Target == null)
            {
                return;
            }

#if UNITY_2018_3
            rect = new Rect(rect.x, rect.y + 25, rect.width, rect.height);
#endif

            serializedObject.UpdateIfRequiredOrScript();

            bool userHeader = manager.toolbarInt == 0;
            var  headerRect = GetContentRect(
                new Rect(kPadding, rect.y, rect.width - kPadding, kPadding),
                0f,
                0f
                );

            if (userHeader)
            {
                headerRect = GetContentRect(
                    new Rect(kPadding, rect.y + kToolbarHeight + kPadding, rect.width - kPadding, kHeaderHeight),
                    kPadding,
                    kPadding
                    );
            }

            var bodyRect = GetContentRect(
                new Rect(kPadding, headerRect.yMax, rect.width - kPadding, rect.height - headerRect.height),
                kPadding,
                kPadding
                );

            var viewRect = GetContentRect(
                new Rect(rect.x, rect.y, rect.width,
                         headerRect.height + m_ReorderableList.GetHeight() + kSlotSize),
                kPadding * -1,
                kPadding
                );

            if (drawInInspector)
            {
                m_ScrollViewStart = GUI.BeginScrollView(rect, m_ScrollViewStart, viewRect, false, false);
            }

            var toolBaRect = new Rect(rect.x, rect.y, rect.width, kToolbarHeight);
            manager.toolbarInt = GUI.Toolbar(toolBaRect, manager.toolbarInt, toolbarStrings);

            var headerMsgStyle = GUI.skin.GetStyle("HelpBox");
            headerMsgStyle.alignment = TextAnchor.UpperCenter;
            headerMsgStyle.fontSize  = 10;
            headerMsgStyle.wordWrap  = true;


            if (manager.toolbarInt == 0)
            {
                DrawHeader(headerRect, infoStringAndroid, headerMsgStyle);

                m_ReorderableList.DoList(bodyRect);
                if (!drawInInspector)
                {
                    EditorGUILayout.GetControlRect(true, headerRect.height + m_ReorderableList.GetHeight() + kSlotSize);
                }
            }
            else
            {
                var settingsPanelRect = bodyRect;                //GetContentRect(rect, kPadding, kPadding);

                var settings = manager.iOSNotificationEditorSettings;
                if (settings == null)
                {
                    return;
                }

                var settingsFlat = settings.Where(s => s is NotificationEditorSetting).Cast <NotificationEditorSetting>().ToList();

                var styleToggle = new GUIStyle(GUI.skin.GetStyle("Toggle"));
                styleToggle.alignment = TextAnchor.MiddleRight;

                var styleDropwDown = new GUIStyle(GUI.skin.GetStyle("Button"));
                styleDropwDown.fixedWidth = kSlotSize * 2.5f;

                GUI.BeginGroup(settingsPanelRect);
                DrawSettingsElementList(settings, false, styleToggle, styleDropwDown, settingsPanelRect);
                GUI.EndGroup();
            }
            if (drawInInspector)
            {
                GUI.EndScrollView();
            }
        }
Esempio n. 25
0
        public static void Icon(Texture texture, float size)
        {
            var rect = EditorGUILayout.GetControlRect(false, size, GUILayout.Width(size));

            GUI.DrawTexture(rect, texture);
        }
Esempio n. 26
0
        void OnGUI()
        {
            // show processing options. some of them are editable while running.
            GUILayout.Label("Duplicate frame remover (MJPEG/PCM AVI remux)", EditorStyles.boldLabel);

            if (!running)
            {
                srcPath      = MpEditorUtil.OpenFileField(srcPath, "Source path", "Source file");
                dstPath      = MpEditorUtil.SaveFileField(dstPath, "Destination path", "Destination file");
                discardAudio = EditorGUILayout.Toggle("Discard audio", discardAudio);
            }
            else
            {
                EditorGUILayout.LabelField("Source path", srcPath);
                EditorGUILayout.LabelField("Destination path", dstPath);
                EditorGUILayout.LabelField("Discard audio", discardAudio ? "true" : "false");
            }
            options.maxLookbackFrames = EditorGUILayout.IntField("Max lookback frames", options.maxLookbackFrames);

            // advances procession options
            advancedSettingsFoldout = EditorGUILayout.Foldout(advancedSettingsFoldout, "Advanced settings");
            if (advancedSettingsFoldout)
            {
                options.maxImageDiff        = EditorGUILayout.Slider("  Max image diff", options.maxImageDiff, 0, MAX_IMAGE_DIFF);
                options.maxPixelDiff        = EditorGUILayout.IntSlider("  Max pixel diff", options.maxPixelDiff, 0, MAX_PIXEL_DIFF);
                options.toneCompareDistrust = EditorGUILayout.IntSlider("  Tone compare distrust", options.toneCompareDistrust, 0, MAX_TONE_COMPARE_DISTRUST);
                if (!running)
                {
                    options.pixelCacheSize = EditorGUILayout.IntField("  Pixel cache size", options.pixelCacheSize);
                    EditorGUILayout.LabelField(" ", (int)(3.69f * options.pixelCacheSize) + "Mb (720p estimate)");
                    if (options.pixelCacheSize < options.maxLookbackFrames || options.pixelCacheSize > 1000)
                    {
                        EditorGUILayout.HelpBox("For optimal performance, pixel cache should be larger than \"max lookback frames\"," +
                                                "but if it's too large, you may get out of memory errors", MessageType.Warning);
                    }

                    logDuplicatesPath = MpEditorUtil.SaveFileField(logDuplicatesPath, "  Log duplicates to file", "Log duplicates to file");
                }
                else
                {
                    int pixelCacheMb = movie.demux.videoStreamInfo.width * movie.demux.videoStreamInfo.height * 4 * options.pixelCacheSize / 1000000;
                    EditorGUILayout.LabelField("  Pixel cache size", options.pixelCacheSize.ToString() + " (" + pixelCacheMb + "Mb)");
                    EditorGUILayout.LabelField("  Log duplicates to file", logDuplicatesPath);
                }
            }

            // controls
            if (!running)
            {
                GUI.enabled = File.Exists(srcPath) && !string.IsNullOrEmpty(dstPath);
                if (GUILayout.Button("Process file"))
                {
                    running = true;
                    if (File.Exists(dstPath))
                    {
                        running = EditorUtility.DisplayDialog("File exists. Overwrite?", dstPath, "Yes", "No");
                    }
                    if (running)
                    {
                        File.WriteAllText(dstPath, "");                          // just empty the file
                        StartProcessing();
                        Debug.Log("AVI remux started");
                    }
                }
                GUI.enabled = true;
            }
            else
            {
                if (GUILayout.Button("Stop"))
                {
                    StopProcessing();
                    Debug.Log("AVI remux stopped");
                    running = false;
                }
            }

            // if we have a duplicate finder (we're not necessarily running), then show progress and stats
            if (dupFinder != null)
            {
                // progress bar
                string progressStr = dupFinder.framesProcessed + "/" + (float)movie.demux.videoStreamInfo.frameCount;

                                #if (UNITY_4_0 || UNITY_4_1 || UNITY_4_2)
                EditorGUILayout.LabelField("Progress", progressStr);
                                #else
                float progress = (float)dupFinder.framesProcessed / (float)movie.demux.videoStreamInfo.frameCount;
                var   rect     = EditorGUILayout.GetControlRect();
                EditorGUI.ProgressBar(rect, progress, progressStr);
                                #endif

                // duplicates found so far
                EditorGUILayout.LabelField("Duplicates found", dupFinder.stats.duplicateCount.ToString());

                // love preview and stats foldout
                livePreviewFoldout = EditorGUILayout.Foldout(livePreviewFoldout, "Live preview and stats");
                if (livePreviewFoldout && framebuffer != null)
                {
                    int height = 160 * movie.demux.videoStreamInfo.height / movie.demux.videoStreamInfo.width;
                    GUILayout.Box(framebuffer, GUILayout.Width(160), GUILayout.Height(height));

                    EditorGUILayout.LabelField("Frames partially compared", dupFinder.stats.framesPartiallyComparedPercent.ToString("0.00") + " %");
                    EditorGUILayout.LabelField("Frames fully compared", dupFinder.stats.framesFullyComparedPercent.ToString("0.00") + " %");
                    EditorGUILayout.LabelField("Pixel cache hits", dupFinder.stats.pixelCacheHitPercent.ToString("0.00") + " %");
                }
            }
        }
Esempio n. 27
0
        public VisualElement CreateEditor()
        {
            if (m_Editor == null)
            {
                m_Editor = new VisualElement()
                {
                    style = { marginLeft = 5, marginRight = 5, marginTop = 5, marginBottom = 5 }
                };
                var metadataLabel = new GUIContent("Metadata");

                // Shared data
                var sharedIndex = m_Table.SharedData.Entries.FindIndex(e => e.Id == m_KeyId);
                Debug.Assert(sharedIndex != -1, $"Could not find index of key {m_KeyId}");
                var sharedSerializedObject = new SerializedObject(m_Table.SharedData);
                var sharedSerializedEditor = new MetadataCollectionField()
                {
                    Type = m_SharedMetadataType
                };
                var sharedEntryProperty = sharedSerializedObject.FindProperty($"m_Entries.Array.data[{sharedIndex}].m_Metadata");
                var sharedLabel         = new GUIContent("Shared Entry");
                var sharedEditor        = new IMGUIContainer(() =>
                {
                    sharedSerializedObject.Update();

                    EditorGUILayout.LabelField(sharedLabel, EditorStyles.boldLabel);
                    var rect = EditorGUILayout.GetControlRect(true, sharedSerializedEditor.GetPropertyHeight(sharedEntryProperty, metadataLabel));
                    sharedSerializedEditor.OnGUI(rect, sharedEntryProperty, metadataLabel);
                    sharedSerializedObject.ApplyModifiedProperties();
                });
                m_Editor.Add(sharedEditor);

                // Table data
                var tableIndex            = m_Table.TableData.FindIndex(d => d.Id == m_KeyId);
                var tableSerializedObject = new SerializedObject(m_Table);
                if (tableIndex == -1)
                {
                    EditorUtility.SetDirty(m_Table);
                    m_Table.CreateEmpty(m_KeyId);
                    tableSerializedObject.Update();

                    tableIndex = m_Table.TableData.FindIndex(d => d.Id == m_KeyId);
                    if (tableIndex == -1)
                    {
                        throw new System.Exception($"Failed to create or find a new entry for {m_KeyId} in the table");
                    }
                }

                var tableEntryProperty    = tableSerializedObject.FindProperty($"m_TableData.Array.data[{tableIndex}].m_Metadata");
                var tableSerializedEditor = new MetadataCollectionField()
                {
                    Type = m_MetadataType
                };
                var tableLabel  = new GUIContent($"{m_Locale?.ToString()} Entry Metadata");
                var tableEditor = new IMGUIContainer(() =>
                {
                    tableSerializedObject.Update();

                    EditorGUILayout.LabelField(tableLabel, EditorStyles.boldLabel);
                    var rect = EditorGUILayout.GetControlRect(true, tableSerializedEditor.GetPropertyHeight(tableEntryProperty, metadataLabel));
                    tableSerializedEditor.OnGUI(rect, tableEntryProperty, metadataLabel);
                    tableSerializedObject.ApplyModifiedProperties();
                });
                m_Editor.Add(tableEditor);
            }

            return(m_Editor);
        }
Esempio n. 28
0
        private void DrawResults()
        {
            Event currentEvent = Event.current;

            if (context != null)
            {
                GUILayout.BeginHorizontal("GroupBox");
                GUILayout.Label("Searched");
                var rect = EditorGUILayout.GetControlRect(GUILayout.Height(20));
                GUI.Label(rect, new GUIContent(context.name, GetIconForObject(context)), OddBackground);
                GUILayout.EndHorizontal();

                //On Left Click
                if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0 && rect.Contains(currentEvent.mousePosition))
                {
                    Selection.SetActiveObjectWithContext(context, this);
                    Repaint();
                }
            }

            if (results.Count <= 0)
            {
                GUILayout.BeginVertical(new GUIStyle("GroupBox"));
                EditorGUILayout.LabelField("No Results");
                GUILayout.EndVertical();
                return;
            }

            GUILayout.BeginVertical(new GUIStyle("GroupBox"));
            scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
            drawingScene   = string.Empty;

            for (int i = 0; i < results.Count; i++)
            {
                if (results[i] == null)
                {
                    continue;
                }

                GameObject resultGameObject = null;
                string     rowText          = results[i].name;

                //Is our result object in a scene or is it an asset?
                if (results[i] is GameObject)
                {
                    resultGameObject = ( GameObject )results[i];
                }
                else if (results[i] is Component)
                {
                    resultGameObject = (( Component )results[i]).gameObject;
                    rowText          = $"{results[i].name} ▶ {results[i].GetType()}";
                }

                GUIContent content = EditorGUIUtility.ObjectContent(results[i], results[i].GetType());
                content.text = rowText;

                var locationName = "Assets";

                if (resultGameObject != null)
                {
                    //If we're in a valid scene let's use the Scene info
                    if (resultGameObject.scene.IsValid())
                    {
                        locationName = resultGameObject.scene.name;
                    }
                    else
                    {
                        //If game object has no valid scene it is a prefab
                        locationName  = "Prefabs";
                        content.image = EditorGUIUtility.IconContent("PrefabNormal Icon").image;
                    }
                }

                if (drawingScene != locationName)
                {
                    drawingScene = locationName;
                    var style = ( GUIStyle )"toolbarbutton";
                    style.alignment = TextAnchor.MiddleLeft;
                    switch (locationName)
                    {
                    case "Prefabs":
                        GUILayout.Label(new GUIContent(locationName, EditorGUIUtility.IconContent("PrefabNormal Icon").image), style);
                        break;

                    case "Assets":
                        GUILayout.Label(new GUIContent(locationName, AssetPreview.GetMiniTypeThumbnail(typeof(ScriptableObject))), style);
                        break;

                    default:
                        GUILayout.Label(new GUIContent(locationName, AssetPreview.GetMiniTypeThumbnail(typeof(SceneAsset))), style);
                        break;
                    }
                }

                GUIStyle background = i % 2 == 0 ? OddBackground : EvenBackground;
                //Draw Game Object Row
                if (Selection.activeObject == results[i])
                {
                    GUI.backgroundColor = new Color(0.5f, 0.8f, 1f, 1f);
                }
                var rect = EditorGUILayout.GetControlRect();
                background.imagePosition = ImagePosition.ImageLeft;
                background.alignment     = TextAnchor.MiddleLeft;
                background.padding.left  = 0;
                EditorGUI.LabelField(rect, new GUIContent(rowText, GetIconForObject(results[i])), background);
                GUI.backgroundColor = Color.white;

                //On Left Click
                if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0 && rect.Contains(currentEvent.mousePosition))
                {
                    Selection.SetActiveObjectWithContext(results[i], this);
                    Repaint();
                }
                if (currentEvent.type == EventType.MouseDown && currentEvent.button == 1 && rect.Contains(currentEvent.mousePosition))
                {
                    var menu = new GenericMenu();

                    if (resultGameObject != null && !resultGameObject.scene.IsValid())
                    {
                        //Menu Options for a Prefab
                        menu.AddItem(new GUIContent("Open"), false, OpenInPreviewScene, resultGameObject);
                        menu.AddItem(new GUIContent("Open and Search"), false, OpenInPreviewSceneAndSearch, resultGameObject);
                    }

                    menu.ShowAsContext();
                    currentEvent.Use();
                }
            }

            EditorGUILayout.EndScrollView();
            GUILayout.EndVertical();

            if (results.Count > 0)
            {
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Clear"))
                {
                    results.Clear();
                    context = null;
                }
                GUILayout.EndHorizontal();
                GUILayout.Space(5);
            }
        }
Esempio n. 29
0
    /// <summary>
    /// Draw the label's properties.
    /// </summary>

    protected override bool ShouldDrawProperties()
    {
        mLabel = mWidget as UILabel;

        GUILayout.BeginHorizontal();

#if DYNAMIC_FONT
        mFontType = (FontType)EditorGUILayout.EnumPopup(mFontType, "DropDown", GUILayout.Width(74f));
        if (NGUIEditorTools.DrawPrefixButton("Font", GUILayout.Width(64f)))
#else
        mFontType = FontType.NGUI;
        if (NGUIEditorTools.DrawPrefixButton("Font", GUILayout.Width(74f)))
#endif
        {
            if (mFontType == FontType.NGUI)
            {
                ComponentSelector.Show <UIFont>(OnNGUIFont);
            }
            else
            {
                ComponentSelector.Show <Font>(OnUnityFont, new string[] { ".ttf", ".otf" });
            }
        }

        bool isValid           = false;
        SerializedProperty fnt = null;
        SerializedProperty ttf = null;

        if (mFontType == FontType.NGUI)
        {
            GUI.changed = false;
            fnt         = NGUIEditorTools.DrawProperty("", serializedObject, "mFont", GUILayout.MinWidth(40f));

            if (fnt.objectReferenceValue != null)
            {
                if (GUI.changed)
                {
                    serializedObject.FindProperty("mTrueTypeFont").objectReferenceValue = null;
                }
                NGUISettings.ambigiousFont = fnt.objectReferenceValue;
                isValid = true;
            }
        }
        else
        {
            GUI.changed = false;
            ttf         = NGUIEditorTools.DrawProperty("", serializedObject, "mTrueTypeFont", GUILayout.MinWidth(40f));

            if (ttf.objectReferenceValue != null)
            {
                if (GUI.changed)
                {
                    serializedObject.FindProperty("mFont").objectReferenceValue = null;
                }
                NGUISettings.ambigiousFont = ttf.objectReferenceValue;
                isValid = true;
            }
        }

        GUILayout.EndHorizontal();

        if (mFontType == FontType.Unity)
        {
            EditorGUILayout.HelpBox("Dynamic fonts suffer from issues in Unity itself where your characters may disappear, get garbled, or just not show at times. Use this feature at your own risk.\n\n" +
                                    "When you do run into such issues, please submit a Bug Report to Unity via Help -> Report a Bug (as this is will be a Unity bug, not an NGUI one).", MessageType.Warning);
        }

        EditorGUI.BeginDisabledGroup(!isValid);
        {
            UIFont uiFont  = (fnt != null) ? fnt.objectReferenceValue as UIFont : null;
            Font   dynFont = (ttf != null) ? ttf.objectReferenceValue as Font : null;

            if (uiFont != null && uiFont.isDynamic)
            {
                dynFont = uiFont.dynamicFont;
                uiFont  = null;
            }

            if (dynFont != null)
            {
                GUILayout.BeginHorizontal();
                {
                    EditorGUI.BeginDisabledGroup((ttf != null) ? ttf.hasMultipleDifferentValues : fnt.hasMultipleDifferentValues);

                    SerializedProperty prop = NGUIEditorTools.DrawProperty("Font Size", serializedObject, "mFontSize", GUILayout.Width(142f));
                    NGUISettings.fontSize = prop.intValue;

                    prop = NGUIEditorTools.DrawProperty("", serializedObject, "mFontStyle", GUILayout.MinWidth(40f));
                    NGUISettings.fontStyle = (FontStyle)prop.intValue;

                    NGUIEditorTools.DrawPadding();
                    EditorGUI.EndDisabledGroup();
                }
                GUILayout.EndHorizontal();

                NGUIEditorTools.DrawProperty("Material", serializedObject, "mMaterial");
            }
            else if (uiFont != null)
            {
                GUILayout.BeginHorizontal();
                SerializedProperty prop = NGUIEditorTools.DrawProperty("Font Size", serializedObject, "mFontSize", GUILayout.Width(142f));

                EditorGUI.BeginDisabledGroup(true);
                if (!serializedObject.isEditingMultipleObjects)
                {
                    if (mLabel.overflowMethod == UILabel.Overflow.ShrinkContent)
                    {
                        GUILayout.Label(" Actual: " + mLabel.finalFontSize + "/" + mLabel.defaultFontSize);
                    }
                    else
                    {
                        GUILayout.Label(" Default: " + mLabel.defaultFontSize);
                    }
                }
                EditorGUI.EndDisabledGroup();

                NGUISettings.fontSize = prop.intValue;
                GUILayout.EndHorizontal();
            }

            bool ww = GUI.skin.textField.wordWrap;
            GUI.skin.textField.wordWrap = true;
            SerializedProperty sp = serializedObject.FindProperty("mText");

            if (sp.hasMultipleDifferentValues)
            {
                NGUIEditorTools.DrawProperty("", sp, GUILayout.Height(128f));
            }
            else
            {
                GUIStyle style = new GUIStyle(EditorStyles.textField);
                style.wordWrap = true;

                float height = style.CalcHeight(new GUIContent(sp.stringValue), Screen.width - 100f);
                bool  offset = true;

                if (height > 90f)
                {
                    offset = false;
                    height = style.CalcHeight(new GUIContent(sp.stringValue), Screen.width - 20f);
                }
                else
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.BeginVertical(GUILayout.Width(76f));
                    GUILayout.Space(3f);
                    GUILayout.Label("Text");
                    GUILayout.EndVertical();
                    GUILayout.BeginVertical();
                }
                Rect rect = EditorGUILayout.GetControlRect(GUILayout.Height(height));

                GUI.changed = false;
                string text = EditorGUI.TextArea(rect, sp.stringValue, style);
                if (GUI.changed)
                {
                    sp.stringValue = text;
                }

                if (offset)
                {
                    GUILayout.EndVertical();
                    GUILayout.EndHorizontal();
                }
            }

            GUI.skin.textField.wordWrap = ww;

            SerializedProperty ov = NGUIEditorTools.DrawPaddedProperty("Overflow", serializedObject, "mOverflow");
            NGUISettings.overflowStyle = (UILabel.Overflow)ov.intValue;
            if (NGUISettings.overflowStyle == UILabel.Overflow.ClampContent)
            {
                NGUIEditorTools.DrawProperty("Use Ellipsis", serializedObject, "mOverflowEllipsis", GUILayout.Width(110f));
            }

            NGUIEditorTools.DrawPaddedProperty("Alignment", serializedObject, "mAlignment");

            if (dynFont != null)
            {
                NGUIEditorTools.DrawPaddedProperty("Keep crisp", serializedObject, "keepCrispWhenShrunk");
            }

            EditorGUI.BeginDisabledGroup(mLabel.bitmapFont != null && mLabel.bitmapFont.packedFontShader);
            GUILayout.BeginHorizontal();
            SerializedProperty gr = NGUIEditorTools.DrawProperty("Gradient", serializedObject, "mApplyGradient",
                                                                 GUILayout.Width(95f));

            EditorGUI.BeginDisabledGroup(!gr.hasMultipleDifferentValues && !gr.boolValue);
            {
                NGUIEditorTools.SetLabelWidth(30f);
                NGUIEditorTools.DrawProperty("Top", serializedObject, "mGradientTop", GUILayout.MinWidth(40f));
                GUILayout.EndHorizontal();
                GUILayout.BeginHorizontal();
                NGUIEditorTools.SetLabelWidth(50f);
                GUILayout.Space(79f);

                NGUIEditorTools.DrawProperty("Bottom", serializedObject, "mGradientBottom", GUILayout.MinWidth(40f));
                NGUIEditorTools.SetLabelWidth(80f);
            }
            EditorGUI.EndDisabledGroup();
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Effect", GUILayout.Width(76f));
            sp = NGUIEditorTools.DrawProperty("", serializedObject, "mEffectStyle", GUILayout.MinWidth(16f));

            EditorGUI.BeginDisabledGroup(!sp.hasMultipleDifferentValues && !sp.boolValue);
            {
                NGUIEditorTools.DrawProperty("", serializedObject, "mEffectColor", GUILayout.MinWidth(10f));
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                {
                    GUILayout.Label(" ", GUILayout.Width(56f));
                    NGUIEditorTools.SetLabelWidth(20f);
                    NGUIEditorTools.DrawProperty("X", serializedObject, "mEffectDistance.x", GUILayout.MinWidth(40f));
                    NGUIEditorTools.DrawProperty("Y", serializedObject, "mEffectDistance.y", GUILayout.MinWidth(40f));
                    NGUIEditorTools.DrawPadding();
                    NGUIEditorTools.SetLabelWidth(80f);
                }
            }
            EditorGUI.EndDisabledGroup();
            GUILayout.EndHorizontal();
            EditorGUI.EndDisabledGroup();

            sp = NGUIEditorTools.DrawProperty("Float spacing", serializedObject, "mUseFloatSpacing", GUILayout.Width(100f));

            if (!sp.boolValue)
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Spacing", GUILayout.Width(56f));
                NGUIEditorTools.SetLabelWidth(20f);
                NGUIEditorTools.DrawProperty("X", serializedObject, "mSpacingX", GUILayout.MinWidth(40f));
                NGUIEditorTools.DrawProperty("Y", serializedObject, "mSpacingY", GUILayout.MinWidth(40f));
                NGUIEditorTools.DrawPadding();
                NGUIEditorTools.SetLabelWidth(80f);
                GUILayout.EndHorizontal();
            }
            else
            {
                GUILayout.BeginHorizontal();
                GUILayout.Label("Spacing", GUILayout.Width(56f));
                NGUIEditorTools.SetLabelWidth(20f);
                NGUIEditorTools.DrawProperty("X", serializedObject, "mFloatSpacingX", GUILayout.MinWidth(40f));
                NGUIEditorTools.DrawProperty("Y", serializedObject, "mFloatSpacingY", GUILayout.MinWidth(40f));
                NGUIEditorTools.DrawPadding();
                NGUIEditorTools.SetLabelWidth(80f);
                GUILayout.EndHorizontal();
            }

            NGUIEditorTools.DrawProperty("Max Lines", serializedObject, "mMaxLineCount", GUILayout.Width(110f));

            GUILayout.BeginHorizontal();
            sp = NGUIEditorTools.DrawProperty("BBCode", serializedObject, "mEncoding", GUILayout.Width(100f));
            EditorGUI.BeginDisabledGroup(!sp.boolValue || mLabel.bitmapFont == null || !mLabel.bitmapFont.hasSymbols);
            NGUIEditorTools.SetLabelWidth(60f);
            NGUIEditorTools.DrawPaddedProperty("Symbols", serializedObject, "mSymbols");
            NGUIEditorTools.SetLabelWidth(80f);
            EditorGUI.EndDisabledGroup();
            GUILayout.EndHorizontal();
        }
        EditorGUI.EndDisabledGroup();
        return(isValid);
    }
Esempio n. 30
0
        public void Inspector(MotionEditor editor)
        {
            UltiDraw.Begin();
            Utility.SetGUIColor(UltiDraw.Grey);
            using (new EditorGUILayout.VerticalScope("Box")) {
                Utility.ResetGUIColor();

                Frame frame = Module.Data.GetFrame(editor.GetState().Index);

                Utility.SetGUIColor(UltiDraw.Orange);
                using (new EditorGUILayout.VerticalScope("Box")) {
                    Utility.ResetGUIColor();
                    EditorGUILayout.LabelField(this == Module.RegularPhaseFunction ? "Regular" : "Inverse");
                }

                if (IsKey(frame))
                {
                    SetPhase(frame, EditorGUILayout.Slider("Phase", GetPhase(frame), 0f, 1f));
                }
                else
                {
                    EditorGUI.BeginDisabledGroup(true);
                    SetPhase(frame, EditorGUILayout.Slider("Phase", GetPhase(frame), 0f, 1f));
                    EditorGUI.EndDisabledGroup();
                }

                if (IsKey(frame))
                {
                    if (Utility.GUIButton("Unset Key", UltiDraw.Grey, UltiDraw.White))
                    {
                        SetKey(frame, false);
                    }
                }
                else
                {
                    if (Utility.GUIButton("Set Key", UltiDraw.DarkGrey, UltiDraw.White))
                    {
                        SetKey(frame, true);
                    }
                }

                EditorGUILayout.BeginHorizontal();
                if (Utility.GUIButton("<", UltiDraw.DarkGrey, UltiDraw.White, 25f, 50f))
                {
                    editor.LoadFrame((GetPreviousKey(frame).Timestamp));
                }

                EditorGUILayout.BeginVertical(GUILayout.Height(50f));
                Rect ctrl = EditorGUILayout.GetControlRect();
                Rect rect = new Rect(ctrl.x, ctrl.y, ctrl.width, 50f);
                EditorGUI.DrawRect(rect, UltiDraw.Black);

                float startTime = frame.Timestamp - editor.GetWindow() / 2f;
                float endTime   = frame.Timestamp + editor.GetWindow() / 2f;
                if (startTime < 0f)
                {
                    endTime  -= startTime;
                    startTime = 0f;
                }
                if (endTime > Module.Data.GetTotalTime())
                {
                    startTime -= endTime - Module.Data.GetTotalTime();
                    endTime    = Module.Data.GetTotalTime();
                }
                startTime = Mathf.Max(0f, startTime);
                endTime   = Mathf.Min(Module.Data.GetTotalTime(), endTime);
                int start    = Module.Data.GetFrame(startTime).Index;
                int end      = Module.Data.GetFrame(endTime).Index;
                int elements = end - start;

                Vector3 prevPos = Vector3.zero;
                Vector3 newPos  = Vector3.zero;
                Vector3 bottom  = new Vector3(0f, rect.yMax, 0f);
                Vector3 top     = new Vector3(0f, rect.yMax - rect.height, 0f);

                //Sequences
                for (int i = 0; i < Module.Data.Sequences.Length; i++)
                {
                    float   _start = (float)(Mathf.Clamp(Module.Data.Sequences[i].Start, start, end) - start) / (float)elements;
                    float   _end   = (float)(Mathf.Clamp(Module.Data.Sequences[i].End, start, end) - start) / (float)elements;
                    float   left   = rect.x + _start * rect.width;
                    float   right  = rect.x + _end * rect.width;
                    Vector3 a      = new Vector3(left, rect.y, 0f);
                    Vector3 b      = new Vector3(right, rect.y, 0f);
                    Vector3 c      = new Vector3(left, rect.y + rect.height, 0f);
                    Vector3 d      = new Vector3(right, rect.y + rect.height, 0f);
                    UltiDraw.DrawTriangle(a, c, b, UltiDraw.Yellow.Transparent(0.25f));
                    UltiDraw.DrawTriangle(b, c, d, UltiDraw.Yellow.Transparent(0.25f));
                }

                if (Module.ShowVelocities)
                {
                    //Regular Velocities
                    for (int i = 1; i < elements; i++)
                    {
                        prevPos.x = rect.xMin + (float)(i - 1) / (elements - 1) * rect.width;
                        prevPos.y = rect.yMax - Module.RegularPhaseFunction.NVelocities[i + start - 1] * rect.height;
                        newPos.x  = rect.xMin + (float)(i) / (elements - 1) * rect.width;
                        newPos.y  = rect.yMax - Module.RegularPhaseFunction.NVelocities[i + start] * rect.height;
                        UltiDraw.DrawLine(prevPos, newPos, this == Module.RegularPhaseFunction ? UltiDraw.Green : UltiDraw.Red);
                    }

                    //Inverse Velocities
                    for (int i = 1; i < elements; i++)
                    {
                        prevPos.x = rect.xMin + (float)(i - 1) / (elements - 1) * rect.width;
                        prevPos.y = rect.yMax - Module.InversePhaseFunction.NVelocities[i + start - 1] * rect.height;
                        newPos.x  = rect.xMin + (float)(i) / (elements - 1) * rect.width;
                        newPos.y  = rect.yMax - Module.InversePhaseFunction.NVelocities[i + start] * rect.height;
                        UltiDraw.DrawLine(prevPos, newPos, this == Module.RegularPhaseFunction ? UltiDraw.Red : UltiDraw.Green);
                    }
                }

                if (Module.ShowCycle)
                {
                    //Cycle
                    for (int i = 1; i < elements; i++)
                    {
                        prevPos.x = rect.xMin + (float)(i - 1) / (elements - 1) * rect.width;
                        prevPos.y = rect.yMax - NormalisedCycle[i + start - 1] * rect.height;
                        newPos.x  = rect.xMin + (float)(i) / (elements - 1) * rect.width;
                        newPos.y  = rect.yMax - NormalisedCycle[i + start] * rect.height;
                        UltiDraw.DrawLine(prevPos, newPos, UltiDraw.Yellow);
                    }
                }

                //Phase
                //for(int i=1; i<Module.Data.Frames.Length; i++) {
                //	Frame A = Module.Data.Frames[i-1];
                //	Frame B = Module.Data.Frames[i];
                //	prevPos.x = rect.xMin + (float)(A.Index-start)/elements * rect.width;
                //	prevPos.y = rect.yMax - Mathf.Repeat(Phase[A.Index-1], 1f) * rect.height;
                //	newPos.x = rect.xMin + (float)(B.Index-start)/elements * rect.width;
                //	newPos.y = rect.yMax - Phase[B.Index-1] * rect.height;
                //	UltiDraw.DrawLine(prevPos, newPos, UltiDraw.White);
                //	bottom.x = rect.xMin + (float)(B.Index-start)/elements * rect.width;
                //	top.x = rect.xMin + (float)(B.Index-start)/elements * rect.width;
                //}

                Frame A = Module.Data.GetFrame(start);
                if (A.Index == 1)
                {
                    bottom.x = rect.xMin;
                    top.x    = rect.xMin;
                    UltiDraw.DrawLine(bottom, top, UltiDraw.Magenta.Transparent(0.5f));
                }
                Frame B = GetNextKey(A);
                while (A != B)
                {
                    prevPos.x = rect.xMin + (float)(A.Index - start) / elements * rect.width;
                    prevPos.y = rect.yMax - Mathf.Repeat(Phase[A.Index - 1], 1f) * rect.height;
                    newPos.x  = rect.xMin + (float)(B.Index - start) / elements * rect.width;
                    newPos.y  = rect.yMax - Phase[B.Index - 1] * rect.height;
                    UltiDraw.DrawLine(prevPos, newPos, UltiDraw.White);
                    bottom.x = rect.xMin + (float)(B.Index - start) / elements * rect.width;
                    top.x    = rect.xMin + (float)(B.Index - start) / elements * rect.width;
                    UltiDraw.DrawLine(bottom, top, UltiDraw.Magenta.Transparent(0.5f));
                    A = B;
                    B = GetNextKey(A);
                    if (B.Index > end)
                    {
                        break;
                    }
                }

                //Seconds
                float timestamp = startTime;
                while (timestamp <= endTime)
                {
                    float floor = Mathf.FloorToInt(timestamp);
                    if (floor >= startTime && floor <= endTime)
                    {
                        top.x = rect.xMin + (float)(Module.Data.GetFrame(floor).Index - start) / elements * rect.width;
                        UltiDraw.DrawCircle(top, 5f, UltiDraw.White);
                    }
                    timestamp += 1f;
                }
                //

                //Current Pivot
                top.x    = rect.xMin + (float)(frame.Index - start) / elements * rect.width;
                bottom.x = rect.xMin + (float)(frame.Index - start) / elements * rect.width;
                UltiDraw.DrawLine(top, bottom, UltiDraw.Yellow);
                UltiDraw.DrawCircle(top, 3f, UltiDraw.Green);
                UltiDraw.DrawCircle(bottom, 3f, UltiDraw.Green);

                Handles.DrawLine(Vector3.zero, Vector3.zero);                 //Somehow needed to get it working...
                EditorGUILayout.EndVertical();

                if (Utility.GUIButton(">", UltiDraw.DarkGrey, UltiDraw.White, 25f, 50f))
                {
                    editor.LoadFrame(GetNextKey(frame).Timestamp);
                }
                EditorGUILayout.EndHorizontal();
            }
            UltiDraw.End();
        }