Exemple #1
0
    public override void OnGUI(Rect pos, SerializedProperty property, GUIContent label)
    {
        SliderAttribute rAttribute = (SliderAttribute)attribute;

        if (property.propertyType != SerializedPropertyType.Float)
        {
            EditorGUI.HelpBox(pos, "(" + property.type + " " + property.name + ") Has to be of type float!", MessageType.Warning);
            HeightMultiplier = 2.5f;
            return;
        }

        EditorGUI.BeginProperty(pos, label, property);
        {
            // Label
            pos = EditorGUI.PrefixLabel(pos, label);

            // Child objects shouldn't be indented
            int indent = EditorGUI.indentLevel;
            EditorGUI.indentLevel = 0;

            //Draw the different sliders
            if (!rAttribute.Modifiable)
            {
                NormalSlider(rAttribute, pos, property, label);
            }
            else
            {
                ModifiableSlider(rAttribute, pos, property, label);
            }

            // Reset indenting
            EditorGUI.indentLevel = indent;
        }
        EditorGUI.EndProperty();
    }
Exemple #2
0
    void ModifiableSlider(SliderAttribute rAttribute, Rect pos, SerializedProperty property, GUIContent label)
    {
        // Create rects
        Rect minRect    = new Rect(pos.x, pos.y, FieldWidth, pos.height);
        Rect sliderRect = new Rect(minRect.xMax + SliderPadding * 0.5f, pos.y, Mathf.Max(0.0f, pos.width - FieldWidth * 2.0f - SliderPadding), pos.height);
        Rect maxRect    = new Rect(sliderRect.xMax, pos.y, FieldWidth, pos.height);

        //get the properties
        SerializedProperty spMin   = property.serializedObject.FindProperty(rAttribute.PropertyMin);
        SerializedProperty spMax   = property.serializedObject.FindProperty(rAttribute.PropertyMax);
        SerializedProperty spValue = property;

        if (spMin == null || spMin.propertyType != SerializedPropertyType.Float)
        {
            if (spMin != null)
            {
                EditorGUI.HelpBox(pos, "(" + spMin.type + " " + spMin.name + ") Is null or not of type float!", MessageType.Error);
            }
            else
            {
                EditorGUI.HelpBox(pos, "PropertyMin == NULL (not found?)", MessageType.Error);
            }

            HeightMultiplier = 2.5f;
            return;
        }

        if (spMax == null || spMax.propertyType != SerializedPropertyType.Float)
        {
            if (spMax != null)
            {
                EditorGUI.HelpBox(pos, "(" + spMax.type + " " + spMax.name + ") Is null or not of type float!", MessageType.Error);
            }
            else
            {
                EditorGUI.HelpBox(pos, "PropertyMax == NULL (not found?)", MessageType.Error);
            }

            HeightMultiplier = 2.5f;
            return;
        }

        // Minimum
        spMin.floatValue = EditorGUI.FloatField(minRect, spMin.floatValue);
        spMin.floatValue = Mathf.Min(spMin.floatValue, spMax.floatValue);

        // Maximum
        spMax.floatValue = EditorGUI.FloatField(maxRect, spMax.floatValue);
        spMax.floatValue = Mathf.Max(spMax.floatValue, spMin.floatValue);

        // Value slider
        spValue.floatValue = EditorGUI.Slider(sliderRect, spValue.floatValue, spMin.floatValue, spMax.floatValue);
    }
Exemple #3
0
    void NormalSlider(SliderAttribute rAttribute, Rect pos, SerializedProperty property, GUIContent label)
    {
        // Create rects
        Rect minRect    = new Rect(pos.x, pos.y, FieldWidth, pos.height);
        Rect sliderRect = new Rect(minRect.xMax + SliderPadding * 0.5f, pos.y, Mathf.Max(0.0f, pos.width - FieldWidth * 2.0f - SliderPadding), pos.height);
        Rect maxRect    = new Rect(sliderRect.xMax, pos.y, FieldWidth, pos.height);

        // Minimum
        EditorGUI.LabelField(minRect, rAttribute.Min.ToString("0.0"));

        // Value slider
        property.floatValue = EditorGUI.Slider(sliderRect, property.floatValue, rAttribute.Min, rAttribute.Max);

        // Maximum
        EditorGUI.LabelField(maxRect, rAttribute.Max.ToString("0.0"));
    }
Exemple #4
0
        private VisualElement CreateMinMaxSlider(MinMaxSliderField slider, SliderAttribute sliderAttribute, SerializedProperty property, float defaultMinimum, float defaultMaximum)
        {
            void setMin(float value) => slider.MinimumLimit = value;
            void setMax(float value) => slider.MaximumLimit = value;

            if (!ReflectionHelper.SetupValueSourceCallback(sliderAttribute.MinimumSource, fieldInfo.DeclaringType, property, slider, defaultMinimum, sliderAttribute.AutoUpdate, setMin))
            {
                Debug.LogWarningFormat(_invalidMinimumSourceError, property.propertyPath, "float", sliderAttribute.MinimumSource);
            }

            if (!ReflectionHelper.SetupValueSourceCallback(sliderAttribute.MaximumSource, fieldInfo.DeclaringType, property, slider, defaultMaximum, sliderAttribute.AutoUpdate, setMax))
            {
                Debug.LogWarningFormat(_invalidMaximumSourceError, property.propertyPath, "float", sliderAttribute.MaximumSource);
            }

            return(slider.ConfigureProperty(property));
        }
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        SliderAttribute slider = attribute as SliderAttribute;

        switch (property.propertyType)
        {
        case SerializedPropertyType.Integer:
            EditorGUI.IntSlider(position, property, Convert.ToInt32(slider.min), Convert.ToInt32(slider.max), label);
            break;

        case SerializedPropertyType.Float:
            EditorGUI.Slider(position, property, slider.min, slider.max, label);
            break;

        default:
            EditorGUI.LabelField(position, label.text, "Slider only works with float or int.");
            break;
        }
    }
