protected virtual void OnEnable()
        {
            // Reference to the root of the window.
            rootElement = rootVisualElement;

            controlParent = new VisualElement();
            controlParent.Add(toggleRecording = new Button(ToggleRecording)
            {
                text = "--"
            });
            buttonParent = new VisualElement();
            buttonParent.style.flexDirection = new StyleEnum <FlexDirection>(FlexDirection.Row);
            buttonParent.Add(togglePlayback  = new Button(TogglePlayback)
            {
                text = "--"
            });
            buttonParent.Add(playbackPauseGame = new Toggle("Pause game on playback ?")
            {
                viewDataKey = "playbackPauseGame"
            });
            controlParent.Add(new Label(" "));
            controlParent.Add(buttonParent);
            controlParent.Add(playbackPauseGame);
            controlParent.Add(new Label(" "));
            rootElement.Add(controlParent);

            framesParent = new VisualElement();
            var textParent = new VisualElement();

            textParent.style.flexDirection = new StyleEnum <FlexDirection>(FlexDirection.Row);
            textParent.style.alignContent  = new StyleEnum <Align>(Align.Center);
            textParent.Add(recordedFrames  = new Label("Recordered --/--"));
            textParent.Add(previewedFrames = new Label("Previewing --/--"));
            framesParent.Add(textParent);
            var recordParent = new VisualElement();

            recordParent.style.flexDirection = new StyleEnum <FlexDirection>(FlexDirection.Row);
            recordParent.style.alignContent  = new StyleEnum <Align>(Align.Center);
            recordParent.Add(frameCapacity   = new IntegerField("Frame capacity: ")
            {
                value = 50, viewDataKey = "frameCapacity"
            });
            recordParent.Add(showMultipleFrames = new Toggle("Show multiple frames ?")
            {
                viewDataKey = "showMultipleFrames"
            });
            framesParent.Add(recordParent);
            rootElement.Add(framesParent);

            playbackParent = new VisualElement();
            playbackParent.Add(playbackSingle = new SliderInt(0, 100)
            {
                viewDataKey = "playbackSingle"
            });
            playbackParent.Add(playbackMultiple = new MinMaxSlider(0, 100, 0, 100)
            {
                viewDataKey = "playbackMultiple"
            });
            rootElement.Add(playbackParent);
        }
Beispiel #2
0
        void OnGeometryChange(GeometryChangedEvent evt)
        {
            musicToggle = this.Q <Toggle>("music-toggle");
            bool muteMusic = PlayerPrefs.GetInt(PlayerPrefsMuteMusicKey, 0) == 0;

            musicToggle?.SetValueWithoutNotify(!muteMusic);
            SetMuteMusic(muteMusic);
            musicToggle?.RegisterValueChangedCallback(e => OnMusicToggle(e));

            speedSlider = this.Q <SliderInt>("speed-slider");
            speedValue  = this.Q <Label>("speed-value-label");
            int timeScale = (int)Mathf.Round(Time.timeScale);

            // Capping (only matters in the Editor where the time scale can be changed on the project properties
            // but we're being safe).
            if (timeScale > 3)
            {
                timeScale = 3;
            }
            else if (timeScale < 1)
            {
                timeScale = 1;
            }

            if (speedValue != null)
            {
                speedValue.text   = timeScale.ToString();
                speedSlider.value = timeScale;
                speedSlider.RegisterValueChangedCallback(e => OnSpeedSliderChanged(e.newValue));
            }

            this.UnregisterCallback <GeometryChangedEvent>(OnGeometryChange);
        }
Beispiel #3
0
    private void OnEnable()
    {
        accidentParent = GameObject.Find("Accidents");

        root = rootVisualElement;
        VisualTreeAsset quickToolVisualTree = Resources.Load <VisualTreeAsset>("AccidentUI_Main");

        quickToolVisualTree.CloneTree(root);

        VisualElement tmp = root.Query(name: "sphere-toggle");

        tsphd = tmp.Query <Toggle>();

        tmp  = root.Query(name: "cube-toggle");
        tcub = tmp.Query <Toggle>();

        tmp  = root.Query(name: "cylinder-toggle");
        tcyl = tmp.Query <Toggle>();

        tmp       = root.Query(name: "name-field");
        nameField = tmp.Query <TextField>();

        tmp = root.Query(name: "probability-field");
        probabilityField = tmp.Query <SliderInt>();

        tmp            = root.Query(name: "accident-button");
        buttonAccident = tmp.Query <Button>();
        buttonAccident.clickable.clicked += () => InstantiateAccident();
    }
    private void OnEnable()
    {
        var root = rootVisualElement;

        var slider = new SliderInt();

        root.Add(slider);

        var box = new Box();

        box.Add(new Label()
        {
            text = "ラベルの表示"
        });
        box.Add(new Button()
        {
            text = "ボタンです", style = { width = 200 }, name = "button1"
        });

        root.Add(box);

        var button = root.Q <Button>("button1");

        button.clickable.clicked += () => Debug.Log("root.Qを使ってボタンにアクセス出来ます。");
    }
Beispiel #5
0
        VisualElement CreateTextureSettingsView()
        {
            var textureSettings = new VisualElement();

            var t = target as Texture;

            textureSettings.Add(new Label("Texture Settings:"));

            var wrapMode = new EnumField("Wrap Mode", t.wrapMode);

            wrapMode.RegisterValueChangedCallback(e => {
                Undo.RegisterCompleteObjectUndo(t, "Changed wrap mode");
                t.wrapMode = (TextureWrapMode)e.newValue;
            });
            textureSettings.Add(wrapMode);

            var filterMode = new EnumField("Filter Mode", t.filterMode);

            filterMode.RegisterValueChangedCallback(e => {
                Undo.RegisterCompleteObjectUndo(t, "Changed filter mode");
                t.filterMode = (FilterMode)e.newValue;
            });
            textureSettings.Add(filterMode);

            var aniso = new SliderInt("Aniso Level", 1, 9);

            aniso.RegisterValueChangedCallback(e => {
                Undo.RegisterCompleteObjectUndo(t, "Changed aniso level");
                t.anisoLevel = e.newValue;
            });
            textureSettings.Add(aniso);

            return(textureSettings);
        }
Beispiel #6
0
            public EditorIntSliderField(string label, int value, int min, int max, EventCallback <ChangeEvent <int> > callback)
            {
                sliderInt       = new SliderInt(label, min, max, SliderDirection.Horizontal);
                sliderInt.name  = nameof(sliderInt);
                sliderInt.value = value;
                labelElement.StylePadding(0, 8, 0, 0);
                Add(sliderInt);

                integerField      = new IntegerField();
                integerField.name = nameof(integerField);
                integerField.StyleWidth(64);
                integerField.style.paddingLeft = 4;
                integerField.style.marginRight = 0;
                integerField.value             = value;
                integerField.RegisterValueChangedCallback(callback);
                integerField.RegisterValueChangedCallback((callbackChangedSlider) =>
                {
                    sliderInt.value = callbackChangedSlider.newValue;
                });
                sliderInt.Add(integerField);

                sliderInt.RegisterValueChangedCallback((callbackSlide) =>
                {
                    integerField.value = callbackSlide.newValue;
                });
            }
Beispiel #7
0
        public SliderIntControl(int value, int min, int max)
        {
            _slider = new SliderInt(min, max);
            _text   = new IntegerField();

            Setup(value);
        }
Beispiel #8
0
    private void OnEnable()
    {
        riskParent = GameObject.Find("Risks");

        root = rootVisualElement;
        VisualTreeAsset quickToolVisualTree = Resources.Load <VisualTreeAsset>("RiskUI_Main");

        quickToolVisualTree.CloneTree(root);

        VisualElement tmp = root.Query(name: "sphere-toggle");

        tsphd = tmp.Query <Toggle>();

        tmp  = root.Query(name: "cube-toggle");
        tcub = tmp.Query <Toggle>();

        tmp  = root.Query(name: "cylinder-toggle");
        tcyl = tmp.Query <Toggle>();

        tmp       = root.Query(name: "name-field");
        nameField = tmp.Query <TextField>();

        tmp           = root.Query(name: "priority-field");
        priorityField = tmp.Query <SliderInt>();

        tmp        = root.Query(name: "score-field");
        scoreField = tmp.Query <TextField>();

        tmp        = root.Query(name: "risk-button");
        buttonRisk = tmp.Query <Button>();
        buttonRisk.clickable.clicked += () => InstantiateRisk();
    }
        private void InitPreviewToolbar()
        {
            #region Scale
            m_ScaleSlider           = m_RootElement.Q <SliderInt>("scale-slider");
            m_ScaleSlider.lowValue  = kScaleMin;
            m_ScaleSlider.highValue = kScaleMax;
            m_ScaleSlider.value     = m_Scale;
            m_ScaleSlider.RegisterCallback <ChangeEvent <int> >(SetScale);

            m_ScaleValueLabel      = m_RootElement.Q <Label>("scale-value-label");
            m_ScaleValueLabel.text = m_Scale.ToString();

            m_FitToScreenToggle = m_RootElement.Q <ToolbarToggle>("fit-to-screen");
            m_FitToScreenToggle.RegisterValueChangedCallback(FitToScreen);
            m_FitToScreenToggle.SetValueWithoutNotify(m_FitToScreenEnabled);
            #endregion

            #region Rotate
            var          namePostfix = EditorGUIUtility.isProSkin ? "_dark" : "_light";
            const string iconPath    = "packages/com.unity.device-simulator/Editor/icons";

            m_RootElement.Q <Image>("rotate-cw-image").image = AssetDatabase.LoadAssetAtPath <Texture2D>($"{iconPath}/rotate_cw{namePostfix}.png");
            m_RootElement.Q <VisualElement>("rotate-cw").AddManipulator(new Clickable(RotateDeviceCW));

            m_RootElement.Q <Image>("rotate-ccw-image").image = AssetDatabase.LoadAssetAtPath <Texture2D>($"{iconPath}/rotate_ccw{namePostfix}.png");
            m_RootElement.Q <VisualElement>("rotate-ccw").AddManipulator(new Clickable(RotateDeviceCCW));
            #endregion

            // Highlight safe area.
            var highlightSafeAreaToggle = m_RootElement.Q <Toggle>("highlight-safe-area");
            highlightSafeAreaToggle.RegisterValueChangedCallback((evt) => { m_HighlightSafeArea = evt.newValue; OnStateChanged(); });
            highlightSafeAreaToggle.SetValueWithoutNotify(m_HighlightSafeArea);
        }
        public override VisualElement CreateInspectorGUI()
        {
            var rootView = new VisualElement();

            string pathUxml = PackagePath + "Editor/MeshSubdivisionRenderer.uxml";
            string pathUss  = PackagePath + "Editor/MeshSubdivisionRenderer.uss";

            var treeAsset  = AssetDatabase.LoadAssetAtPath <VisualTreeAsset>(pathUxml);
            var styleAsset = AssetDatabase.LoadAssetAtPath <StyleSheet>(pathUss);

            treeAsset.CloneTree(rootView);
            rootView.styleSheets.Add(styleAsset);

            _meshTypeEnum = rootView.Q <EnumField>("enumMeshType");
            _meshTypeEnum.Init(MeshTypeInEditor.Quad);
            _meshTypeEnum.value = GetMeshType((Mesh)_meshProp.objectReferenceValue);
            _meshTypeEnum.RegisterCallback <ChangeEvent <Enum> >(
                (evt) => OnChangeMesh(evt.newValue));

            _meshShadingEnum = rootView.Q <EnumField>("enumMeshShading");
            _meshShadingEnum.Init(MeshShading.Lit);
            _meshShadingEnum.value = GetMeshShading();
            _meshShadingEnum.RegisterCallback <ChangeEvent <Enum> >(
                (evt) => OnChangeMeshShading(evt.newValue));

            _subdInterpEnum = rootView.Q <EnumField>("enumSubdInterp");
            _subdInterpEnum.Init(SubdInterp.None);
            _subdInterpEnum.value = GetSubdInterp();
            _subdInterpEnum.RegisterCallback <ChangeEvent <Enum> >(
                (evt) => OnChangeSubdInterp(evt.newValue));

            _castShadowsToggle       = rootView.Q <Toggle>("toggleCastShadows");
            _castShadowsToggle.value = _castShadowsProp.boolValue;
            _castShadowsToggle.RegisterCallback <ChangeEvent <bool> >(
                (evt) => OnChangeCastShadows(evt.newValue));

            _cullingToggle       = rootView.Q <Toggle>("toggleCulling");
            _cullingToggle.value = _enableCullingProp.boolValue;
            _cullingToggle.RegisterCallback <ChangeEvent <bool> >(
                (evt) => OnChangeDoCulling(evt.newValue));

            _targetPixelSlider       = rootView.Q <SliderInt>("sliderTargetPixel");
            _targetPixelSlider.value = _targetPixelSizeProp.intValue;
            _targetPixelSlider.RegisterCallback <ChangeEvent <int> >(
                (evt) => OnChangeTargetPixelSize(evt.newValue));

            _targetPixelText       = rootView.Q <TextField>("textTargetPixel");
            _targetPixelText.value = _targetPixelSizeProp.intValue.ToString();
            _targetPixelText.RegisterCallback <ChangeEvent <string> >(
                (evt) => OnChangeTargetPixelSize(evt.newValue));

            _debugCameraObject            = rootView.Q <ObjectField>("objectDebugCamera");
            _debugCameraObject.objectType = typeof(Camera);
            _debugCameraObject.value      = _debugCameraProp.objectReferenceValue;
            _debugCameraObject.RegisterCallback <ChangeEvent <UnityEngine.Object> >(
                (evt) => OnChangeDebugCamera(evt.newValue));

            return(rootView);
        }
Beispiel #11
0
    public void OnEnable()
    {
        var root = this.rootVisualElement;

        root.style.paddingTop    = new StyleLength(10f);
        root.style.paddingBottom = new StyleLength(10f);
        root.style.paddingLeft   = new StyleLength(10f);
        root.style.paddingRight  = new StyleLength(10f);

        UnityEngine.UIElements.Toggle hideSliderBool = new Toggle("Hide Slider!");
        root.Add(hideSliderBool);

        var label = new Label(0.ToString());

        root.Add(label);

        SliderInt slider = new SliderInt();

        root.Add(slider);         // Add slider as a child of root.
        slider.RegisterCallback <ChangeEvent <int> >(evt =>
        {
            label.text = evt.newValue.ToString();
        });


        hideSliderBool.RegisterCallback <ChangeEvent <bool> >(evt =>
        {
            // You want to easily hide/show dynamically...
            if (hideSliderBool.value)
            {
                slider.style.display = UnityEngine.UIElements.DisplayStyle.None;
            }
            else
            {
                slider.style.display = UnityEngine.UIElements.DisplayStyle.Flex;
            }
        });


        // Or, once you're done with this element. Make it go away.
        //Button removeSliderButton = new Button(Hej);
        Button removeSliderButton = new Button(() => slider.RemoveFromHierarchy());

        removeSliderButton.text = "Remove Slider?";
        root.Add(removeSliderButton);

        // Add slider again
        Button addSliderButton = new Button(() => root.Add(slider));

        addSliderButton.text = "Add Slider?";
        root.Add(addSliderButton);
    }
Beispiel #12
0
    protected SliderInt addSlider(ref VisualElement dataRoot, int minVal, int maxVal, string label, string bindingPath)
    {
        dataRoot.Add(new Spacer(30));
        var slider      = new SliderInt(minVal, maxVal);
        var sliderLabel = new Label(label + slider.value);

        dataRoot.Add(sliderLabel);
        slider.RegisterCallback <ChangeEvent <int> >((evt) =>
        {
            sliderLabel.text = label + slider.value;
        });
        slider.bindingPath = bindingPath;
        dataRoot.Add(slider);
        return(slider);
    }
Beispiel #13
0
        public PercentSlider(string label) : base(label)
        {
            AddToClassList(s_UssClassName);

            styleSheets.Add(AssetDatabase.LoadAssetAtPath <StyleSheet>(s_UssPath));

            var template = AssetDatabase.LoadAssetAtPath <VisualTreeAsset>(s_UxmlPath);

            template.CloneTree(this);

            visualInput = this.Q(s_VisualInputName);
            mSlider     = this.Q <SliderInt>(s_SliderName);
            mField      = this.Q <IntegerField>(s_FieldName);

            mSlider.RegisterValueChangedCallback(OnSubFieldValueChange);
            mField.RegisterValueChangedCallback(OnSubFieldValueChange);
        }
Beispiel #14
0
    public void OnEnable()
    {
        VisualElement root = rootVisualElement;

        // Import UXML
        var           visualTree    = AssetDatabase.LoadAssetAtPath <VisualTreeAsset>("Assets/Editor/Sample4.uxml");
        var           styleSheet    = AssetDatabase.LoadAssetAtPath <StyleSheet>("Assets/Editor/Sample4.uss");
        VisualElement labelFromUXML = visualTree.CloneTree();

        labelFromUXML.styleSheets.Add(styleSheet);
        root.Add(labelFromUXML);

        this.label  = root.Q <Label>("label");
        this.image  = root.Q <Image>("image");
        this.slider = root.Q <SliderInt>("slider");

        slider.RegisterValueChangedCallback <int>(Slider_ValueChanged);
    }
Beispiel #15
0
        public Slider(int val, int min, int max, EventCallback <int> cb)
        {
            Callback = cb;
            Value    = val;

            contentContainer.AddToClassList("bounded-int");
            contentContainer.AddToClassList("range");

            Range = new SliderInt {
                highValue = max,
                lowValue  = min,
                value     = val
            };

            Min = new IntegerField {
                value = min
            };
            Current = new IntegerField {
                value = val
            };
            Max = new IntegerField {
                value = max
            };

            Min.AddToClassList("min-value");
            Current.AddToClassList("current-value");
            Max.AddToClassList("max-value");

            var Fields = new VisualElement();

            Fields.AddToClassList("input-fields");

            Fields.Add(Min);
            Fields.Add(Current);
            Fields.Add(Max);

            contentContainer.Add(Range);
            contentContainer.Add(Fields);

            Range.RegisterValueChangedCallback(CurrentChanged);
            Min.RegisterValueChangedCallback(MinChanged);
            Current.RegisterValueChangedCallback(CurrentChanged);
            Max.RegisterValueChangedCallback(MaxChanged);
        }