Exemple #6
0
        public override void DrawProperty(SerializedProperty property)
        {
            SliderAttribute sliderAttribute = PropertyUtility.GetAttributes <SliderAttribute>(property)[0];

            if (property.propertyType == SerializedPropertyType.Integer)
            {
                EditorGUILayout.IntSlider(property, (int)sliderAttribute.MinValue, (int)sliderAttribute.MaxValue);
            }
            else if (property.propertyType == SerializedPropertyType.Float)
            {
                EditorGUILayout.Slider(property, sliderAttribute.MinValue, sliderAttribute.MaxValue);
            }
            else
            {
                string warning = sliderAttribute.GetType().Name + " can be used only on int or float fields";
                EditorGUILayout.HelpBox(warning, MessageType.Warning);
                Debug.LogWarning(warning, PropertyUtility.GetTargetObject(property));

                EditorGUILayout.PropertyField(property, true);
            }
        }
Exemple #7
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            SliderAttribute assert = attribute as SliderAttribute;

            if (assert != null)
            {
                label.tooltip = "Min, Max : " + assert._min.ToString() + ", " + assert._max.ToString();
                if (property.propertyType == SerializedPropertyType.Float)
                {
                    property.floatValue = EditorGUI.Slider(position, label, property.floatValue, assert._min, assert._max);
                }
                else if (property.propertyType == SerializedPropertyType.Integer)
                {
                    property.intValue = (int)EditorGUI.Slider(position, label, property.intValue, assert._min, assert._max);
                }
                else
                {
                    EditorGUI.LabelField(position, label.text, "Use Slider with float or int.");
                }
            }
        }
Exemple #8
0
        public override void DrawProperty(SerializedProperty property)
        {
            EditorDrawUtility.DrawHeader(property);

            SliderAttribute sliderAttribute = PropertyUtility.GetAttribute <SliderAttribute>(property);

            if (property.propertyType == SerializedPropertyType.Integer)
            {
                EditorGUILayout.IntSlider(property, (int)sliderAttribute.MinValue, (int)sliderAttribute.MaxValue);
            }
            else if (property.propertyType == SerializedPropertyType.Float)
            {
                EditorGUILayout.Slider(property, sliderAttribute.MinValue, sliderAttribute.MaxValue);
            }
            else
            {
                string warning = sliderAttribute.GetType().Name + " can be used only on int or float fields";
                EditorDrawUtility.DrawHelpBox(warning, MessageType.Warning, logToConsole: true, context: PropertyUtility.GetTargetObject(property));

                EditorDrawUtility.DrawPropertyField(property);
            }
        }
Exemple #9
0
        public NumberSlider(SliderAttribute attributes, PropertyInfo p, object owner)
        {
            InitializeComponent();
            this.attributes = attributes;
            property        = p;
            propertyOwner   = owner;

            initValue = true;

            SlideInput.Minimum = attributes.Min;

            initValue = true;

            SlideInput.Maximum = attributes.Max;

            initValue = true;

            if (attributes.Snap && attributes.Ticks != null && attributes.Ticks.Length > 0)
            {
                SlideInput.IsSnapToTickEnabled = true;
                foreach (float t in attributes.Ticks)
                {
                    SlideInput.Ticks.Add(t);
                }
            }

            isInt = attributes.IsInt;

            if (isInt)
            {
                SlideInput.Value = Convert.ToInt32(p.GetValue(owner));
                InputValue.Text  = SlideInput.Value > 0 ? String.Format("{0:0}", SlideInput.Value) : "0";
            }
            else
            {
                SlideInput.Value = Convert.ToSingle(p.GetValue(owner));
                InputValue.Text  = SlideInput.Value >= 0.01 ? String.Format("{0:0.000}", SlideInput.Value) : "0";
            }
        }
        private static UISlider AddSlider <T>(this UIHelperBase group, string text, string propertyName, SliderAttribute attr)
        {
            var     property   = typeof(T).GetProperty(propertyName);
            UILabel valueLabel = null;

            var helper = group as UIHelper;

            if (helper != null)
            {
                var type = typeof(UIHelper).GetField("m_Root", BindingFlags.NonPublic | BindingFlags.Instance);
                if (type != null)
                {
                    var panel = type.GetValue(helper) as UIComponent;
                    valueLabel = panel?.AddUIComponent <UILabel>();
                }
            }


            var slider = (UISlider)group.AddSlider(text, attr.Min, attr.Max, attr.Step, (float)property.GetValue(OptionsWrapper <T> .Options, null),
                                                   f =>
            {
                property.SetValue(OptionsWrapper <T> .Options, f, null);
                OptionsWrapper <T> .SaveOptions();
                attr.Action <float>().Invoke(f);
                if (valueLabel != null)
                {
                    valueLabel.text = f.ToString(CultureInfo.InvariantCulture);
                }
            });
            var nameLabel = slider.parent.Find <UILabel>("Label");

            if (nameLabel != null)
            {
                nameLabel.width = nameLabel.textScale * nameLabel.font.size * nameLabel.text.Length;
            }
            if (valueLabel == null)
            {
                return(slider);
            }
            valueLabel.AlignTo(slider, UIAlignAnchor.TopLeft);
            valueLabel.relativePosition = new Vector3(240, 0, 0);
            valueLabel.text             = property.GetValue(OptionsWrapper <T> .Options, null).ToString();
            return(slider);
        }