Beispiel #16
0
        VisualElement CreateTextureSettingsView()
        {
            var textureSettings = new VisualElement();

            var t = target as Texture;

            var settingsLabel = new Label("Texture Settings");

            settingsLabel.AddToClassList("Header");
            textureSettings.Add(settingsLabel);

            var settings = new VisualElement();

            settings.AddToClassList("Indent");
            textureSettings.Add(settings);

            var wrapMode = new EnumField("Wrap Mode", t.wrapMode);

            wrapMode.RegisterValueChangedCallback(e => {
                Undo.RegisterCompleteObjectUndo(t, "Changed wrap mode");
                t.wrapMode = (TextureWrapMode)e.newValue;
                graph.settings.wrapMode = (OutputWrapMode)t.wrapMode;
            });
            settings.Add(wrapMode);

            var filterMode = new EnumField("Filter Mode", t.filterMode);

            filterMode.RegisterValueChangedCallback(e => {
                Undo.RegisterCompleteObjectUndo(t, "Changed filter mode");
                t.filterMode = (FilterMode)e.newValue;
                graph.settings.filterMode = (OutputFilterMode)t.filterMode;
            });
            settings.Add(filterMode);

            var aniso = new SliderInt("Aniso Level", 1, 9);

            aniso.RegisterValueChangedCallback(e => {
                Undo.RegisterCompleteObjectUndo(t, "Changed aniso level");
                t.anisoLevel = e.newValue;
            });
            settings.Add(aniso);

            return(textureSettings);
        }
Beispiel #17
0
        public NodeTexturePreview(MixtureNodeView view)
        {
            nodeView    = view;
            graphView   = nodeView.owner as MixtureGraphView;
            previewRoot = Resources.Load <VisualTreeAsset>("UI Blocks/Preview").CloneTree();
            Add(previewRoot);

            // Load additional resources:
            arrowUp   = Resources.Load <Texture2D>("Collapse-Down");
            arrowDown = Resources.Load <Texture2D>("Collapse-Up");

            // Init all preview components:
            previewContainer = previewRoot.Q("PreviewContainer");
            rgb = previewRoot.Q("ToggleRGB") as Toggle;
            r   = previewRoot.Q("ToggleR") as Toggle;
            g   = previewRoot.Q("ToggleG") as Toggle;
            b   = previewRoot.Q("ToggleB") as Toggle;
            a   = previewRoot.Q("ToggleA") as Toggle;

            mipmapSlider      = previewRoot.Q("MipMapSlider") as SliderInt;
            mipmapInputs      = previewRoot.Q("MipMapInput") as VisualElement;
            currentMipIndex   = previewRoot.Q("MipMapNumberText") as Label;
            sliceInputs       = previewRoot.Q("SliceInputs");
            sliceSlider       = previewRoot.Q("SliceSlider") as SliderInt;
            currentSliceIndex = previewRoot.Q("SliceNumber") as IntegerField;
            imageInfo         = previewRoot.Q("ImageInfo");
            textureInfo       = previewRoot.Q("ImageInfoText") as Label;
            collapseButton    = previewRoot.Q("PreviewFoldout") as Button;
            previewImage      = previewRoot.Q("PreviewImage");

            previewImage.style.width  = 200;
            previewImage.style.height = 200;

            previewImage.Add(new IMGUIContainer(DrawPreviewImage));

            // TODO: determine image size rect to fit the node

            collapseButton.clicked += PreviewColapse;

            // TODO: all events, preview shader ect...
        }
Beispiel #18
0
        public override VisualElement CreatePropertyGUI(SerializedProperty property)
        {
            RangeAttribute range = (RangeAttribute)attribute;

            if (property.propertyType == SerializedPropertyType.Float)
            {
                var slider = new Slider(property.displayName, range.min, range.max);
                slider.bindingPath    = property.propertyPath;
                slider.showInputField = true;
                return(slider);
            }
            else if (property.propertyType == SerializedPropertyType.Integer)
            {
                var intSlider = new SliderInt(property.displayName, (int)range.min, (int)range.max);
                intSlider.bindingPath    = property.propertyPath;
                intSlider.showInputField = true;
                return(intSlider);
            }

            return(new Label(s_InvalidTypeMessage));
        }
        public override void OnOpen()
        {
            editorWindow.rootVisualElement.AddStyleSheetPath("PAAnimationOptions");
            editorWindow.rootVisualElement.name = "Window";

            editorWindow.rootVisualElement.Add(new Label("Name"));
            var animationName = new TextField();

            animationName.value = _animation.name;
            animationName.RegisterValueChangedCallback((e) =>
            {
                _animation.name = e.newValue;
                _workspace.RefreshAnimationList();
            });
            editorWindow.rootVisualElement.Add(animationName);

            editorWindow.rootVisualElement.Add(new Label("Frame Rate"));
            var animationFPS = new SliderInt(1, 30);

            animationFPS.value = _animation.fps;
            animationFPS.RegisterValueChangedCallback((e) => _animation.fps = e.newValue);
            editorWindow.rootVisualElement.Add(animationFPS);
        }
        internal override void Apply(VisualElement container)
        {
            /// <sample>
            // Get a reference to the slider from UXML and assign it its value.
            var uxmlSlider = container.Q <SliderInt>("the-uxml-slider");

            uxmlSlider.value = 42;

            // Create a new slider, disable it, and give it a style class.
            var csharpSlider = new SliderInt("C# Slider", 0, 100);

            csharpSlider.SetEnabled(false);
            csharpSlider.AddToClassList("some-styled-slider");
            csharpSlider.value = uxmlSlider.value;
            container.Add(csharpSlider);

            // Mirror value of uxml slider into the C# field.
            uxmlSlider.RegisterCallback <ChangeEvent <int> >((evt) =>
            {
                csharpSlider.value = evt.newValue;
            });
            /// </sample>
        }
Beispiel #21
0
        void CreateTexturePreviewImGUI(VisualElement previewContainer, MixtureNode node, int currentSlice)
        {
            // Add slider for texture 3D
            if (node.previewTexture.dimension == TextureDimension.Tex3D)
            {
                var previewSliceIndex = new SliderInt(0, TextureUtils.GetSliceCount(node.previewTexture) - 1)
                {
                    label = "Slice",
                    value = currentSlice,
                };
                previewSliceIndex.RegisterValueChangedCallback((ChangeEvent <int> a) => {
                    currentSlice = a.newValue;
                });
                previewContainer.Add(previewSliceIndex);
            }

            var previewImageSlice = new IMGUIContainer(() => {
                if (node.previewTexture == null)
                {
                    return;
                }

                DrawPreviewCommonSettings(node.previewTexture);

                Rect previewRect = GetPreviewRect(node.previewTexture);
                DrawImGUIPreview(node, previewRect, currentSlice);

                DrawTextureInfoHover(previewRect, node.previewTexture);
            });

            // Force the ImGUI preview to refresh
            EditorApplication.update -= previewImageSlice.MarkDirtyRepaint;
            EditorApplication.update += previewImageSlice.MarkDirtyRepaint;

            previewContainer.Add(previewImageSlice);
        }
Beispiel #22
0
        public void OnEnable()
        {
            VisualElement root = rootVisualElement;
            VisualElement vt   = Resources.Load <VisualTreeAsset>("Editor/SDFWizardMarkup").Instantiate();

            vt.styleSheets.Add(Resources.Load <StyleSheet>("Editor/SDFWizardStyle"));
            root.Add(vt);
            Label        dLabel         = vt.Q <Label>         (null, "dLabel");
            Image        dropBox        = vt.Q <Image>         ("DropBox");
            SliderInt    sizeSlider     = vt.Q <SliderInt>     ("SizeSlider");
            IntegerField sizeField      = vt.Q <IntegerField>  ("SizeField");
            Slider       tresholdSlider = vt.Q <Slider>        ("TresholdSlider");
            FloatField   tresholdField  = vt.Q <FloatField>    ("TresholdField");
            SliderInt    sampleSlider   = vt.Q <SliderInt>     ("SampleSlider");
            IntegerField sampleField    = vt.Q <IntegerField>  ("SampleField");
            EnumField    channelSelect  = vt.Q <EnumField>     ("ChannelSelect");
            Box          channelDisplay = vt.Q <Box>           ("ChannelDisplay");
            EnumField    modeSelect     = vt.Q <EnumField>     ("RenderingSelect");
            EnumField    tilingSelect   = vt.Q <EnumField>     ("TilingSelect");

            channelSelect.Init(WizardUtils.ColorChannel.Alpha);
            modeSelect.Init(SDFConverter.RenderingMode.DistanceOnly);
            tilingSelect.Init(TextureWrapMode.Repeat);
            bool validated = false;

            dropBox.RegisterCallback <DragEnterEvent>((e) =>
            {
                foreach (var item in DragAndDrop.objectReferences)
                {
                    if (item.GetType() == typeof(Texture2D))
                    {
                        validated = true;
                    }
                }
                dropBox.tintColor  = validated ? new Color(.6f, .94f, .2f) : new Color(.94f, .3f, .2f);
                dLabel.style.color = validated ? new Color(.6f, .94f, .2f) : new Color(.94f, .3f, .2f);
            });

            dropBox.RegisterCallback <DragUpdatedEvent>((e) =>
            {
                if (validated)
                {
                    DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
                }
            });

            dropBox.RegisterCallback <DragPerformEvent>((e) =>
            {
                if (validated)
                {
                    for (int i = 0; i < DragAndDrop.objectReferences.Length; i++)
                    {
                        var item    = (UnityEngine.Object)DragAndDrop.objectReferences[i];
                        string path = DragAndDrop.paths[i];
                        if (item.GetType() == typeof(Texture2D))
                        {
                            string newPath    = path.Substring(0, path.LastIndexOf(".")) + "_SDF.png";
                            string systemPath = Application.dataPath.Substring(0, Application.dataPath.Length - 6) + newPath;
                            var texture       = item as Texture2D;
                            texture.wrapMode  = (TextureWrapMode)tilingSelect.value;
                            var outData       = SDFConverter.RenderSDF(texture, sizeField.value, tresholdField.value, sampleField.value, channelSelect.value, modeSelect.value);
                            System.IO.File.WriteAllBytes(systemPath, outData.EncodeToPNG());
                            AssetDatabase.Refresh();
                            var importer         = (TextureImporter)AssetImporter.GetAtPath(newPath);
                            var importerSettings = new TextureImporterSettings();
                            ((TextureImporter)AssetImporter.GetAtPath(path)).ReadTextureSettings(importerSettings);
                            importer.SetTextureSettings(importerSettings);
                            importer.sRGBTexture       &= modeSelect.value.Equals(SDFConverter.RenderingMode.RGBDistance);
                            importer.textureCompression = TextureImporterCompression.Uncompressed;
                            importer.SaveAndReimport();
                            AssetDatabase.ImportAsset(newPath);
                        }
                    }
                }
            });

            dropBox.RegisterCallback <DragExitedEvent>((e) =>
            {
                validated          = false;
                dropBox.tintColor  = Color.white;
                dLabel.style.color = Color.white;
            });

            dropBox.RegisterCallback <DragLeaveEvent>((e) =>
            {
                validated          = false;
                dropBox.tintColor  = Color.white;
                dLabel.style.color = Color.white;
            });

            sizeSlider.RegisterCallback <ChangeEvent <int> >((e) =>
            {
                sizeField.value = 2 << e.newValue;
            });

            sizeField.RegisterCallback <ChangeEvent <int> >((e) =>
            {
                int c = 0;
                int v = e.newValue;
                while (v > 2)
                {
                    c++; v >>= 1;
                }
                sizeSlider.value = c;
                sizeField.value  = 2 << c;
            });

            tresholdSlider.RegisterCallback <ChangeEvent <float> >((e) =>
            {
                tresholdField.value = 1f - e.newValue;
            });

            tresholdField.RegisterCallback <ChangeEvent <float> >((e) =>
            {
                tresholdSlider.value = 1f - e.newValue;
            });
            sampleSlider.RegisterCallback <ChangeEvent <int> >((e) =>
            {
                sampleField.value = e.newValue;
            });

            sampleField.RegisterCallback <ChangeEvent <int> >((e) =>
            {
                sampleSlider.value = e.newValue;
            });

            channelSelect.RegisterCallback <ChangeEvent <Enum> >((e) =>
            {
                switch (e.newValue)
                {
                case WizardUtils.ColorChannel.Red:
                    channelDisplay.style.backgroundColor = new Color(.94f, .3f, .2f);
                    break;

                case WizardUtils.ColorChannel.Green:
                    channelDisplay.style.backgroundColor = new Color(.6f, .94f, .2f);
                    break;

                case WizardUtils.ColorChannel.Blue:
                    channelDisplay.style.backgroundColor = new Color(.2f, .6f, .94f);
                    break;

                case WizardUtils.ColorChannel.Alpha:
                    channelDisplay.style.backgroundColor = Color.grey;
                    break;

                default:
                    channelDisplay.style.backgroundColor = Color.white;
                    break;
                }
            });
        }
    void OnEnable()
    {
        rootVisualElement.Clear();

        var PREVIEW = new Image();
        {
            PREVIEW.image          = _texture;
            PREVIEW.scaleMode      = ScaleMode.ScaleAndCrop;
            PREVIEW.style.flexGrow = 1f;
        }

        var INVERT = new VisualElement();

        SetupStyle(INVERT);
        var BUTTON_INVERT = new Button(() => InvertColors(_texture));

        {
            BUTTON_INVERT.SetEnabled(_texture != null);
            BUTTON_INVERT.text = "Invert Colors";
        }
        INVERT.Add(BUTTON_INVERT);

        var EDGES = new VisualElement();

        SetupStyle(EDGES);
        var BUTTON_EDGES = new Button(() => EdgeDetect(_texture));

        {
            BUTTON_EDGES.SetEnabled(_texture != null);
            BUTTON_EDGES.text = "Edge Detect";
        }
        EDGES.Add(BUTTON_EDGES);

        var BOX_BLUR = new VisualElement();

        SetupStyle(BOX_BLUR, 46);
        var SLIDER_BOX_BLUR = new SliderInt(1, 100);
        {
            SLIDER_BOX_BLUR.value = 10;
        }
        var BUTTON_BOX_BLUR = new Button(() => BoxBlur(_texture, SLIDER_BOX_BLUR.value));

        {
            BUTTON_BOX_BLUR.SetEnabled(_texture != null);
            BUTTON_BOX_BLUR.text = "Box Blur";
        }
        BOX_BLUR.Add(BUTTON_BOX_BLUR);
        BOX_BLUR.Add(SLIDER_BOX_BLUR);

        var GAUSSIAN_BLUR = new VisualElement();

        SetupStyle(GAUSSIAN_BLUR, 46);
        var SLIDER_GAUSSIAN_BLUR = new SliderInt(1, 100);
        {
            SLIDER_GAUSSIAN_BLUR.value = 10;
        }
        var BUTTON_GAUSSIAN_BLUR = new Button(() => GaussianBlur(_texture, SLIDER_GAUSSIAN_BLUR.value));

        {
            BUTTON_GAUSSIAN_BLUR.SetEnabled(_texture != null);
            BUTTON_GAUSSIAN_BLUR.text = "Gaussian Blur";
        }
        GAUSSIAN_BLUR.Add(BUTTON_GAUSSIAN_BLUR);
        GAUSSIAN_BLUR.Add(SLIDER_GAUSSIAN_BLUR);

        var GRAYSCALE = new VisualElement();

        SetupStyle(GRAYSCALE);
        var BUTTON_GRAYSCALE = new Button(() => Grayscale(_texture));

        {
            BUTTON_GRAYSCALE.SetEnabled(_texture != null);
            BUTTON_GRAYSCALE.text = "Grayscale";
        }
        GRAYSCALE.Add(BUTTON_GRAYSCALE);

        var FIELD = new ObjectField();

        {
            FIELD.objectType = typeof(Texture2D);
            FIELD.value      = _texture;
            FIELD.RegisterValueChangedCallback(
                (e) =>
            {
                var newTexture = e.newValue as Texture2D;
                if (newTexture != null)
                {
                    if (!newTexture.isReadable)
                    {
                        UnityEditor.EditorUtility.DisplayDialog(
                            "Texture is not readable",
                            $"Texture '{newTexture.name}' is not readable. Choose different texture or enable \"Read/Write Enabled\" for needs of this demonstration.",
                            "OK"
                            );
                        return;
                    }
                    _texture      = newTexture;
                    PREVIEW.image = newTexture;

                    bool b = true;
                    PREVIEW.SetEnabled(b);
                    BUTTON_INVERT.SetEnabled(b);
                    BUTTON_EDGES.SetEnabled(b);
                    BUTTON_BOX_BLUR.SetEnabled(b);
                    BUTTON_GAUSSIAN_BLUR.SetEnabled(b);
                    BUTTON_GRAYSCALE.SetEnabled(b);
                }
                else
                {
                    _texture      = null;
                    PREVIEW.image = null;

                    bool b = false;
                    PREVIEW.SetEnabled(b);
                    BUTTON_INVERT.SetEnabled(b);
                    BUTTON_EDGES.SetEnabled(b);
                    BUTTON_BOX_BLUR.SetEnabled(b);
                    BUTTON_GAUSSIAN_BLUR.SetEnabled(b);
                    BUTTON_GRAYSCALE.SetEnabled(b);
                }
            }
                );
        }

        // add elemenets to root:
        rootVisualElement.Add(FIELD);
        rootVisualElement.Add(PREVIEW);
        rootVisualElement.Add(INVERT);
        rootVisualElement.Add(EDGES);
        rootVisualElement.Add(BOX_BLUR);
        rootVisualElement.Add(GAUSSIAN_BLUR);
        rootVisualElement.Add(GRAYSCALE);
    }