Exemple #11
0
        protected void BuildParameter(string parameter, GraphParameterValue v, Node n)
        {
            try
            {
                PropertyInfo info1 = n.GetType().GetProperty(parameter);
                PropertyInfo info2 = v.GetType().GetProperty("Value");

                if (info1 == null)
                {
                    if (v.Value is float)
                    {
                        NumberInput np = new NumberInput(NumberInputType.Float, v, info2);
                        Stack.Children.Add(np);
                    }
                    else if (v.Value is int)
                    {
                        NumberInput np = new NumberInput(NumberInputType.Int, v, info2);
                        Stack.Children.Add(np);
                    }
                    else if (v.Value is bool)
                    {
                        ToggleControl tc = new ToggleControl("True", info2, v);
                        Stack.Children.Add(tc);
                    }
                }
                else
                {
                    if (v.Value is float || v.Value is int)
                    {
                        SliderAttribute sl = info1.GetCustomAttribute <SliderAttribute>();

                        if (sl != null)
                        {
                            NumberSlider inp = new NumberSlider(sl, info2, v);
                            Stack.Children.Add(inp);
                        }
                        else if (v.Value is float)
                        {
                            NumberInput np = new NumberInput(NumberInputType.Float, v, info2);
                            Stack.Children.Add(np);
                        }
                        else if (v.Value is int)
                        {
                            NumberInput np = new NumberInput(NumberInputType.Int, v, info2);
                            Stack.Children.Add(np);
                        }
                    }
                    else if (v.Value is bool)
                    {
                        ToggleControl tc = new ToggleControl(v.Name, info2, v);
                        Stack.Children.Add(tc);
                    }
                    else if (v.Value is Vector4)
                    {
                        ColorSelect cs = new ColorSelect(info2, v);
                        Stack.Children.Add(cs);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
        }
Exemple #12
0
        private void SerializeFields()
        {
            FieldInfo[] fields = this.GetType().GetFields();

            for (int i = 0; i < fields.Length; i++)
            {
                var field = fields[i];
                var value = field.GetValue(this);

                if (value is MeshRenderer)
                {
                    return;
                }

                var attributes = field.GetCustomAttributes().ToArray();

                if (attributes != default && attributes.Length > 0)
                {
                    if (attributes.Any(x => x is NonSerializedAttribute))
                    {
                        continue;
                    }

                    DragAttribute   dragAttribute   = default;
                    SliderAttribute sliderAttribute = default;
                    InputAttribute  inputAttribute  = default;

                    // drag attribute
                    if (attributes.Any(x =>
                    {
                        if (x.GetType() == typeof(DragAttribute))
                        {
                            dragAttribute = (DragAttribute)x;
                            return(true);
                        }
                        return(false);
                    }))
                    {
                        switch (value)
                        {
                        case float val:
                            ImGui.DragFloat(field.Name, ref val, dragAttribute.speed, dragAttribute.min, dragAttribute.max, dragAttribute.format);
                            field.SetValue(this, val);
                            continue;

                        case int intVal:
                            ImGui.DragInt(field.Name, ref intVal);
                            field.SetValue(this, intVal);
                            continue;

                        case Vector2 vector2:
                            System.Numerics.Vector2 vec2Val = vector2.ToSystemRef();
                            ImGui.DragFloat2(field.Name, ref vec2Val, dragAttribute.speed, dragAttribute.min, dragAttribute.max, dragAttribute.format);

                            field.SetValue(this, vec2Val.ToOpenTKRef());
                            continue;

                        case Vector3 vector3:
                            System.Numerics.Vector3 vec3Val = vector3.ToSystemRef();
                            ImGui.DragFloat3(field.Name, ref vec3Val, dragAttribute.speed, dragAttribute.min, dragAttribute.max, dragAttribute.format);
                            field.SetValue(this, vec3Val.ToOpenTKRef());
                            continue;
                        }
                    }

                    // slider attribute
                    if (attributes.Any(x =>
                    {
                        if (x.GetType() == typeof(SliderAttribute))
                        {
                            sliderAttribute = (SliderAttribute)x;
                            return(true);
                        }
                        return(false);
                    }))
                    {
                        switch (value)
                        {
                        case float val:
                            ImGui.SliderFloat(field.Name, ref val, sliderAttribute.min, sliderAttribute.max, sliderAttribute.format, sliderAttribute.imGuiSliderFlags);
                            field.SetValue(this, val);
                            continue;

                        case int intVal:
                            ImGui.SliderInt(field.Name, ref intVal, (int)sliderAttribute.min, (int)sliderAttribute.max, intVal.ToString(), sliderAttribute.imGuiSliderFlags);
                            field.SetValue(this, intVal);
                            continue;

                        case Vector2 vector2:
                            System.Numerics.Vector2 vec2Val = vector2.ToSystemRef();
                            ImGui.SliderFloat2(field.Name, ref vec2Val, sliderAttribute.min, sliderAttribute.max, sliderAttribute.format, sliderAttribute.imGuiSliderFlags);

                            field.SetValue(this, vec2Val.ToOpenTKRef());
                            continue;

                        case Vector3 vector3:
                            System.Numerics.Vector3 vec3Val = vector3.ToSystemRef();
                            ImGui.DragFloat3(field.Name, ref vec3Val);
                            field.SetValue(this, vec3Val.ToOpenTKRef());
                            continue;
                        }
                    }

                    //Input attribute
                    if (attributes.Any(x =>
                    {
                        if (x.GetType() == typeof(InputAttribute))
                        {
                            inputAttribute = (InputAttribute)x;
                            return(true);
                        }
                        return(false);
                    }))
                    {
                        switch (value)
                        {
                        case float val:
                            ImGui.InputFloat(field.Name, ref val, inputAttribute.step, inputAttribute.step_fast, inputAttribute.format, inputAttribute.flags);
                            field.SetValue(this, val);
                            continue;

                        case int intVal:
                            ImGui.InputInt(field.Name, ref intVal, (int)inputAttribute.step, (int)inputAttribute.step_fast, inputAttribute.flags);
                            field.SetValue(this, intVal);
                            continue;

                        case Vector2 vector2:
                            System.Numerics.Vector2 vec2Val = vector2.ToSystemRef();
                            ImGui.InputFloat2(field.Name, ref vec2Val, inputAttribute.format, inputAttribute.flags);

                            field.SetValue(this, vec2Val.ToOpenTKRef());
                            continue;

                        case Vector3 vector3:
                            System.Numerics.Vector3 vec3Val = vector3.ToSystemRef();
                            ImGui.InputFloat3(field.Name, ref vec3Val, inputAttribute.format, inputAttribute.flags);
                            field.SetValue(this, vec3Val.ToOpenTKRef());
                            continue;
                        }
                    }
                }

                // if has no attribute draw drag

                switch (value)
                {
                case float val:
                    ImGui.DragFloat(field.Name, ref val);
                    field.SetValue(this, val);
                    break;

                case int intVal:
                    ImGui.DragInt(field.Name, ref intVal);
                    field.SetValue(this, intVal);
                    break;

                case bool boolVal:
                    ImGui.Checkbox(field.Name, ref boolVal);
                    field.SetValue(this, boolVal);
                    break;

                case string strValue:
                    ImGui.InputText(field.Name, ref strValue, 20);
                    field.SetValue(this, strValue);
                    break;

                case Vector2 vector2:
                    System.Numerics.Vector2 vec2Val = vector2.ToSystemRef();
                    ImGui.DragFloat2(field.Name, ref vec2Val);

                    field.SetValue(this, vec2Val.ToOpenTKRef());
                    break;

                case Vector3 vector3:
                    System.Numerics.Vector3 vec3Val = vector3.ToSystemRef();
                    ImGui.DragFloat3(field.Name, ref vec3Val);
                    field.SetValue(this, vec3Val.ToOpenTKRef());
                    break;

                case Color4 color4:
                    System.Numerics.Vector4 sysColor = color4.ToSystem();
                    ImGui.ColorEdit4(field.Name, ref sysColor);
                    field.SetValue(this, sysColor.ToOpenTkColorRef());
                    break;
                }
            }
        } //SerializeFields end
Exemple #13
0
 public SliderDrawerAttribute(SliderAttribute slider)
 {
     this.min = slider.Min;
     this.max = slider.Max;
 }
        private void BakeMenu()
        {
            Type caller = this.GetType();

            foreach (PropertyInfo info in caller.GetProperties())
            {
                if (info.CanWrite & info.CanWrite)
                {
                    bool isEditable = true;
                    foreach (Attribute attrib in info.GetCustomAttributes <Attribute>())
                    {
                        if (attrib.GetType() == typeof(NotEditableAttribute))
                        {
                            isEditable = false;
                            break;
                        }
                        else
                        {
                            isEditable = true;
                        }
                    }
                    if (isEditable)
                    {
                        bool isWhiteListed = false;
                        foreach (Type test in this.typeWhiteList)
                        {
                            if (test == info.PropertyType)
                            {
                                isWhiteListed = true;
                                break;
                            }
                        }
                        if (!isWhiteListed)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        continue;
                    }
                    // Option Name
                    this.menu.Left.Children.Add(this.CreateLabelWithText(info.Name));

                    // Option Input
                    if (info.PropertyType == typeof(float) | info.PropertyType == typeof(double) | info.PropertyType == typeof(int)) //Numeric Input
                    {
                        if (info.GetCustomAttribute <SliderAttribute>() != null)
                        {
                            SliderAttribute attribute = info.GetCustomAttribute <SliderAttribute>();
                            Slider          slider    = new Slider();
                            slider.Height  = OptionHeight;
                            slider.ToolTip = 0;
                            if (info.GetValue(this) != null)
                            {
                                slider.Value = Convert.ToDouble(info.GetValue(this)); // Set current value
                            }
                            slider.VerticalAlignment = VerticalAlignment.Center;
                            slider.ValueChanged     += delegate(object sender, RoutedPropertyChangedEventArgs <double> e)
                            {
                                slider.ToolTip = slider.Value;
                                if (info.PropertyType == typeof(int))
                                {
                                    info.SetValue(this, Convert.ToInt32(slider.Value));
                                }
                                else
                                {
                                    info.SetValue(this, slider.Value);
                                }
                            };
                            slider.Minimum = attribute.minValue;
                            slider.Maximum = attribute.maxValue;
                            if (info.PropertyType == typeof(int))
                            {
                                slider.TickFrequency       = 1;
                                slider.IsSnapToTickEnabled = true;
                            }
                            this.menu.Right.Children.Add(slider);
                        }
                        else
                        {
                            TextBox textBox = new TextBox();
                            textBox.Height = OptionHeight;
                            if (info.GetValue(this) != null)
                            {
                                textBox.Text = info.GetValue(this).ToString(); // Set current value
                            }
                            textBox.VerticalAlignment = VerticalAlignment.Center;
                            textBox.PreviewTextInput += delegate(object sender, TextCompositionEventArgs e)
                            {
                                Regex _regex = new Regex("[^0-9.,-]+");
                                e.Handled = _regex.IsMatch(e.Text);
                            };
                            textBox.TextChanged += delegate(object sender, TextChangedEventArgs e)
                            {
                                if (info.PropertyType == typeof(double))
                                {
                                    info.SetValue(this, Convert.ToDouble(textBox.Text));
                                }
                                else if (info.PropertyType == typeof(float))
                                {
                                    info.SetValue(this, float.Parse(textBox.Text));
                                }
                                else if (info.PropertyType == typeof(int))
                                {
                                    info.SetValue(this, Convert.ToInt32(textBox.Text));
                                }
                            };
                            this.menu.Right.Children.Add(textBox);
                        }
                    }
                    else if (info.PropertyType == typeof(string) | info.PropertyType == typeof(char)) // Text Input
                    {
                        TextBox textBox = new TextBox();
                        textBox.Height = OptionHeight;
                        if (info.GetValue(this) != null)
                        {
                            textBox.Text = info.GetValue(this).ToString(); // Set current value
                        }
                        textBox.TextChanged += delegate(object sender, TextChangedEventArgs e)
                        {
                            info.SetValue(this, textBox.Text);
                        };
                        if (info.GetCustomAttribute <TextboxAttribute>() != null)
                        {
                            TextboxAttribute attribute = info.GetCustomAttribute <TextboxAttribute>();
                            textBox.MaxLength = attribute.maxChars;
                            if (attribute.multiLine)
                            {
                                textBox.MaxLines = 999;
                            }
                        }
                        else
                        {
                            textBox.MaxLines = 1;
                        }
                        this.menu.Right.Children.Add(textBox);
                    }
                    else if (info.PropertyType == typeof(bool))
                    {
                        CheckBox checkBox = new CheckBox();
                        checkBox.Height = OptionHeight;
                        if (info.GetValue(this) != null)
                        {
                            checkBox.IsChecked = (bool)info.GetValue(this); // Set current value
                        }
                        checkBox.VerticalAlignment   = VerticalAlignment.Center;
                        checkBox.HorizontalAlignment = HorizontalAlignment.Center;
                        checkBox.Checked            += delegate(object sender, RoutedEventArgs e)
                        {
                            info.SetValue(this, checkBox.IsChecked);
                        };
                        this.menu.Right.Children.Add(checkBox);
                    }
                    else
                    {
                        this.menu.Right.Children.Add(this.CreateLabelWithText(" ")); // Add dummy
                    }
                }
            }
        }
Exemple #15
0
 public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
 {
     mAttribute          = (SliderAttribute)this.attribute;
     property.floatValue = EditorGUI.Slider(position, label.text, property.floatValue, mAttribute.mStart, mAttribute.mEnd);
 }
        private static UISlider AddSlider <T>(this UIHelperBase group, IOptionsWrapper <T> options, string text, string propertyName, SliderAttribute attr)
        {
            var     property   = typeof(T).GetProperty(propertyName);
            UILabel valueLabel = null;

            var helper = group as UIHelper;

            if (helper != null)
            {
                var type = typeof(UIHelper).GetField("m_Root", BindingFlags.NonPublic | BindingFlags.Instance);
                if (type != null)
                {
                    var panel = type.GetValue(helper) as UIComponent;
                    valueLabel = panel?.AddUIComponent <UILabel>();
                }
            }

            float finalValue;
            var   value = property.GetValue(options.GetOptions(), null);

            if (value is float)
            {
                finalValue = (float)value;
            }
            else if (value is byte)
            {
                finalValue = (byte)value;
            }
            else if (value is int)
            {
                finalValue = (int)value;
            }
            else
            {
                throw new Exception("Unsupported numeric type for slider!");
            }

            var slider = (UISlider)group.AddSlider(text, attr.Min, attr.Max, attr.Step, Mathf.Clamp(finalValue, attr.Min, attr.Max),
                                                   f =>
            {
                if (value is float)
                {
                    property.SetValue(options.GetOptions(), f, null);
                }
                else if (value is byte)
                {
                    property.SetValue(options.GetOptions(), (byte)Math.Round(f, MidpointRounding.AwayFromZero), null);
                }
                else if (value is int)
                {
                    property.SetValue(options.GetOptions(), (int)Math.Round(f, MidpointRounding.AwayFromZero), null);
                }
                options.SaveOptions();
                attr.Action <float>().Invoke(f);
                if (valueLabel != null)
                {
                    valueLabel.text = f.ToString(CultureInfo.InvariantCulture);
                }
            });
            var nameLabel = slider.parent.Find <UILabel>("Label");

            if (nameLabel != null)
            {
                nameLabel.width = nameLabel.textScale * nameLabel.font.size * nameLabel.text.Length;
            }
            if (valueLabel == null)
            {
                return(slider);
            }
            valueLabel.AlignTo(slider, UIAlignAnchor.TopLeft);
            valueLabel.relativePosition = new Vector3(240, 0, 0);
            valueLabel.text             = value.ToString();
            return(slider);
        }
Exemple #17
0
        public static Tuple <UIElement, UIElement> WrapIt(UIElement parent, ref int top, PropertyFieldWrapper memberInfo, object item, int order, object list = null, Type arrayType = null, int index = -1)
        {
            int  elementHeight = 0;
            Type type          = memberInfo.Type;

            if (arrayType != null)
            {
                type = arrayType;
            }
            UIElement e;

            // TODO: Other common structs? -- Rectangle, Point
            CustomModConfigItemAttribute customUI = ConfigManager.GetCustomAttribute <CustomModConfigItemAttribute>(memberInfo, null, null);

            if (customUI != null)
            {
                Type customUIType = customUI.t;
                if (typeof(ConfigElement).IsAssignableFrom(customUIType))
                {
                    ConstructorInfo ctor = customUIType.GetConstructor(new Type[0]);
                    if (ctor != null)
                    {
                        object instance = ctor.Invoke(new object[0]);
                        e = instance as UIElement;
                    }
                    else
                    {
                        e = new UIText($"{customUIType.Name} specified via CustomModConfigItem for {memberInfo.Name} does not have an empty constructor.");
                    }
                }
                else
                {
                    e = new UIText($"{customUIType.Name} specified via CustomModConfigItem for {memberInfo.Name} does not inherit from ConfigElement.");
                }
            }
            else if (item.GetType() == typeof(HeaderAttribute))
            {
                e = new HeaderElement((string)memberInfo.GetValue(item));
            }
            else if (type == typeof(ItemDefinition))
            {
                e = new ItemDefinitionElement();
            }
            else if (type == typeof(ProjectileDefinition))
            {
                e = new ProjectileDefinitionElement();
            }
            else if (type == typeof(NPCDefinition))
            {
                e = new NPCDefinitionElement();
            }
            else if (type == typeof(PrefixDefinition))
            {
                e = new PrefixDefinitionElement();
            }
            else if (type == typeof(Color))
            {
                e = new ColorElement();
            }
            else if (type == typeof(Vector2))
            {
                e = new Vector2Element();
            }
            else if (type == typeof(bool))             // isassignedfrom?
            {
                e = new BooleanElement();
            }
            else if (type == typeof(float))
            {
                e = new FloatElement();
            }
            else if (type == typeof(byte))
            {
                e = new ByteElement();
            }
            else if (type == typeof(uint))
            {
                e = new UIntElement();
            }
            else if (type == typeof(int))
            {
                SliderAttribute sliderAttribute = ConfigManager.GetCustomAttribute <SliderAttribute>(memberInfo, item, list);
                if (sliderAttribute != null)
                {
                    e = new IntRangeElement();
                }
                else
                {
                    e = new IntInputElement();
                }
            }
            else if (type == typeof(string))
            {
                OptionStringsAttribute ost = ConfigManager.GetCustomAttribute <OptionStringsAttribute>(memberInfo, item, list);
                if (ost != null)
                {
                    e = new StringOptionElement();
                }
                else
                {
                    e = new StringInputElement();
                }
            }
            else if (type.IsEnum)
            {
                if (list != null)
                {
                    e = new UIText($"{memberInfo.Name} not handled yet ({type.Name}).");
                }
                else
                {
                    e = new EnumElement();
                }
            }
            else if (type.IsArray)
            {
                e = new ArrayElement();
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List <>))
            {
                e = new ListElement();
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(HashSet <>))
            {
                e = new SetElement();
            }
            else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary <,>))
            {
                e = new DictionaryElement();
            }
            else if (type.IsClass)
            {
                e = new ObjectElement(/*, ignoreSeparatePage: ignoreSeparatePage*/);
            }
            else if (type.IsValueType && !type.IsPrimitive)
            {
                e = new UIText($"{memberInfo.Name} not handled yet ({type.Name}) Structs need special UI.");
                //e.Top.Pixels += 6;
                e.Height.Pixels += 6;
                e.Left.Pixels   += 4;

                object subitem = memberInfo.GetValue(item);
            }
            else
            {
                e              = new UIText($"{memberInfo.Name} not handled yet ({type.Name})");
                e.Top.Pixels  += 6;
                e.Left.Pixels += 4;
            }
            if (e != null)
            {
                if (e is ConfigElement configElement)
                {
                    configElement.Bind(memberInfo, item, (IList)list, index);
                    configElement.OnBind();
                }
                e.Recalculate();
                elementHeight = (int)e.GetOuterDimensions().Height;

                var container = GetContainer(e, index == -1 ? order : index);
                container.Height.Pixels = elementHeight;
                UIList uiList = parent as UIList;
                if (uiList != null)
                {
                    uiList.Add(container);
                    float p = uiList.GetTotalHeight();
                }
                else
                {
                    // Only Vector2 and Color use this I think, but modders can use the non-UIList approach for custom UI and layout.
                    container.Top.Pixels   = top;
                    container.Width.Pixels = -20;
                    container.Left.Pixels  = 20;
                    top += elementHeight + 4;
                    parent.Append(container);
                    parent.Height.Set(top, 0);
                }
                var tuple = new Tuple <UIElement, UIElement>(container, e);
                if (parent == Interface.modConfig.mainConfigList)
                {
                    Interface.modConfig.mainConfigItems.Add(tuple);
                }

                return(tuple);
            }
            return(null);
        }
        void CreateUIElement(Type t, PropertyInfo p, string name)
        {
            DropdownAttribute             dp   = p.GetCustomAttribute <DropdownAttribute>();
            LevelEditorAttribute          le   = p.GetCustomAttribute <LevelEditorAttribute>();
            CurveEditorAttribute          ce   = p.GetCustomAttribute <CurveEditorAttribute>();
            SliderAttribute               sl   = p.GetCustomAttribute <SliderAttribute>();
            FileSelectorAttribute         fsl  = p.GetCustomAttribute <FileSelectorAttribute>();
            HidePropertyAttribute         hp   = p.GetCustomAttribute <HidePropertyAttribute>();
            ColorPickerAttribute          cp   = p.GetCustomAttribute <ColorPickerAttribute>();
            TitleAttribute                ti   = p.GetCustomAttribute <TitleAttribute>();
            TextInputAttribute            tinp = p.GetCustomAttribute <TextInputAttribute>();
            GraphParameterEditorAttribute gpe  = p.GetCustomAttribute <GraphParameterEditorAttribute>();
            ParameterMapEditorAttribute   pme  = p.GetCustomAttribute <ParameterMapEditorAttribute>();
            PromoteAttribute              pro  = p.GetCustomAttribute <PromoteAttribute>();

            //handle very special stuff
            //exposed constant parameter variable names
            if (gpe != null)
            {
                if (node is Graph)
                {
                    Graph g = node as Graph;

                    GraphParameterEditor inp = new GraphParameterEditor(g, g.Parameters);
                    Stack.Children.Add(inp);
                    elementLookup[name] = inp;
                }
            }
            //for graph instance exposed parameters from underlying graph
            else if (pme != null)
            {
                if (node is GraphInstanceNode)
                {
                    GraphInstanceNode gin = node as GraphInstanceNode;
                    ParameterMap      pm  = new ParameterMap(gin.GraphInst, gin.Parameters);
                    Stack.Children.Add(pm);
                    elementLookup[name] = pm;
                }
            }

            string title = name;

            if (ti != null)
            {
                title = ti.Title;
            }

            PropertyInfo op = null;

            //we don't create an element for this one
            //as it is hidden
            if (hp != null)
            {
                return;
            }

            try
            {
                if (ce != null)
                {
                    op = node.GetType().GetProperty(ce.OutputProperty);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }

            if (t.Equals(typeof(Vector4)))
            {
                if (cp != null)
                {
                    PropertyLabel l = null;
                    if (pro != null && node is Node)
                    {
                        l = new PropertyLabel(title, node as Node, name);
                    }
                    else
                    {
                        l       = new PropertyLabel();
                        l.Title = title;
                    }

                    labels.Add(l);
                    Stack.Children.Add(l);

                    ColorSelect cs = new ColorSelect(p, node);
                    Stack.Children.Add(cs);
                    elementLookup[name] = cs;
                }
            }
            else if (t.Equals(typeof(string[])))
            {
                if (dp != null)
                {
                    PropertyLabel l = new PropertyLabel();
                    l.Title = title;
                    labels.Add(l);
                    Stack.Children.Add(l);

                    DropDown inp = new DropDown((string[])p.GetValue(node), node, p, dp.OutputProperty);
                    Stack.Children.Add(inp);
                    elementLookup[name] = inp;
                }
            }
            else if (t.Equals(typeof(bool)))
            {
                PropertyLabel l = null;
                if (pro != null && node is Node)
                {
                    l = new PropertyLabel(title, node as Node, name);
                }
                else
                {
                    l       = new PropertyLabel();
                    l.Title = title;
                }

                labels.Add(l);
                Stack.Children.Add(l);

                ToggleControl tg = new ToggleControl(name, p, node);
                Stack.Children.Add(tg);
                elementLookup[name] = tg;
            }
            else if (t.Equals(typeof(string)))
            {
                if (tinp != null)
                {
                    PropertyLabel l = new PropertyLabel();
                    l.Title = title;
                    labels.Add(l);
                    Stack.Children.Add(l);

                    PropertyInput ip = new PropertyInput(p, node);
                    Stack.Children.Add(ip);
                    elementLookup[name] = ip;
                }
                else if (fsl != null)
                {
                    PropertyLabel l = new PropertyLabel();
                    l.Title = title;
                    labels.Add(l);
                    Stack.Children.Add(l);

                    FileSelector inp = new FileSelector(p, node, fsl.Filter);
                    Stack.Children.Add(inp);
                    elementLookup[name] = inp;
                }
                else if (dp != null)
                {
                    PropertyLabel l = new PropertyLabel();
                    l.Title = title;
                    labels.Add(l);
                    Stack.Children.Add(l);

                    object[] names = dp.Values;
                    DropDown inp   = new DropDown(names, node, p, dp.OutputProperty);
                    Stack.Children.Add(inp);
                    elementLookup[name] = inp;
                }
            }
            if (t.Equals(typeof(float)))
            {
                if (sl != null)
                {
                    PropertyLabel l = null;
                    if (pro != null && node is Node)
                    {
                        l = new PropertyLabel(title, node as Node, name);
                    }
                    else
                    {
                        l       = new PropertyLabel();
                        l.Title = title;
                    }

                    labels.Add(l);
                    Stack.Children.Add(l);

                    NumberSlider inp = new NumberSlider(sl, p, node);
                    Stack.Children.Add(inp);
                    elementLookup[name] = inp;
                }
                else
                {
                    PropertyLabel l = null;
                    if (pro != null && node is Node)
                    {
                        l = new PropertyLabel(title, node as Node, name);
                    }
                    else
                    {
                        l       = new PropertyLabel();
                        l.Title = title;
                    }

                    labels.Add(l);
                    Stack.Children.Add(l);

                    NumberInput inp = new NumberInput(NumberInputType.Float, node, p);
                    Stack.Children.Add(inp);
                    elementLookup[name] = inp;
                }
            }
            else if (t.Equals(typeof(int)))
            {
                if (dp != null)
                {
                    PropertyLabel l = new PropertyLabel();
                    l.Title = title;
                    labels.Add(l);
                    Stack.Children.Add(l);

                    //do a dropdown
                    object[] names = dp.Values;
                    DropDown inp   = new DropDown(names, node, p, dp.OutputProperty);
                    Stack.Children.Add(inp);
                    elementLookup[name] = inp;
                }
                else if (sl != null)
                {
                    PropertyLabel l = null;
                    if (pro != null && node is Node)
                    {
                        l = new PropertyLabel(title, node as Node, name);
                    }
                    else
                    {
                        l       = new PropertyLabel();
                        l.Title = title;
                    }

                    labels.Add(l);
                    Stack.Children.Add(l);

                    NumberSlider inp = new NumberSlider(sl, p, node);
                    Stack.Children.Add(inp);
                    elementLookup[name] = inp;
                }
                else
                {
                    PropertyLabel l = null;
                    if (pro != null && node is Node)
                    {
                        l = new PropertyLabel(title, node as Node, name);
                    }
                    else
                    {
                        l       = new PropertyLabel();
                        l.Title = title;
                    }

                    labels.Add(l);
                    Stack.Children.Add(l);

                    NumberInput inp = new NumberInput(NumberInputType.Int, node, p);
                    Stack.Children.Add(inp);
                    elementLookup[name] = inp;
                }
            }
            else if (t.Equals(typeof(MultiRange)))
            {
                if (le != null)
                {
                    UILevels lv = null;
                    if (node is Node)
                    {
                        Node nd = (Node)node;
                        if (nd.Inputs.Count > 0 && nd.Inputs[0].Input != null)
                        {
                            var    n      = nd.Inputs[0].Input.Node;
                            byte[] result = n.GetPreview(n.Width, n.Height);

                            RawBitmap bit = null;

                            if (result != null)
                            {
                                bit = new RawBitmap(n.Width, n.Height, result);
                            }

                            lv = new UILevels(bit, node, p);
                        }
                        else
                        {
                            lv = new UILevels(null, node, p);
                        }
                        Stack.Children.Add(lv);
                        elementLookup[name] = lv;
                    }
                }
            }
            else if (op != null && ce != null)
            {
                UICurves cv = new UICurves(p, op, node);
                Stack.Children.Add(cv);
                elementLookup[name] = cv;
            }
            else if (t.IsEnum)
            {
                PropertyLabel l = new PropertyLabel();
                l.Title = title;
                labels.Add(l);
                Stack.Children.Add(l);

                string[] names = Enum.GetNames(t);
                DropDown inp   = new DropDown(names, node, p);
                Stack.Children.Add(inp);
                elementLookup[name] = inp;
            }
        }