Beispiel #24
0
    public void OnEnable()
    {
        VisualElement root = this.rootVisualElement;

        root.style.flexDirection = FlexDirection.Row;
        root.style.paddingTop    = 20;
        root.style.paddingBottom = 20;



        VisualElement gameRoot = new VisualElement()
        {
            style =
            {
                width        = width * 0.22f,
                paddingRight =            20,
                paddingLeft  = 20
            }
        };
        VisualElement mapRoot = new VisualElement()
        {
            style =
            {
                alignContent = Align.Center,
                width        = width * 0.56f
            }
        };
        VisualElement levelRoot = new VisualElement()
        {
            style =
            {
                width        = width * 0.22f,
                paddingLeft  =            20,
                paddingRight = 20
            }
        };

        root.Add(gameRoot);
        root.Add(mapRoot);
        root.Add(levelRoot);

        //game root
        {
            gameRoot.Add(new Label("Choose a Gauntlet Game:"));
            gameData            = new ObjectField();
            gameData.objectType = typeof(GauntletGame);
            gameRoot.Add(gameData);

            gameData.RegisterCallback <ChangeEvent <UnityEngine.Object> >((evt) =>
            {
                var change       = (evt.target as ObjectField).value;
                game             = change as GauntletGame;
                levelData.value  = null;
                playerData.value = null;
                rebindLevelListView();
            });

            Button createGameButton = new Button(() =>
            {
                var newGame = CreateInstance <GauntletGame>();
                var path    = "Assets/Resources/Gauntlet/GameData";
                AssetDatabase.CreateAsset(newGame, AssetDatabase.GenerateUniqueAssetPath(path + "/GameData-00.asset"));
                EditorUtility.SetDirty(newGame);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
                gameData.value = newGame;
            });
            createGameButton.text = "Create New Game";
            gameRoot.Add(createGameButton);


            Button saveDataButton = new Button(() =>
            {
                if (game != null)
                {
                    var path = EditorUtility.OpenFolderPanel("Export Game Data", "", "");

                    if (path == null)
                    {
                        return;
                    }

                    if (path.Length != 0)
                    {
                        game.saveGameData(path);
                    }
                }
            });
            saveDataButton.text = "Save Game Data";
            gameRoot.Add(saveDataButton);

            VisualElement levelListDataRoot = new VisualElement()
            {
                style =
                {
                    flexDirection = FlexDirection.Row,
                    paddingTop    =                20,
                    paddingBottom =                40,
                    height        = 300
                }
            };

            VisualElement levelListRoot = new VisualElement()
            {
                style =
                {
                    flexGrow = 0.75f
                }
            };

            VisualElement levelButtonsRoot = new VisualElement()
            {
                style =
                {
                    flexGrow       =          0.25f,
                    justifyContent = Justify.Center,
                    paddingLeft    =             10,
                    paddingRight   = 10
                }
            };

            levelListDataRoot.Add(levelListRoot);
            levelListDataRoot.Add(levelButtonsRoot);
            gameRoot.Add(levelListDataRoot);

            Label levelLabel = new Label("List of Levels:");
            levelListRoot.Add(levelLabel);
            levelListRoot.Add(createLevelListView());

            Button upButton = new Button(() =>
            {
                if (game != null)
                {
                    int newIndex = game.changeLevelOrder(levelListView.selectedIndex, true);
                    rebindLevelListView();
                    levelListView.selectedIndex = newIndex;
                }
            });
            Button downButton = new Button(() =>
            {
                if (game != null)
                {
                    int newIndex = game.changeLevelOrder(levelListView.selectedIndex, false);
                    rebindLevelListView();
                    levelListView.selectedIndex = newIndex;
                }
            });
            Button removeButton = new Button(() =>
            {
                if (game != null && levelListView.selectedIndex >= 0)
                {
                    game.levels.RemoveAt(levelListView.selectedIndex);
                    rebindLevelListView();
                }
            });
            Button editButton = new Button(() =>
            {
                if (game != null && levelListView.selectedIndex >= 0)
                {
                    levelData.value = game.levels[levelListView.selectedIndex];
                }
            });
            upButton.text     = "Move Up";
            downButton.text   = "Move Down";
            removeButton.text = "Remove";
            editButton.text   = "Edit";
            levelButtonsRoot.Add(upButton);
            levelButtonsRoot.Add(downButton);
            levelButtonsRoot.Add(removeButton);
            levelButtonsRoot.Add(editButton);


            gameRoot.Add(new Label("Choose a Player for this Game:"));
            playerData            = new ObjectField();
            playerData.objectType = typeof(Player);
            gameRoot.Add(playerData);

            playerData.RegisterCallback <ChangeEvent <UnityEngine.Object> >((evt) =>
            {
                var change = (evt.target as ObjectField).value;
                if (game)
                {
                    game.playerObject = change as Player;
                }
            });

            // Level
            gameRoot.Add(new Label("Choose a Level to edit:"));
            levelData            = new ObjectField();
            levelData.objectType = typeof(GauntletLevel);
            gameRoot.Add(levelData);
            gameRoot.Add(new Label("Level Name:"));

            levelData.RegisterCallback <ChangeEvent <UnityEngine.Object> >((evt) =>
            {
                var change = (evt.target as ObjectField).value;
                level      = change as GauntletLevel;
                UpdateLevelBinding();
                tileMap.createGrid(level);
            });

            var levelName = new TextField();
            levelName.bindingPath = "levelName";
            gameRoot.Add(levelName);
            Button addLevelButton = new Button(() =>
            {
                if (game != null && level != null)
                {
                    game.levels.Add(level);
                    EditorUtility.SetDirty(game);
                    AssetDatabase.SaveAssets();
                    AssetDatabase.Refresh();
                    rebindLevelListView();
                }
            });
            addLevelButton.text = "Add Level To Game";
            gameRoot.Add(addLevelButton);

            // New Level
            Button newLevelButton = new Button(() =>
            {
                var newLevel = CreateInstance <GauntletLevel>();
                newLevel.initialize("TestLevel", levelSizeSlider.value, 570);
                var path = "Assets/Resources/Gauntlet/LevelData";
                AssetDatabase.CreateAsset(newLevel, AssetDatabase.GenerateUniqueAssetPath(path + "/LevelData-00.asset"));
                EditorUtility.SetDirty(newLevel);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
                levelData.value = newLevel;
            });

            newLevelButton.text            = "Create New Level";
            newLevelButton.style.marginTop = 40;
            gameRoot.Add(newLevelButton);

            levelSizeSlider       = new SliderInt(5, 35);
            levelSizeSlider.value = 20;
            var levelSizeLabel = new Label("Size of New Level:" + levelSizeSlider.value);
            gameRoot.Add(levelSizeLabel);
            levelSizeSlider.RegisterCallback <ChangeEvent <int> >((evt) =>
            {
                levelSizeLabel.text = "Size of New Level:  " + evt.newValue;
            });

            gameRoot.Add(levelSizeSlider);
        }


        tileMap             = new TileMap();
        tileMap.levelEditor = this;
        mapRoot.Add(tileMap.gridContainer);


        // Level Root
        levelRoot.Add(new Label("Choose a prefab to place:"));
        MapPrefabTypesField = new EnumField(MapPrefabTypes.GroundTile);
        MapPrefabTypesField.RegisterCallback <ChangeEvent <Enum> >((evt) =>
        {
            rebindPrefabListView();
        });
        levelRoot.Add(MapPrefabTypesField);
        //levelRoot.Add(createSpriteList());
        levelRoot.Add(createMapTileList());

        var eraseToggle = new Toggle("Erase Mode");

        eraseToggle.RegisterCallback <ChangeEvent <bool> >((evt) =>
        {
            tileMap.eraseMode = evt.newValue;
        });
        levelRoot.Add(eraseToggle);
        var timeLimit      = new SliderInt(60, 600);
        var timeLimitLabel = new Label("Time Limit:   " + timeLimit.value + " seconds");

        levelRoot.Add(timeLimitLabel);
        timeLimit.RegisterCallback <ChangeEvent <int> >((evt) =>
        {
            timeLimitLabel.text = "Time Limit:   " + evt.newValue + " seconds";
        });
        timeLimit.bindingPath = "timeLimit";
        levelRoot.Add(timeLimit);
        levelRoot.Add(new Label("Current Layer:"));

        EnumField mapLayers = new EnumField(MapLayers.Layer1);

        mapLayers.RegisterCallback <ChangeEvent <Enum> >((evt) =>
        {
            var change = evt.newValue;
            tileMap.changeLayer(Convert.ToInt32(change));
        });

        levelRoot.Add(mapLayers);
        levelRoot.Add(new Label("Viewable layers in editor:"));
        var layer1Toggle = new Toggle("Layer 1")
        {
            value = true
        };
        var layer2Toggle = new Toggle("Layer 2")
        {
            value = true
        };
        var layer3Toggle = new Toggle("Layer 3")
        {
            value = true
        };

        layer1Toggle.RegisterCallback <ChangeEvent <bool> >((evt) =>
        {
            tileMap.layersOn[0] = evt.newValue;
        });

        layer2Toggle.RegisterCallback <ChangeEvent <bool> >((evt) =>
        {
            tileMap.layersOn[1] = evt.newValue;
        });

        layer3Toggle.RegisterCallback <ChangeEvent <bool> >((evt) =>
        {
            tileMap.layersOn[2] = evt.newValue;
        });

        levelRoot.Add(layer1Toggle);
        levelRoot.Add(layer2Toggle);
        levelRoot.Add(layer3Toggle);


        levelRoot.Add(new Label("Type of asset to create/edit:"));
        EnumField prefabEnums = new EnumField(PrefabTypes.GroundTile);

        levelRoot.Add(prefabEnums);
        Button createEditPrefabButton = new Button(() =>
        {
            switch (prefabEnums.value)
            {
            case PrefabTypes.Player:
                {
                    assetWindow = PrefabEditor.createWindow <GauntletPlayerEditor>(_window, "Player Editor");
                    break;
                }

            case PrefabTypes.Enemy:
                {
                    assetWindow = PrefabEditor.createWindow <GauntletEnemyEditor>(_window, "Enemy Editor");
                    break;
                }

            case PrefabTypes.GroundTile:
                {
                    assetWindow = PrefabEditor.createWindow <GauntletGroundTileEditor>(_window, "Ground Tile Editor");
                    break;
                }

            case PrefabTypes.SpawnFactory:
                {
                    assetWindow = PrefabEditor.createWindow <GauntletSpawnFactoryEditor>(_window, "Spawn Factory Editor");
                    break;
                }

            case PrefabTypes.Projectile:
                {
                    assetWindow = PrefabEditor.createWindow <GauntletProjectileEditor>(_window, "Projectile Editor");
                    break;
                }

            case PrefabTypes.Item:
                {
                    assetWindow = PrefabEditor.createWindow <GauntletItemEditor>(_window, "Item Editor");
                    break;
                }

            case PrefabTypes.Portal:
                {
                    assetWindow = PrefabEditor.createWindow <GauntletPortalEditor>(_window, " Portal Editor");
                    break;
                }

            case PrefabTypes.SpawnPoint:
                {
                    assetWindow = PrefabEditor.createWindow <GauntletSpawnPointEditor>(_window, "Spawn Point Editor");
                    break;
                }

            default: break;
            }
        });

        createEditPrefabButton.text = "Create/Edit Prefab";
        levelRoot.Add(createEditPrefabButton);
    }
Beispiel #25
0
        void CreateUIElements()
        {
            var titleRow = new VisualElement()
            {
                style =
                {
                    flexDirection  = FlexDirection.Row,
                    flexShrink     =                0f,
                    justifyContent = Justify.SpaceBetween
                }
            };

            m_VisualElementContainer.Add(new Label("VisualElements Container"));


            var curveX           = AnimationCurve.Linear(0, 0, 1, 0);
            var popupFieldValues = new List <SomeClass>
            {
                new SomeClass("First Class Value"),
                new SomeClass("Second Value"),
                new SomeClass("Another Value"),
                new SomeClass("Another Value with a very lonnnnnnnnnnnnnnnnnnnnnnnnng text to make sure this is really overflowing the popup field.")
            };
            var maskFieldOptions = new List <string>(m_MaskFieldOptions);


            m_VisualElementContainer.Add(m_IntegerField  = new IntegerField());
            m_VisualElementContainer.Add(m_LongField     = new LongField());
            m_VisualElementContainer.Add(m_FloatField    = new FloatField());
            m_VisualElementContainer.Add(m_DoubleField   = new DoubleField());
            m_VisualElementContainer.Add(m_EnumField     = new EnumField(EnumValues.Two));
            m_VisualElementContainer.Add(m_TextField     = new TextField());
            m_VisualElementContainer.Add(m_PasswordField = new TextField()
            {
                isPasswordField = true, maskChar = '*'
            });
            m_VisualElementContainer.Add(m_Vector3Field      = new Vector3Field());
            m_VisualElementContainer.Add(m_Vector3IntField   = new Vector3IntField());
            m_VisualElementContainer.Add(m_Vector2Field      = new Vector2Field());
            m_VisualElementContainer.Add(m_ColorField        = new ColorField());
            m_VisualElementContainer.Add(m_ObjectFieldCamera = new ObjectField()
            {
                objectType = typeof(Camera)
            });
            m_VisualElementContainer.Add(m_ObjectFieldGameObject = new ObjectField()
            {
                objectType = typeof(GameObject)
            });
            m_VisualElementContainer.Add(m_CurveField = new CurveField()
            {
                value = curveX
            });
            m_VisualElementContainer.Add(m_CurveFieldMesh = new CurveField()
            {
                value = curveX, renderMode = CurveField.RenderMode.Mesh
            });
            m_VisualElementContainer.Add(m_PopupField        = new PopupField <SomeClass>(popupFieldValues, popupFieldValues[1]));
            m_VisualElementContainer.Add(m_RectField         = new RectField());
            m_VisualElementContainer.Add(m_BoundsField       = new BoundsField());
            m_VisualElementContainer.Add(m_ToggleField       = new Toggle());
            m_VisualElementContainer.Add(m_MaskField         = new MaskField(maskFieldOptions, 6));
            m_VisualElementContainer.Add(m_LayerField        = new LayerField());
            m_VisualElementContainer.Add(m_TagField          = new TagField());
            m_VisualElementContainer.Add(m_MinMaxSliderField = new MinMaxSlider(5, 10, 0, 125));
            m_VisualElementContainer.Add(m_Slider            = new Slider(2, 8));
            m_VisualElementContainer.Add(m_SliderInt         = new SliderInt(11, 23));

            var buttonRow = new VisualElement()
            {
                style =
                {
                    flexDirection = FlexDirection.Row,
                    flexShrink    =                0f,
                }
            };

            buttonRow.Add(new Button()
            {
                text = k_ButtonLeftTitle, style = { flexGrow = 1 }
            });
            buttonRow.Add(new Button()
            {
                text = k_ButtonRightTitle, style = { flexGrow = 1 }
            });
            m_VisualElementContainer.Add(buttonRow);

            m_VisualElementContainer.Add(new Button()
            {
                text = k_ButtonTopTitle
            });
            m_VisualElementContainer.Add(new Button()
            {
                text = k_ButtonBottomTitle
            });

            m_VisualElementContainer.Add(m_ColorField1        = new ColorField());
            m_VisualElementContainer.Add(m_LayerMaskField     = new LayerMaskField(0));
            m_VisualElementContainer.Add(m_MultiLineTextField = new TextField()
            {
                multiline = true
            });

            m_VisualElementContainer.Add(m_SliderProgressBar = new SliderInt());
            m_VisualElementContainer.Add(m_ProgressBar       = new ProgressBar());

            m_ProgressBar.title           = nameof(ProgressBar);
            m_SliderProgressBar.lowValue  = 0;
            m_SliderProgressBar.highValue = 100;

            m_SliderProgressBar.bindingPath = nameof(SliderProgressTestObject.exampleValue);
            m_ProgressBar.bindingPath       = nameof(SliderProgressTestObject.exampleValue);

            m_SliderProgressBar.Bind(SliderProgressTestSO);
            m_ProgressBar.Bind(SliderProgressTestSO);
            // The progress bar by itself does not contain any margin in IMGUI...
            // In this example, we are artifically adding the textfield margin to it. (see below, in the IMGUI section, ProgressBar())
            m_ProgressBar.style.marginBottom = 2f;

            m_VisualElementContainer.Add(m_GradientField = new GradientField());
            RefreshUIElements();
        }
Beispiel #26
0
    public NoteSubEditor(OrbitLineSubEditor orbitLineSubEditor, Note note)
    {
        this.orbitLineSubEditor = orbitLineSubEditor;
        this.note = note;

        VisualTreeAsset visualTree = AssetDatabase.LoadAssetAtPath <VisualTreeAsset>("Assets/Examples/StarSystemScene/Scripts/Editor/StarSystemEditor/NoteSubEditor.uxml");

        visualTree.CloneTree(this);

        StyleSheet stylesheet = AssetDatabase.LoadAssetAtPath <StyleSheet>("Assets/Examples/StarSystemScene/Scripts/Editor/StarSystemEditor/NoteSubEditor.uss");

        this.styleSheets.Add(stylesheet);

        this.AddToClassList("noteSubeditor");


        #region Fields
        SliderInt octave = this.Query <SliderInt>("octave").First();
        octave.value = note.octave;
        octave.RegisterCallback <ChangeEvent <int> >(
            e =>
        {
            note.octave = e.newValue;
            EditorUtility.SetDirty(note);
        }
            );

        // Find an object field with the name and set the type
        ObjectField synthPrefab = this.Query <ObjectField>("synthPrefab").First();
        synthPrefab.objectType = typeof(GameObject);
        synthPrefab.value      = note.synth;

        synthPrefab.RegisterCallback <ChangeEvent <Object> >(
            e =>
        {
            note.synth = (GameObject)e.newValue;
            EditorUtility.SetDirty(note);
        }
            );

        Slider velocity = this.Query <Slider>("velocity").First();
        velocity.value = note.velocity;
        velocity.label = "Velocity " + velocity.value.ToString("F3");
        velocity.RegisterCallback <ChangeEvent <float> >(
            e =>
        {
            note.velocity  = e.newValue;
            velocity.label = "Velocity " + e.newValue.ToString("F3");
            EditorUtility.SetDirty(note);
        }
            );

        Slider length = this.Query <Slider>("length").First();
        length.value = note.length;
        length.label = "Length " + length.value.ToString("F3");
        length.RegisterCallback <ChangeEvent <float> >(
            e =>
        {
            note.length  = e.newValue;
            length.label = "Length " + e.newValue.ToString("F3");
            EditorUtility.SetDirty(note);
        }
            );

        Slider size = this.Query <Slider>("size").First();
        size.value = note.size;
        size.label = "Size " + size.value.ToString("F3");
        size.RegisterCallback <ChangeEvent <float> >(
            e =>
        {
            note.size  = e.newValue;
            size.label = "Size " + e.newValue.ToString("F3");
            EditorUtility.SetDirty(note);
        }
            );

        EnumField noteValue = this.Query <EnumField>("noteValue").First();
        noteValue.value = note.note;
        noteValue.RegisterCallback <ChangeEvent <System.Enum> >(
            e =>
        {
            note.note = (NoteValue)e.newValue;
            EditorUtility.SetDirty(note);
        }
            );

        #endregion


        #region Buttons
        Button btnRemoveNote = this.Query <Button>("btnRemove").First();
        btnRemoveNote.clickable.clicked += RemoveNote;
        #endregion
    }
Beispiel #27
0
    public override VisualElement CreateInspectorGUI()
    {
        m_Root = new VisualElement();
        // root.Bind(serializedObject);
        // SerializedProperty property = serializedObject.GetIterator();
        // if (property.NextVisible(true)) // Expand first child.
        // {
        //     do
        //     {
        //         var field = new PropertyField(property);
        //         field.name = "PropertyField:" + property.propertyPath;
        //         if (property.propertyPath == "m_Script" && serializedObject.targetObject != null)
        //             field.SetEnabled(false);
        //         if (property.propertyPath != "CanvasOps")
        //             m_Root.Add(field);
        //     }
        //     while (property.NextVisible(false));
        // }
        var paletteProp = serializedObject.FindProperty("Palette");
        var palette     = new ObjectField("Palette");

        palette.objectType = typeof(Palette);
        palette.BindProperty(paletteProp);
        if (paletteProp.objectReferenceValue == null)
        {
            paletteProp.objectReferenceValue = AssetDatabase.LoadAssetAtPath <Palette>(AssetDatabase.GUIDToAssetPath(AssetDatabase.FindAssets("t:Palette").First()));
        }
        m_Root.Add(palette);
        var size = new Vector2IntField("Size");

        size.value = serializedObject.FindProperty("Size").vector2IntValue;
        m_Root.Add(size);
        var button = new Button(() => ResizeCanvas(size.value));

        button.text = "Resize Canvas";
        m_Root.Add(button);
        int frameCount  = serializedObject.FindProperty("Frames").arraySize;
        var frameSlider = new SliderInt("Frame", 0, frameCount - 1);

        frameSlider.BindProperty(serializedObject.FindProperty("FrameIndex"));
        frameSlider.RegisterValueChangedCallback(ChangeFrame);
        m_Root.Add(frameSlider);
        var frameIndex = new IntegerField("Frame");

        frameIndex.BindProperty(serializedObject.FindProperty("FrameIndex"));
        frameIndex.RegisterValueChangedCallback(ChangeFrame);
        frameIndex.SetEnabled(false);
        m_Root.Add(frameIndex);

        var importFrameButton = new Button(() => ImportFrame());

        importFrameButton.text = "Import Image";
        m_Root.Add(importFrameButton);

        m_Image       = new Image();
        m_Image.image = m_Texture;
        var desiredSize = 128f;

        if (m_Texture.width >= m_Texture.height)
        {
            m_Image.style.width  = desiredSize;
            m_Image.style.height = desiredSize * (m_Texture.height / (float)m_Texture.width);
        }
        else
        {
            m_Image.style.height = desiredSize;
            m_Image.style.width  = desiredSize * (m_Texture.width / (float)m_Texture.height);
        }
        // m_Image.RegisterCallback<MouseDownEvent>(RandomisePixels);
        var spacer = new VisualElement();

        spacer.style.height = 10;
        m_Root.Add(spacer);
        m_Root.Add(m_Image);
        return(m_Root);
    }
Beispiel #28
0
        void ReloadSettingsView()
        {
            // Remove all old fields
            Clear();

            if (title != null)
            {
                var titleLabel = new Label(title);
                titleLabel.AddToClassList("PropertyEditorTitle");
                this.Add(titleLabel);
            }

            var dimension = settings.GetResolvedTextureDimension(graph);

            // Wrap and Filter Modes
            smpHeader = new Label("Sampler States");
            smpHeader.AddToClassList(headerStyleClass);
            this.Add(smpHeader);

            wrapMode       = showSettingsForNode ? new EnumField(settings.wrapMode) : new EnumField((GraphOutputWrapMode)settings.wrapMode);
            wrapMode.label = "Wrap Mode";
            wrapMode.RegisterValueChangedCallback(e =>
            {
                owner.RegisterCompleteObjectUndo("Updated Wrap Mode " + e.newValue);
                settings.wrapMode = (OutputWrapMode)e.newValue;
                onChanged?.Invoke();
            });

            filterMode       = showSettingsForNode ? new EnumField(settings.filterMode) : new EnumField((GraphOutputFilterMode)settings.filterMode);
            filterMode.label = "Filter Mode";
            filterMode.RegisterValueChangedCallback(e =>
            {
                owner.RegisterCompleteObjectUndo("Updated Filter Mode " + e.newValue);
                settings.filterMode = (OutputFilterMode)e.newValue;
                onChanged?.Invoke();
            });

            this.Add(wrapMode);
            this.Add(filterMode);

            // Size Modes
            sizeHeader = new Label("Size Properties");
            sizeHeader.AddToClassList(headerStyleClass);
            this.Add(sizeHeader);

            outputSizeMode       = showSettingsForNode ? new EnumField(settings.sizeMode) : new EnumField((GraphOutputSizeMode)settings.sizeMode);
            outputSizeMode.label = "Size Mode";
            outputSizeMode.RegisterValueChangedCallback((EventCallback <ChangeEvent <Enum> >)(e => {
                owner.RegisterCompleteObjectUndo("Updated Size mode " + e.newValue);
                settings.sizeMode = (OutputSizeMode)e.newValue;
                onChanged?.Invoke();
                ReloadSettingsView();
                UpdateFieldVisibility(settings);
            }));
            this.Add(outputSizeMode);

            potSize = new EnumField(settings.potSize)
            {
                value = settings.potSize,
                label = "Resolution",
            };
            potSize.RegisterValueChangedCallback(e =>
            {
                owner.RegisterCompleteObjectUndo("Updated Size " + e.newValue);
                var size         = (POTSize)e.newValue;
                settings.potSize = size;

                if (size != POTSize.Custom)
                {
                    settings.width  = (int)size;
                    settings.height = (int)size;
                    settings.depth  = (int)size;
                }
                else
                {
                    settings.width  = outputWidth.value;
                    settings.height = outputHeight.value;
                    if (outputDepth != null)
                    {
                        settings.depth = outputDepth.value;
                    }
                }

                onChanged?.Invoke();
                ReloadSettingsView();
                UpdateFieldVisibility(settings);
            });

            this.Add(potSize);

            outputWidth = new IntegerField()
            {
                value     = settings.width,
                label     = "Width",
                isDelayed = true,
            };
            outputWidth.RegisterValueChangedCallback(e =>
            {
                owner.RegisterCompleteObjectUndo("Updated Width " + e.newValue);
                settings.width = e.newValue;
                onChanged?.Invoke();
            });
            this.Add(outputWidth);

            outputWidthScale = CreateSizeScaleSlider(settings.widthScale, (v) => settings.widthScale = v, "Width Scale");
            this.Add(outputWidthScale);

            if (dimension != TextureDimension.Cube)
            {
                outputHeight = new IntegerField()
                {
                    value     = settings.height,
                    label     = "Height",
                    isDelayed = true,
                };
                outputHeight.RegisterValueChangedCallback(e =>
                {
                    owner.RegisterCompleteObjectUndo("Updated Height " + e.newValue);
                    settings.height = e.newValue;
                    onChanged?.Invoke();
                });
                this.Add(outputHeight);

                outputHeightScale = CreateSizeScaleSlider(settings.heightScale, v => settings.heightScale = v, "Height Scale");
                this.Add(outputHeightScale);

                if (dimension == TextureDimension.Tex3D)
                {
                    outputDepth = new IntegerField()
                    {
                        value     = settings.depth,
                        label     = "Depth",
                        isDelayed = true,
                    };
                    outputDepth.RegisterValueChangedCallback(e =>
                    {
                        owner.RegisterCompleteObjectUndo("Updated Depth " + e.newValue);
                        settings.depth = e.newValue;
                        onChanged?.Invoke();
                    });
                    this.Add(outputDepth);

                    outputDepthScale = CreateSizeScaleSlider(settings.depthScale, v => settings.depthScale = v, "Depth Scale");
                    this.Add(outputDepthScale);
                }
            }

            SliderInt CreateSizeScaleSlider(float defaultValue, Action <float> setter, string propertyName)
            {
                var slider = new SliderInt(0, (int)(Mathf.Log(k_MaxSizeScale, 2) * 2))
                {
                    value = SizeScaleToInt(settings.heightScale),
                    label = propertyName,
                };

                slider.RegisterValueChangedCallback(e =>
                {
                    owner.RegisterCompleteObjectUndo(propertyName + " " + e.newValue);
                    setter(IntToSizeScale(e.newValue));
                    onChanged?.Invoke();
                });

                return(slider);
            }

            // Dimension and Pixel Format
            formatHeader = new Label("Format");
            formatHeader.AddToClassList(headerStyleClass);
            this.Add(formatHeader);

            outputDimension       = showSettingsForNode ? new EnumField(settings.dimension) : new EnumField((GraphOutputDimension)settings.dimension);
            outputDimension.label = "Dimension";
            outputDimension.RegisterValueChangedCallback(e => {
                owner.RegisterCompleteObjectUndo("Updated Texture Dimension " + e.newValue);
                // Check if the new texture is not too high res:
                settings.dimension = (OutputDimension)e.newValue;
                if (settings.dimension == OutputDimension.Texture3D)
                {
                    long pixelCount = settings.GetResolvedWidth(graph) * settings.GetResolvedHeight(graph) * settings.GetResolvedDepth(graph);

                    // Above 16M pixels in a texture3D, processing can take too long and crash the GPU when a conversion happen
                    if (pixelCount > 16777216)
                    {
                        settings.sizeMode = OutputSizeMode.Absolute;
                        settings.SetPOTSize(64);
                    }
                }
                onChanged?.Invoke();
                ReloadSettingsView();
            });

            outputChannels       = showSettingsForNode ? new EnumField(settings.outputChannels) : new EnumField((GraphOutputChannel)settings.outputChannels);
            outputChannels.label = "Output Channels";
            outputChannels.RegisterValueChangedCallback(e => {
                owner.RegisterCompleteObjectUndo("Updated Output Channels " + e.newValue);
                settings.outputChannels = (OutputChannel)e.newValue;
                onChanged?.Invoke();
            });

            outputPrecision       = showSettingsForNode ? new EnumField(settings.outputPrecision) : new EnumField((GraphOutputPrecision)settings.outputPrecision);
            outputPrecision.label = "Output Precision";
            outputPrecision.RegisterValueChangedCallback(e => {
                owner.RegisterCompleteObjectUndo("Updated Output Precision " + e.newValue);
                settings.outputPrecision = (OutputPrecision)e.newValue;
                // outputPrecision.Init();
                onChanged?.Invoke();
            });

            this.Add(outputDimension);
            this.Add(outputChannels);
            this.Add(outputPrecision);

            UpdateFieldVisibility(settings);

            if (showSettingsForNode)
            {
                // Realtime fields and refresh mode
                otherHeader = new Label("Other");
                otherHeader.AddToClassList(headerStyleClass);
                this.Add(otherHeader);

                doubleBuffered = new Toggle("Double Buffered")
                {
                    value = settings.doubleBuffered,
                };
                doubleBuffered.RegisterValueChangedCallback(e => {
                    owner.RegisterCompleteObjectUndo("Set Double Buffered " + e.newValue);
                    settings.doubleBuffered = e.newValue;
                    onChanged?.Invoke();
                });

                Add(doubleBuffered);
            }
            else if (graph.type == MixtureGraphType.Realtime)
            {
                otherHeader = new Label("Realtime");
                otherHeader.AddToClassList(headerStyleClass);
                this.Add(otherHeader);

                AddRealtimeFields(owner);
            }
        }
Beispiel #29
0
        protected override VisualElement CreateValueElement(SerializedProperty property)
        {
            var attributes = property.GetFieldAttributes();

            if (attributes.Any(_a => _a is RangeIntAttribute))
            {
                var range = attributes.First(_a => _a is RangeIntAttribute) as RangeIntAttribute;
                var root  = new VisualElement();
                //root.style.justifyContent = new StyleEnum<Justify>(Justify.SpaceBetween);
                root.style.flexDirection = new StyleEnum <FlexDirection>(FlexDirection.Row);
                var slider = new SliderInt(range.Min, range.Max)
                {
                    bindingPath = $"{property.propertyPath}._value"
                };
                slider.style.marginLeft  = new StyleLength(5);
                slider.style.marginRight = new StyleLength(5);
                slider.style.flexGrow    = new StyleFloat(3);
                root.Add(slider);
                var intField = new IntegerField()
                {
                    bindingPath = $"{property.propertyPath}._value"
                };
                //intField.style.paddingLeft = new StyleLength(5);
                intField.style.marginRight = new StyleLength(5);
                intField.style.maxWidth    = new StyleLength(150);
                intField.style.minWidth    = new StyleLength(50);
                EventCallback <ChangeEvent <int> > action = (e) =>
                {
                    var valueProp = property.FindPropertyRelative("_value");
                    Debug.Log($"prop={valueProp.intValue}, value=>{e.newValue}; range=>({range.Min}:{range.Max})");
                    if (range.IsInRange(e.newValue))
                    {
                        return;
                    }
                    var field = e.target as IntegerField;
                    field.value = range.Clamp(e.newValue);
                };
                intField.RegisterValueChangedCallback(action);

                //intField.style.flexGrow = new StyleFloat(1);
                root.Add(intField);
                return(root);
            }
            else if (attributes.Any(_a => _a is MinAttribute))
            {
                var min      = attributes.First(_a => _a is MinAttribute) as MinAttribute;
                var intField = new IntegerField();
                intField.RegisterValueChangedCallback(_e =>
                {
                    if ((int)min.min > _e.newValue)
                    {
                        var valueProp      = property.FindPropertyRelative("_value");
                        valueProp.intValue = (int)min.min;
                    }
                });
                return(intField);
            }
            else
            {
                var intField = new IntegerField();
                return(intField);
            }
        }
Beispiel #30
0
        private void Init(SimulatorJsonSerialization states)
        {
            InitPlayerSettings(states);

            bool overrideDefaultPlayerSettings = (states != null) ? states.overrideDefaultPlayerSettings : false;

            m_OverrideDefaultPlayerSettings = m_RootElement.Q <Toggle>("override-default-player-settings");
            m_OverrideDefaultPlayerSettings.RegisterValueChangedCallback(SetOverridePlayerSettings);
            m_OverrideDefaultPlayerSettings.SetValueWithoutNotify(overrideDefaultPlayerSettings);
            UpdateOverridePlayerSettingsStatus();

            m_CustomizedPlayerSettingsElement = m_RootElement.Q <VisualElement>("customized-player-settings");

            m_StartInFullscreen = m_RootElement.Q <Toggle>("android-start-in-fullscreen");
            m_StartInFullscreen.SetValueWithoutNotify(m_CustomizedPlayerSettings.androidStartInFullscreen);
            m_StartInFullscreen.RegisterValueChangedCallback((evt) => { m_CustomizedPlayerSettings.androidStartInFullscreen = evt.newValue; });

            m_ResolutionScalingMode = m_RootElement.Q <EnumField>("resolution-scaling-mode");
            m_ResolutionScalingMode.Init(ResolutionScalingMode.Disabled);
            m_ResolutionScalingMode.RegisterValueChangedCallback(SetResolutionScalingMode);
            m_ResolutionScalingMode.SetValueWithoutNotify(m_CustomizedPlayerSettings.resolutionScalingMode);

            #region DPI
            m_DpiContainer = m_RootElement.Q <VisualElement>("dpi-container");

            m_DpiSlider = m_DpiContainer.Q <SliderInt>("dpi-slider");
            m_DpiSlider.RegisterValueChangedCallback(SyncDpiField);
            m_DpiSlider.SetValueWithoutNotify(m_CustomizedPlayerSettings.targetDpi);

            m_DpiField = m_DpiContainer.Q <IntegerField>("dpi-field");
            m_DpiField.RegisterValueChangedCallback(SyncDpiSlider);
            m_DpiField.RegisterCallback <KeyDownEvent>(OnDpiFieldKeyDown);
            m_DpiField.SetValueWithoutNotify(m_CustomizedPlayerSettings.targetDpi);
            #endregion

            #region Orientation
            m_DefaultOrientation = m_RootElement.Q <EnumField>("default-screen-orientation");
            m_DefaultOrientation.Init(UIOrientation.AutoRotation);
            m_DefaultOrientation.RegisterValueChangedCallback(SetDefaultOrientation);
            m_DefaultOrientation.SetValueWithoutNotify(m_CustomizedPlayerSettings.defaultOrientation);

            m_AllowedOrienations = m_RootElement.Q <Foldout>("allowed-orientations");

            m_AllowedPortrait = m_AllowedOrienations.Q <Toggle>("orientation-allow-portrait");
            m_AllowedPortrait.SetValueWithoutNotify(m_CustomizedPlayerSettings.allowedPortrait);
            m_AllowedPortrait.RegisterValueChangedCallback((evt) => { m_CustomizedPlayerSettings.allowedPortrait = evt.newValue; });

            m_AllowedPortraitUpsideDown = m_AllowedOrienations.Q <Toggle>("orientation-allow-portrait-upside-down");
            m_AllowedPortraitUpsideDown.SetValueWithoutNotify(m_CustomizedPlayerSettings.allowedPortraitUpsideDown);
            m_AllowedPortraitUpsideDown.RegisterValueChangedCallback((evt) => { m_CustomizedPlayerSettings.allowedPortraitUpsideDown = evt.newValue; });

            m_AllowedLandscapeLeft = m_AllowedOrienations.Q <Toggle>("orientation-allow-landscape-left");
            m_AllowedLandscapeLeft.SetValueWithoutNotify(m_CustomizedPlayerSettings.allowedLandscapeLeft);
            m_AllowedLandscapeLeft.RegisterValueChangedCallback((evt) => { m_CustomizedPlayerSettings.allowedLandscapeLeft = evt.newValue; });

            m_AllowedLandscapeRight = m_AllowedOrienations.Q <Toggle>("orientation-allow-landscape-right");
            m_AllowedLandscapeRight.SetValueWithoutNotify(m_CustomizedPlayerSettings.allowedLandscapeRight);
            m_AllowedLandscapeRight.RegisterValueChangedCallback((evt) => { m_CustomizedPlayerSettings.allowedLandscapeRight = evt.newValue; });
            #endregion

            #region Graphics API
            m_AutoGraphicsAPI = m_RootElement.Q <Toggle>("auto-graphics-api");
            m_AutoGraphicsAPI.SetValueWithoutNotify(m_CustomizedPlayerSettings.autoGraphicsAPI);
            m_AutoGraphicsAPI.RegisterValueChangedCallback(SetAutoGraphicsAPI);

            m_GraphicsAPIPlaceholder = m_RootElement.Q <VisualElement>("graphics-api-placeholder");
            m_GraphicsAPIPlaceholder.SetEnabled(!m_CustomizedPlayerSettings.autoGraphicsAPI);
            #endregion

            UpdateCustomizedPlayerSettings(m_OverrideDefaultPlayerSettings.value);
            UpdateStartInFullScreen();
            UpdateResolutionScalingMode(m_CustomizedPlayerSettings.resolutionScalingMode);
            UpdateAllowedOrientations(m_CustomizedPlayerSettings.defaultOrientation);
            UpdateGraphicsAPI();
        }