void OnSceneGUI()
    {
        Event evt = Event.current;

        if ((evt.type == EventType.KeyUp) && (evt.keyCode == KeyCode.D))
        {
            evt.Use();
            drawing = !drawing;
        }

        if (drawing)
        {
            Handles.BeginGUI();
            GUILayout.BeginArea(new Rect(Screen.width - 150, Screen.height - 65, 140, 20), "Grease Pencil Drawing", "Box");
            GUILayout.EndArea();
            Handles.EndGUI();

            if (evt.alt)
            {
                // don't hijack camera controls
                return;
            }

            float distance = 0f;

            Vector3 screenPosition = evt.mousePosition;
            screenPosition.y = Screen.height - (screenPosition.y + 38f);

            Camera cam = SceneView.currentDrawingSceneView.camera;

            Ray   ray   = cam.ScreenPointToRay(screenPosition);
            Plane plane = new Plane(cam.transform.forward, instance.transform.position);

            HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));

            if (plane.Raycast(ray, out distance))
            {
                Vector3 worldPosition = ray.GetPoint(distance);

                if ((evt.button == 0) && (!evt.shift))
                {
                    if (evt.type == EventType.MouseDown)
                    {
                        instance.StartStroke(worldPosition, HandleUtility.GetHandleSize(instance.transform.position));
                        evt.Use();
                        EditorUtility.SetDirty(instance);
                    }
                    else if (evt.type == EventType.MouseDrag)
                    {
                        instance.UpdateStroke(worldPosition);
                        evt.Use();
                        EditorUtility.SetDirty(instance);
                    }
                    else if (evt.type == EventType.MouseUp)
                    {
                        instance.EndStroke(worldPosition);
                        evt.Use();
                        EditorUtility.SetDirty(instance);
                    }
                }
                else if ((evt.button == 0) && (evt.shift))
                {
                    if ((evt.type == EventType.MouseDrag) || (evt.type == EventType.MouseDown))
                    {
                        erasing = true;
                        EditorGUIUtility.AddCursorRect(new Rect(0f, 0f, Screen.width, Screen.height), MouseCursor.Arrow);
                        EditorGUIUtility.SetWantsMouseJumping(0);

                        // erase
                        List <int> points = new List <int> (100);
                        GreasePencil.GreasePencilStroke stroke;

                        for (int s = 0; s < instance.ActiveLayer.strokes.Count; ++s)
                        {
                            stroke = instance.ActiveLayer.strokes[s];
                            points.Clear();

                            for (int i = 0; i < stroke.points.Count; ++i)
                            {
                                if ((cam.WorldToScreenPoint(stroke.points[i]) - screenPosition).magnitude < eraserSize)
                                {
                                    points.Add(i);
                                }
                            }

                            instance.ActiveLayer.Erase(s, points);
                        }

                        instance.UpdateStroke(worldPosition);
                        evt.Use();
                        EditorUtility.SetDirty(instance);
                    }
                    else if ((evt.type == EventType.MouseUp) || (evt.type == EventType.MouseMove) ||
                             ((evt.type == EventType.KeyUp) && ((evt.keyCode == KeyCode.LeftShift) || (evt.keyCode == KeyCode.RightShift))))
                    {
                        erasing = false;
                        SceneView.RepaintAll();
                    }
                    else if (evt.type == EventType.Repaint)
                    {
                        Handles.BeginGUI();
                        Handles.matrix = Matrix4x4.identity;
                        Handles.color  = erasing?Color.red:Color.black;
                        Handles.DrawWireDisc(evt.mousePosition, Vector3.forward, eraserSize);
                        Handles.color = new Color(erasing?1f:0f, 0f, 0f, 0.125f);
                        Handles.DrawSolidDisc(evt.mousePosition, Vector3.forward, eraserSize);
                        Handles.EndGUI();
                    }
                }
            }
        }
    }
        public void OnSceneGUI()
        {
            var script = target as GraphUpdateScene;

            // Don't allow editing unless it is the active object
            if (Selection.activeGameObject != script.gameObject || script.legacyMode)
            {
                return;
            }

            // Make sure the points array is not null
            if (script.points == null)
            {
                script.points = new Vector3[0];
                EditorUtility.SetDirty(script);
            }

            List <Vector3> points = Pathfinding.Util.ListPool <Vector3> .Claim();

            points.AddRange(script.points);

            Matrix4x4 invMatrix = script.transform.worldToLocalMatrix;

            Matrix4x4 matrix = script.transform.localToWorldMatrix;

            for (int i = 0; i < points.Count; i++)
            {
                points[i] = matrix.MultiplyPoint3x4(points[i]);
            }


            float minScreenDist = float.PositiveInfinity;

            if (Tools.current != Tool.View && Event.current.type == EventType.Layout)
            {
                for (int i = 0; i < script.points.Length; i++)
                {
                    float dist = HandleUtility.DistanceToLine(points[i], points[i]);
                    HandleUtility.AddControl(-i - 1, dist);
                    minScreenDist = Mathf.Min(dist, minScreenDist);
                }
            }

            // If there is a point sort of close to the cursor, but not close enough
            // to receive a click event, then prevent the user from accidentally clicking
            // which would deselect the current object and be kinda annoying.
            if (Tools.current != Tool.View && minScreenDist < 50)
            {
                HandleUtility.AddDefaultControl(0);
            }

            for (int i = 0; i < points.Count; i++)
            {
                if (i == selectedPoint && Tools.current == Tool.Move)
                {
                    Handles.color = PointSelectedColor;
                    SphereCap(-i - 1, points[i], Quaternion.identity, HandleUtility.GetHandleSize(points[i]) * pointGizmosRadius * 2);

                    Vector3 pre  = points[i];
                    Vector3 post = Handles.PositionHandle(points[i], Quaternion.identity);
                    if (pre != post)
                    {
                        Undo.RecordObject(script, "Moved Point");
                        script.points[i] = invMatrix.MultiplyPoint3x4(post);
                    }
                }
                else
                {
                    Handles.color = PointColor;
                    SphereCap(-i - 1, points[i], Quaternion.identity, HandleUtility.GetHandleSize(points[i]) * pointGizmosRadius);
                }
            }

            if (Event.current.type == EventType.MouseDown)
            {
                int pre = selectedPoint;
                selectedPoint = -(HandleUtility.nearestControl + 1);
                if (pre != selectedPoint)
                {
                    GUI.changed = true;
                }
            }

            if (Tools.current == Tool.Move)
            {
                var darkSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene);

                Handles.BeginGUI();
                float width  = 220;
                float height = 76;
                float margin = 10;

                AstarPathEditor.LoadStyles();
                GUILayout.BeginArea(new Rect(Camera.current.pixelWidth - width, Camera.current.pixelHeight - height, width - margin, height - margin), "Shortcuts", AstarPathEditor.astarSkin.FindStyle("SceneBoxDark"));

                GUILayout.Label("Shift+Click: Add new point", darkSkin.label);
                GUILayout.Label("Backspace: Delete selected point", darkSkin.label);

                // Invisible button to capture clicks. This prevents a click inside the box from causing some other GameObject to be selected.
                GUI.Button(new Rect(0, 0, width - margin, height - margin), "", GUIStyle.none);
                GUILayout.EndArea();

                Handles.EndGUI();
            }

            if (Tools.current == Tool.Move && Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Backspace && selectedPoint >= 0 && selectedPoint < points.Count)
            {
                Undo.RecordObject(script, "Removed Point");
                var arr = new List <Vector3>(script.points);
                arr.RemoveAt(selectedPoint);
                points.RemoveAt(selectedPoint);
                script.points = arr.ToArray();
                GUI.changed   = true;
            }

            if (Event.current.shift && Tools.current == Tool.Move)
            {
                HandleUtility.Repaint();

                // Find the closest segment
                int   insertionIndex = points.Count;
                float minDist        = float.PositiveInfinity;
                for (int i = 0; i < points.Count; i++)
                {
                    float dist = HandleUtility.DistanceToLine(points[i], points[(i + 1) % points.Count]);
                    if (dist < minDist)
                    {
                        insertionIndex = i + 1;
                        minDist        = dist;
                    }
                }

                var           ray    = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
                System.Object hit    = HandleUtility.RaySnap(ray);
                Vector3       rayhit = Vector3.zero;
                bool          didHit = false;
                if (hit != null)
                {
                    rayhit = ((RaycastHit)hit).point;
                    didHit = true;
                }
                else
                {
                    var   plane = new Plane(script.transform.up, script.transform.position);
                    float distance;
                    plane.Raycast(ray, out distance);
                    if (distance > 0)
                    {
                        rayhit = ray.GetPoint(distance);
                        didHit = true;
                    }
                }

                if (didHit)
                {
                    if (Event.current.type == EventType.MouseDown)
                    {
                        points.Insert(insertionIndex, rayhit);

                        Undo.RecordObject(script, "Added Point");
                        var arr = new List <Vector3>(script.points);
                        arr.Insert(insertionIndex, invMatrix.MultiplyPoint3x4(rayhit));
                        script.points = arr.ToArray();
                        GUI.changed   = true;
                    }
                    else if (points.Count > 0)
                    {
                        Handles.color = Color.green;
                        Handles.DrawDottedLine(points[(insertionIndex - 1 + points.Count) % points.Count], rayhit, 8);
                        Handles.DrawDottedLine(points[insertionIndex % points.Count], rayhit, 8);
                        SphereCap(0, rayhit, Quaternion.identity, HandleUtility.GetHandleSize(rayhit) * pointGizmosRadius);
                        // Project point down onto a plane
                        var zeroed = invMatrix.MultiplyPoint3x4(rayhit);
                        zeroed.y      = 0;
                        Handles.color = new Color(1, 1, 1, 0.5f);
                        Handles.DrawDottedLine(matrix.MultiplyPoint3x4(zeroed), rayhit, 4);
                    }
                }

                if (Event.current.type == EventType.MouseDown)
                {
                    Event.current.Use();
                }
            }

            // Make sure the convex hull stays up to date
            script.RecalcConvex();
            Pathfinding.Util.ListPool <Vector3> .Release(ref points);

            if (GUI.changed)
            {
                HandleUtility.Repaint();
            }
        }
Пример #3
0
        void DrawPointSceneGUI(BezierPoint point, int index)
        {
            Handles.BeginGUI();
            var e = Event.current;

            Handles.Label(point.position + new Vector3(0, HandleUtility.GetHandleSize(point.position) * 0.4f, 0), index.ToString());
            Handles.color = Color.green;
            var pointGUISize = HandleUtility.GetHandleSize(point.position) * 0.1f;

            if (e.type == EventType.MouseDown)
            {
                var screenPos     = HandleUtility.WorldToGUIPoint(point.position);
                var nextPoint     = index < path.points.Count - 1 ? path[index + 1] : null;
                var previousPoint = index > 0 ? path[index - 1] : null;

                if (((Vector2)screenPos - e.mousePosition).magnitude < 13)
                {
                    if (e.button == 0)
                    {
                        selectedPoint = point;
                        SceneView.RepaintAll();
                    }

                    if (e.button == 1)
                    {
                        path.SetDirty();
                        var menu = new GenericMenu();
                        if (nextPoint != null)
                        {
                            menu.AddItem(new GUIContent("Add Point After"), false, () => { path.AddPointAt(BezierPath.GetPoint(point, nextPoint, 0.5f), index + 1); });
                        }
                        if (previousPoint != null)
                        {
                            menu.AddItem(new GUIContent("Add Point Before"), false, () => { path.AddPointAt(BezierPath.GetPoint(previousPoint, point, 0.5f), index); });
                        }
                        menu.AddItem(new GUIContent("Tangent/Connected"), false, () => { point.handleStyle = BezierPoint.HandleStyle.Connected; });
                        menu.AddItem(new GUIContent("Tangent/Broken"), false, () => { point.handleStyle = BezierPoint.HandleStyle.Broken; });
                        if (path.points.Count > 2)
                        {
                            menu.AddSeparator("/");
                            menu.AddItem(new GUIContent("Delete"), false, () => { path.RemovePoint(point); });
                        }
                        menu.ShowAsContext();
                        e.Use();
                    }
                }
            }

            var newPosition = point.position;

            if (point == selectedPoint)
            {
                newPosition = Handles.PositionHandle(point.position, Quaternion.identity);
            }
            Handles.FreeMoveHandle(point.position, Quaternion.identity, pointGUISize, Vector3.zero, Handles.RectangleCap);

            if (newPosition != point.position)
            {
                point.position = newPosition;
                path.SetDirty();
            }

            if (point.handleStyle != BezierPoint.HandleStyle.None)
            {
                Handles.color = Color.cyan;
                var newGlobal1 = Handles.FreeMoveHandle(point.globalHandle1, Quaternion.identity, HandleUtility.GetHandleSize(point.globalHandle1) * 0.075f, Vector3.zero, Handles.CircleCap);
                if (point.globalHandle1 != newGlobal1)
                {
                    point.globalHandle1 = newGlobal1;
                    path.SetDirty();
                    //if(point.handleStyle == BezierPoint.HandleStyle.Connected) point.globalHandle2 = -(newGlobal1 - point.position) + point.position;
                }

                var newGlobal2 = Handles.FreeMoveHandle(point.globalHandle2, Quaternion.identity, HandleUtility.GetHandleSize(point.globalHandle2) * 0.075f, Vector3.zero, Handles.CircleCap);
                if (point.globalHandle2 != newGlobal2)
                {
                    point.globalHandle2 = newGlobal2;
                    path.SetDirty();
                    //if(point.handleStyle == BezierPoint.HandleStyle.Connected) point.globalHandle1 = -(newGlobal2 - point.position) + point.position;
                }

                Handles.color = Color.yellow;
                Handles.DrawLine(point.position, point.globalHandle1);
                Handles.DrawLine(point.position, point.globalHandle2);
            }

            Handles.EndGUI();
        }
Пример #4
0
        static void OnScene(SceneView sceneView)
        {
            if (!RealtimeCSG.CSGSettings.EnableRealtimeCSG)
            {
                return;
            }
            UpdateOnSceneChange();
            if (Event.current.type == EventType.layout)
            {
                ColorSettings.Update();
            }

            if (!IsActive())
            {
                ResetUpdateRoutine();
            }

            if (Event.current.type == EventType.MouseDown ||
                Event.current.type == EventType.MouseDrag)
            {
                mousePressed = true;
            }
            else if (Event.current.type == EventType.MouseUp ||
                     Event.current.type == EventType.MouseMove)
            {
                mousePressed = false;
            }

            UpdateRectSelection(sceneView);
            OnHandleDragAndDrop(inSceneView: true);

            var s_RectSelectionID_instance = (int)s_RectSelectionID_field.GetValue(null);
            var eventType = Event.current.GetTypeForControl(s_RectSelectionID_instance);

            if (GUIUtility.hotControl == s_RectSelectionID_instance &&
                CSGBrushEditorManager.ActiveTool.IgnoreUnityRect)
            {
                GUIUtility.hotControl = 0;
            }
            switch (eventType)
            {
            case EventType.MouseDown:
            {
                rectClickDown      = (Event.current.button == 0 && GUIUtility.hotControl == s_RectSelectionID_instance);
                clickMousePosition = Event.current.mousePosition;
                mouseDragged       = false;
                break;
            }

            case EventType.MouseUp:
            {
                rectClickDown = false;
                break;
            }

            case EventType.MouseMove:
            {
                rectClickDown = false;
                break;
            }

            case EventType.Used:
            {
                if (clickMousePosition != Event.current.mousePosition)
                {
                    mouseDragged = true;
                }
                if (!mouseDragged && rectClickDown &&
                    Event.current.button == 0)
                {
                    // m_RectSelection field of SceneView
                    var m_RectSelection_instance = m_RectSelection_field.GetValue(sceneView);

                    var m_RectSelecting_instance = (bool)m_RectSelecting_field.GetValue(m_RectSelection_instance);
                    if (!m_RectSelecting_instance)
                    {
                        // make sure GeneratedMeshes are not part of our selection
                        if (Selection.gameObjects != null)
                        {
                            var selectedObjects = Selection.objects;
                            var foundObjects    = new List <UnityEngine.Object>();
                            foreach (var obj in selectedObjects)
                            {
                                var component  = obj as Component;
                                var gameObject = obj as GameObject;
                                var transform  = obj as Transform;
                                if (!(component && component.GetComponent <GeneratedMeshes>()) &&
                                    !(gameObject && gameObject.GetComponent <GeneratedMeshes>()) &&
                                    !(transform && transform.GetComponent <Transform>()))
                                {
                                    foundObjects.Add(obj);
                                }
                            }
                            if (foundObjects.Count != selectedObjects.Length)
                            {
                                Selection.objects = foundObjects.ToArray();
                            }
                        }

                        SelectionUtility.DoSelectionClick();
                        Event.current.Use();
                    }
                }
                rectClickDown = false;
                break;
            }


            case EventType.ValidateCommand:
            {
                if (Event.current.commandName == "SelectAll")
                {
                    Event.current.Use();
                    break;
                }
                if (Keys.HandleSceneValidate(CSGBrushEditorManager.CurrentTool, true))
                {
                    Event.current.Use();
                    HandleUtility.Repaint();
                }
                break;
            }

            case EventType.ExecuteCommand:
            {
                if (Event.current.commandName == "SelectAll")
                {
                    var transforms = new List <UnityEngine.Object>();
                    for (int sceneIndex = 0; sceneIndex < SceneManager.sceneCount; sceneIndex++)
                    {
                        var scene = SceneManager.GetSceneAt(sceneIndex);
                        foreach (var gameObject in scene.GetRootGameObjects())
                        {
                            foreach (var transform in gameObject.GetComponentsInChildren <Transform>())
                            {
                                if ((transform.hideFlags & (HideFlags.NotEditable | HideFlags.HideInHierarchy)) == (HideFlags.NotEditable | HideFlags.HideInHierarchy))
                                {
                                    continue;
                                }
                                transforms.Add(transform.gameObject);
                            }
                        }
                    }
                    Selection.objects = transforms.ToArray();

                    Event.current.Use();
                    break;
                }
                break;
            }

            case EventType.KeyDown:
            {
                if (Keys.HandleSceneKeyDown(CSGBrushEditorManager.CurrentTool, true))
                {
                    Event.current.Use();
                    HandleUtility.Repaint();
                }
                break;
            }

            case EventType.KeyUp:
            {
                if (Keys.HandleSceneKeyUp(CSGBrushEditorManager.CurrentTool, true))
                {
                    Event.current.Use();
                    HandleUtility.Repaint();
                }
                break;
            }

            case EventType.Layout:
            {
                if (currentDragTool != null)
                {
                    currentDragTool.Layout();
                }
                break;
            }

            case EventType.Repaint:
            {
                break;
            }
            }

            CSGBrushEditorManager.UpdateSelection();
            //bool fallbackGUI = EditorWindow.focusedWindow != sceneView;
            //fallbackGUI =
            CSGBrushEditorManager.InitSceneGUI(sceneView);                    // || fallbackGUI;
            //fallbackGUI = true;


            if (Event.current.type == EventType.repaint)
            {
                MeshInstanceManager.RenderHelperSurfaces(sceneView.camera);
            }

            if (Event.current.type == EventType.repaint)
            {
                if (currentDragTool != null)
                {
                    currentDragTool.OnPaint();
                }

                SceneTools.OnPaint(sceneView);
            }
            else
            //if (fallbackGUI)
            {
                BottomBarGUI.ShowGUI(sceneView);
            }


            CSGBrushEditorManager.OnSceneGUI(sceneView);

            //if (fallbackGUI)
            {
                TooltipUtility.InitToolTip(sceneView);
                if (Event.current.type == EventType.repaint)
                {
                    BottomBarGUI.ShowGUI(sceneView);
                }
                if (!mousePressed)
                {
                    Handles.BeginGUI();
                    TooltipUtility.DrawToolTip(getLastRect: false);
                    Handles.EndGUI();
                }
            }
        }
Пример #5
0
    public new void OnSceneGUI()
    {
        if (tk2dPreferences.inst.enableSpriteHandles == false || !tk2dEditorUtility.IsEditable(target))
        {
            return;
        }

        tk2dTiledSprite spr = (tk2dTiledSprite)target;

        Transform t      = spr.transform;
        var       sprite = spr.CurrentSprite;

        if (sprite == null)
        {
            return;
        }

        Vector2 totalMeshSize = new Vector2(spr.dimensions.x * sprite.texelSize.x * spr.scale.x, spr.dimensions.y * sprite.texelSize.y * spr.scale.y);
        Vector2 anchorOffset  = tk2dSceneHelper.GetAnchorOffset(totalMeshSize, spr.anchor);

        {
            Vector3 v     = new Vector3(anchorOffset.x, anchorOffset.y, 0);
            Vector3 d     = totalMeshSize;
            Rect    rect0 = new Rect(v.x, v.y, d.x, d.y);

            Handles.color = new Color(1, 1, 1, 0.5f);
            tk2dSceneHelper.DrawRect(rect0, t);

            Handles.BeginGUI();
            // Resize handles
            if (tk2dSceneHelper.RectControlsToggle())
            {
                EditorGUI.BeginChangeCheck();
                Rect resizeRect = tk2dSceneHelper.RectControl(123192, rect0, t);
                if (EditorGUI.EndChangeCheck())
                {
                    tk2dUndo.RecordObjects(new Object[] { t, spr }, "Resize");
                    spr.ReshapeBounds(new Vector3(resizeRect.xMin, resizeRect.yMin) - new Vector3(rect0.xMin, rect0.yMin),
                                      new Vector3(resizeRect.xMax, resizeRect.yMax) - new Vector3(rect0.xMax, rect0.yMax));
                    EditorUtility.SetDirty(spr);
                }
            }

            // Rotate handles
            if (!tk2dSceneHelper.RectControlsToggle())
            {
                EditorGUI.BeginChangeCheck();
                List <int> hidePts = tk2dSceneHelper.getAnchorHidePtList(spr.anchor, rect0, t);
                float      theta   = tk2dSceneHelper.RectRotateControl(456384, rect0, t, hidePts);
                if (EditorGUI.EndChangeCheck())
                {
                    if (Mathf.Abs(theta) > Mathf.Epsilon)
                    {
                        tk2dUndo.RecordObject(t, "Rotate");
                        t.Rotate(t.forward, theta, Space.World);
                    }
                }
            }

            Handles.EndGUI();

            // Sprite selecting
            tk2dSceneHelper.HandleSelectSprites();

            // Sprite moving (translation)
            tk2dSceneHelper.HandleMoveSprites(t, new Rect(v.x, v.y, d.x, d.y));
        }

        if (GUI.changed)
        {
            EditorUtility.SetDirty(target);
        }
    }
Пример #6
0
    /// <summary>
    /// Draw the specified anchor point.
    /// </summary>

    static public void DrawAnchorHandle(UIRect.AnchorPoint anchor, Transform myTrans, Vector3[] myCorners, int side, int id)
    {
        if (!anchor.target)
        {
            return;
        }

        int i0, i1;

        if (side == 0)
        {
            // Left
            i0 = 0;
            i1 = 1;
        }
        else if (side == 1)
        {
            // Top
            i0 = 1;
            i1 = 2;
        }
        else if (side == 2)
        {
            // Right
            i0 = 3;
            i1 = 2;
        }
        else
        {
            // Bottom
            i0 = 0;
            i1 = 3;
        }

        Vector3 myPos = (myCorners[i0] + myCorners[i1]) * 0.5f;

        Vector3[] sides = null;

        if (anchor.rect != null)
        {
            sides = anchor.rect.worldCorners;
        }
        else
        {
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
            Camera cam = anchor.target.camera;
#else
            Camera cam = anchor.target.GetComponent <Camera>();
#endif
            if (cam != null)
            {
                sides = cam.GetWorldCorners();
            }
        }

        Vector3 theirPos;

        if (sides != null)
        {
            Vector3 v0, v1;

            if (side == 0 || side == 2)
            {
                // Left or right
                v0 = Vector3.Lerp(sides[0], sides[3], anchor.relative);
                v1 = Vector3.Lerp(sides[1], sides[2], anchor.relative);
            }
            else
            {
                // Top or bottom
                v0 = Vector3.Lerp(sides[0], sides[1], anchor.relative);
                v1 = Vector3.Lerp(sides[3], sides[2], anchor.relative);
            }

            theirPos = HandleUtility.ProjectPointLine(myPos, v0, v1);
        }
        else
        {
            theirPos = anchor.target.position;
        }

        NGUIHandles.DrawShadowedLine(myCorners, myPos, theirPos, Color.yellow);

        if (Event.current.GetTypeForControl(id) == EventType.Repaint)
        {
            Vector2 screenPoint = HandleUtility.WorldToGUIPoint(theirPos);
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
            Rect rect = new Rect(screenPoint.x - 7f, screenPoint.y - 7f, 14f, 14f);
#else
            Rect rect = new Rect(screenPoint.x - 5f, screenPoint.y - 9f, 14f, 14f);
#endif
            if (mYellowDot == null)
            {
                mYellowDot = "sv_label_4";
            }

            Vector3 v0 = HandleUtility.WorldToGUIPoint(myPos);
            Vector3 v1 = HandleUtility.WorldToGUIPoint(theirPos);

            Handles.BeginGUI();

            mYellowDot.Draw(rect, GUIContent.none, id);

            Vector3 diff         = v1 - v0;
            bool    isHorizontal = Mathf.Abs(diff.x) > Mathf.Abs(diff.y);
            float   mag          = diff.magnitude;

            if ((isHorizontal && mag > 60f) || (!isHorizontal && mag > 30f))
            {
                Vector3 pos  = (myPos + theirPos) * 0.5f;
                string  text = anchor.absolute.ToString();

                GUI.color = Color.yellow;

                if (side == 0)
                {
                    if (theirPos.x < myPos.x)
                    {
                        NGUIHandles.DrawCenteredLabel(pos, text);
                    }
                }
                else if (side == 1)
                {
                    if (theirPos.y > myPos.y)
                    {
                        NGUIHandles.DrawCenteredLabel(pos, text);
                    }
                }
                else if (side == 2)
                {
                    if (theirPos.x > myPos.x)
                    {
                        NGUIHandles.DrawCenteredLabel(pos, text);
                    }
                }
                else if (side == 3)
                {
                    if (theirPos.y < myPos.y)
                    {
                        NGUIHandles.DrawCenteredLabel(pos, text);
                    }
                }
                GUI.color = Color.white;
            }
            Handles.EndGUI();
        }
    }
Пример #7
0
    /// <summary>
    /// Handles & interaction.
    /// </summary>

    public void OnSceneGUI()
    {
        if (Selection.objects.Length > 1)
        {
            return;
        }

        UICamera cam = UICamera.FindCameraForLayer(mPanel.gameObject.layer);

#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6
        if (cam == null || !cam.cachedCamera.isOrthoGraphic)
        {
            return;
        }
#else
        if (cam == null || !cam.cachedCamera.orthographic)
        {
            return;
        }
#endif

        NGUIEditorTools.HideMoveTool(true);
        //if (!UIWidget.showHandles) return;

        Event     e    = Event.current;
        int       id   = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
        EventType type = e.GetTypeForControl(id);
        Transform t    = mPanel.cachedTransform;

        Vector3[] handles = UIWidgetInspector.GetHandles(mPanel.worldCorners);

        // Time to figure out what kind of action is underneath the mouse
        UIWidgetInspector.Action actionUnderMouse = mAction;

        Color handlesColor = new Color(0.5f, 0f, 0.5f);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);

        if (mPanel.isAnchored)
        {
            UIWidgetInspector.DrawAnchorHandle(mPanel.leftAnchor, mPanel.cachedTransform, handles, 0, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.topAnchor, mPanel.cachedTransform, handles, 1, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.rightAnchor, mPanel.cachedTransform, handles, 2, id);
            UIWidgetInspector.DrawAnchorHandle(mPanel.bottomAnchor, mPanel.cachedTransform, handles, 3, id);
        }

        if (type == EventType.Repaint)
        {
            bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
            if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control)
            {
                showDetails = true;
            }
            if (NGUITools.GetActive(mPanel) && mPanel.parent == null)
            {
                showDetails = true;
            }
            if (showDetails)
            {
                NGUIHandles.DrawSize(handles, Mathf.RoundToInt(mPanel.width), Mathf.RoundToInt(mPanel.height));
            }
        }

        bool canResize = (mPanel.clipping != UIDrawCall.Clipping.None);

        // NOTE: Remove this part when it's possible to neatly resize rotated anchored panels.
        if (canResize && mPanel.isAnchored)
        {
            Quaternion rot = mPanel.cachedTransform.localRotation;
            if (Quaternion.Angle(rot, Quaternion.identity) > 0.01f)
            {
                canResize = false;
            }
        }

        bool[] resizable = new bool[8];

        resizable[4] = canResize;                    // left
        resizable[5] = canResize;                    // top
        resizable[6] = canResize;                    // right
        resizable[7] = canResize;                    // bottom

        resizable[0] = resizable[7] && resizable[4]; // bottom-left
        resizable[1] = resizable[5] && resizable[4]; // top-left
        resizable[2] = resizable[5] && resizable[6]; // top-right
        resizable[3] = resizable[7] && resizable[6]; // bottom-right

        UIWidget.Pivot pivotUnderMouse = UIWidgetInspector.GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);

        switch (type)
        {
        case EventType.Repaint:
        {
            Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
            Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);

            if ((v2 - v0).magnitude > 60f)
            {
                Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
                Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);

                Handles.BeginGUI();
                {
                    for (int i = 0; i < 4; ++i)
                    {
                        DrawKnob(handles[i], id, resizable[i]);
                    }

                    if (Mathf.Abs(v1.y - v0.y) > 80f)
                    {
                        if (mPanel.leftAnchor.target == null || mPanel.leftAnchor.absolute != 0)
                        {
                            DrawKnob(handles[4], id, resizable[4]);
                        }

                        if (mPanel.rightAnchor.target == null || mPanel.rightAnchor.absolute != 0)
                        {
                            DrawKnob(handles[6], id, resizable[6]);
                        }
                    }

                    if (Mathf.Abs(v3.x - v0.x) > 80f)
                    {
                        if (mPanel.topAnchor.target == null || mPanel.topAnchor.absolute != 0)
                        {
                            DrawKnob(handles[5], id, resizable[5]);
                        }

                        if (mPanel.bottomAnchor.target == null || mPanel.bottomAnchor.absolute != 0)
                        {
                            DrawKnob(handles[7], id, resizable[7]);
                        }
                    }
                }
                Handles.EndGUI();
            }
        }
        break;

        case EventType.MouseDown:
        {
            if (actionUnderMouse != UIWidgetInspector.Action.None)
            {
                mStartMouse     = e.mousePosition;
                mAllowSelection = true;

                if (e.button == 1)
                {
                    if (e.modifiers == 0)
                    {
                        GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                        e.Use();
                    }
                }
                else if (e.button == 0 && actionUnderMouse != UIWidgetInspector.Action.None &&
                         UIWidgetInspector.Raycast(handles, out mStartDrag))
                {
                    mWorldPos             = t.position;
                    mLocalPos             = t.localPosition;
                    mStartRot             = t.localRotation.eulerAngles;
                    mStartDir             = mStartDrag - t.position;
                    mStartCR              = mPanel.baseClipRegion;
                    mDragPivot            = pivotUnderMouse;
                    mActionUnderMouse     = actionUnderMouse;
                    GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                    e.Use();
                }
            }
        }
        break;

        case EventType.MouseUp:
        {
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;

                if (e.button < 2)
                {
                    bool handled = false;

                    if (e.button == 1)
                    {
                        // Right-click: Open a context menu listing all widgets underneath
                        NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
                        handled = true;
                    }
                    else if (mAction == UIWidgetInspector.Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the topmost widget
                            NGUIEditorTools.SelectWidget(e.mousePosition);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        Vector3 pos = t.localPosition;
                        pos.x           = Mathf.Round(pos.x);
                        pos.y           = Mathf.Round(pos.y);
                        pos.z           = Mathf.Round(pos.z);
                        t.localPosition = pos;
                        handled         = true;
                    }

                    if (handled)
                    {
                        e.Use();
                    }
                }

                // Clear the actions
                mActionUnderMouse = UIWidgetInspector.Action.None;
                mAction           = UIWidgetInspector.Action.None;
            }
            else if (mAllowSelection)
            {
                List <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                if (widgets.Count > 0)
                {
                    Selection.activeGameObject = widgets[0].gameObject;
                }
            }
            mAllowSelection = true;
        }
        break;

        case EventType.MouseDrag:
        {
            // Prevent selection once the drag operation begins
            bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
            if (dragStarted)
            {
                mAllowSelection = false;
            }

            if (GUIUtility.hotControl == id)
            {
                e.Use();

                if (mAction != UIWidgetInspector.Action.None || mActionUnderMouse != UIWidgetInspector.Action.None)
                {
                    Vector3 pos;

                    if (UIWidgetInspector.Raycast(handles, out pos))
                    {
                        if (mAction == UIWidgetInspector.Action.None && mActionUnderMouse != UIWidgetInspector.Action.None)
                        {
                            // Wait until the mouse moves by more than a few pixels
                            if (dragStarted)
                            {
                                if (mActionUnderMouse == UIWidgetInspector.Action.Move)
                                {
                                    NGUISnap.Recalculate(mPanel);
                                }
                                else if (mActionUnderMouse == UIWidgetInspector.Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                }
                                else if (mActionUnderMouse == UIWidgetInspector.Action.Scale)
                                {
                                    mStartCR   = mPanel.baseClipRegion;
                                    mDragPivot = pivotUnderMouse;
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != UIWidgetInspector.Action.None)
                        {
                            NGUIEditorTools.RegisterUndo("Change Rect", t);
                            NGUIEditorTools.RegisterUndo("Change Rect", mPanel);

                            if (mAction == UIWidgetInspector.Action.Move)
                            {
                                Vector3 before      = t.position;
                                Vector3 beforeLocal = t.localPosition;
                                t.position = mWorldPos + (pos - mStartDrag);
                                pos        = NGUISnap.Snap(t.localPosition, mPanel.localCorners,
                                                           e.modifiers != EventModifiers.Control) - beforeLocal;
                                t.position = before;

                                NGUIMath.MoveRect(mPanel, pos.x, pos.y);
                            }
                            else if (mAction == UIWidgetInspector.Action.Rotate)
                            {
                                Vector3 dir   = pos - t.position;
                                float   angle = Vector3.Angle(mStartDir, dir);

                                if (angle > 0f)
                                {
                                    float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
                                    if (dot < 0f)
                                    {
                                        angle = -angle;
                                    }
                                    angle = mStartRot.z + angle;
                                    angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
                                            Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == UIWidgetInspector.Action.Scale)
                            {
                                // World-space delta since the drag started
                                Vector3 delta = pos - mStartDrag;

                                // Adjust the widget's position and scale based on the delta, restricted by the pivot
                                AdjustClipping(mPanel, mLocalPos, mStartCR, delta, mDragPivot);
                            }
                        }
                    }
                }
            }
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 0f, 1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 0f, -1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, -1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
                NGUIMath.MoveRect(mPanel, 1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != UIWidgetInspector.Action.None)
                    {
                        Undo.PerformUndo();
                    }

                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;

                    mActionUnderMouse = UIWidgetInspector.Action.None;
                    mAction           = UIWidgetInspector.Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
Пример #8
0
    void DrawResList()
    {
        if (string.IsNullOrEmpty(selectService))
        {
            return;
        }
        int startX      = serviceListTabWidth + 2;
        int scrollWidth = Screen.width - startX - 2;

        nowResRootPath = resRubTypeList[resSubType] + nowSubDic;

        Handles.BeginGUI();
        Handles.color = Color.black;
        float tempY = position.height - RES_LIST_HEIGHT_OFFY;

        Handles.DrawLine(new Vector3(startX, tempY), new Vector3(position.width, tempY));
        Handles.EndGUI();

        Rect rectArea = new Rect(serviceListTabWidth, RES_LIST_START_Y, position.width - serviceListTabWidth, position.height - RES_LIST_HEIGHT_OFFY - RES_LIST_START_Y);

        GUILayout.BeginArea(rectArea);
        if (Directory.Exists(nowResRootPath) == false)
        {
            GUILayout.Label("不存在此目录:" + nowResRootPath);
            if (GUILayout.Button("创建(带ABName)", GUILayout.Width(serviceListTabWidth - 22)))
            {
                if (UnityEditor.EditorUtility.DisplayDialog("创建目录", "是否创建目录并设置ABName:\n" + nowResRootPath + "", "确认", "取消"))
                {
                    ServiceResSelectorUtil.CreateDirectory(nowResRootPath);
                }
            }
            if (GUILayout.Button("创建(不带ABName)", GUILayout.Width(serviceListTabWidth - 22)))
            {
                if (UnityEditor.EditorUtility.DisplayDialog("创建目录", "是否创建目录:\n" + nowResRootPath + "", "确认", "取消"))
                {
                    ServiceResSelectorUtil.CreateDirectory(nowResRootPath, false);
                }
            }
        }
        else
        {
            nowResList  = GetResList(nowResRootPath);
            scrollWidth = Mathf.Max(100, scrollWidth);

            resListScrollPos = GUILayout.BeginScrollView(resListScrollPos, GUILayout.Width(scrollWidth), GUILayout.Height(position.height - RES_LIST_HEIGHT_OFFY - RES_LIST_START_Y));
            int  col_show_count = (scrollWidth) / (resItemSize + 10);
            int  offY           = RES_ITEM_LABEL_HEIGHT + 2;
            bool isMinMode      = resItemSize == MIN_RES_ITEM_SIZE;
            if (isMinMode)
            {
                col_show_count            = 1;
                offY                      = 0;
                resNameGUIStyle.alignment = TextAnchor.MiddleLeft;
            }
            else
            {
                resNameGUIStyle.alignment = TextAnchor.MiddleCenter;
            }
            col_show_count = Mathf.Max(1, col_show_count); //the following for-loop will run forever if we limit this
            int total_count = nowResList.Count;
            int row_index   = 0;
            Dictionary <int, Rect> rectList = new Dictionary <int, Rect>();
            for (int res_index = 0; res_index < total_count;)
            {
                GUILayout.BeginHorizontal();
                for (int col_index = 0; col_index < col_show_count && res_index < total_count; ++col_index)
                {
                    Object res       = nowResList[res_index];
                    Rect   draw_rect = DrawResItem(row_index, col_index, res, offY, isMinMode, scrollWidth);
                    rectList[res_index] = draw_rect;
                    ++res_index;
                }
                GUILayout.EndHorizontal();
                row_index++;
            }
            GUILayout.Space(row_index * (resItemSize + offY));
            if (total_count == 0)
            {
                GUILayout.Label("当前目录为空,请拖资源进来");
            }
            GUILayout.EndScrollView();
            CheckEvent(rectList, nowResList, rectArea);
        }
        GUILayout.EndArea();
        Rect sliderRect = new Rect(position.width - 100, position.height - 20, 150, 20);

        resItemSize = (int)EditorGUI.Slider(sliderRect, resItemSize, MIN_RES_ITEM_SIZE, MAX_RES_ITEM_SIZE);
        //resItemSize = (int)GUILayout.HorizontalSlider(resItemSize, MIN_RES_ITEM_SIZE, MAX_RES_ITEM_SIZE, GUILayout.Width(100));
        if (nowSelectObj != null)
        {
            Rect   selNameRect = new Rect(startX, position.height - 20, position.width - 250, 20);
            string path        = AssetDatabase.GetAssetPath(nowSelectObj);
            EditorGUI.LabelField(selNameRect, "", Path.GetFileName(path));
        }
    }
Пример #9
0
    //Handles the options that appear on this Editor Window that the user can change
    private void OnGUI()
    {
        //If the user is selecting an object that has a Tile Map and a text source, the map's settings can be changed
        if (this.mapOrigin != null && this.mapOrigin.xmlFile != null)
        {
            //Begins a check to see if any properties are changed
            EditorGUI.BeginChangeCheck();

            //Creating a header that displays the name of the tile map object we're editing
            GUILayout.Label("Currently Editing " + this.mapOrigin.name, EditorStyles.largeLabel);

            EditorGUILayout.Space();

            //Setting it so that this whole editor is within a scroll view
            this.scrollPos = GUILayout.BeginScrollView(this.scrollPos, true, true);

            //Creating a fold out section on the window that lets the user set the width and height of the selected tile map
            this.showDimensions = EditorGUILayout.Foldout(this.showDimensions, "Map Details");
            if (this.showDimensions)
            {
                EditorGUI.indentLevel++;

                //Created a field where the user can select the sprite that this map uses as a texture
                this.tileMapSprite = EditorGUILayout.ObjectField("Tile Map Texture Sprite", this.tileMapSprite, typeof(Sprite),
                                                                 GUILayout.Width(250)) as Sprite;

                //Created an input field to set the number of pixels shown for each tile
                this.mapOrigin.pixelWidth = EditorGUILayout.IntField("Tile Pixel Size", this.mapOrigin.pixelWidth, GUILayout.Width(200));
                if (this.mapOrigin.pixelWidth < 1)
                {
                    this.mapOrigin.pixelWidth = 1;
                }

                //Created an input field to set the width/height of tiles on the map
                this.mapOrigin.tileSize = EditorGUILayout.FloatField("Tile Grid Height/Width", this.mapOrigin.tileSize, GUILayout.Width(200));


                EditorGUILayout.Space();

                //Grouping the "Tiles Up" and "Tiles Down" input fields on the same line
                EditorGUILayout.BeginHorizontal();
                //Created a placeholderint and input field to set the number of rows above the origin
                int phUP = this.mapOrigin.tilesUp;
                phUP = EditorGUILayout.IntField("Rows Up", phUP, GUILayout.Width(200));

                //Preventing the number of tiles from going below 0
                if (phUP < 0)
                {
                    phUP = 0;
                }

                //If the placeholder int is different from the current value, the current value is changed
                if (phUP != this.mapOrigin.tilesUp)
                {
                    this.mapOrigin.tilesUp = this.mapOrigin.DetermineGridChange(phUP, Directions.Up);
                }

                //Created a placeholder int and input field to set the number of rows below the origin
                int phDown = this.mapOrigin.tilesDown;
                phDown = EditorGUILayout.IntField("Rows Down", phDown, GUILayout.Width(200));

                //Preventing the number of tiles from going below 0
                if (phDown < 0)
                {
                    phDown = 0;
                }

                //If the placeholder int is different from the current value, the current value is changed
                if (phDown != this.mapOrigin.tilesDown)
                {
                    this.mapOrigin.tilesDown = this.mapOrigin.DetermineGridChange(phDown, Directions.Down);
                }
                EditorGUILayout.EndHorizontal();


                //Grouping the "Tiles Left" and "Tiles Down" input fields on the same line
                EditorGUILayout.BeginHorizontal();
                //Created a placeholder int and input field to set the number of columns left of the origin
                int phLeft = this.mapOrigin.tilesLeft;
                phLeft = EditorGUILayout.IntField("Columns Left", phLeft, GUILayout.Width(200));

                //Preventing the number of tiles from going below 0
                if (phLeft < 0)
                {
                    phLeft = 0;
                }

                //If the placeholder int is different from the current value, the current value is changed
                if (phLeft != this.mapOrigin.tilesLeft)
                {
                    this.mapOrigin.tilesLeft = this.mapOrigin.DetermineGridChange(phLeft, Directions.Left);
                }

                //Created a placeholder int and input field to set the number of columns right of the origin
                int phRight = this.mapOrigin.tilesRight;
                phRight = EditorGUILayout.IntField("Columns Right", phRight, GUILayout.Width(200));

                //Preventing the number of tiles from going below 0
                if (phRight < 0)
                {
                    phRight = 0;
                }

                //If the placeholder int is different from the current value, the current value is changed
                if (phRight != this.mapOrigin.tilesRight)
                {
                    this.mapOrigin.tilesRight = this.mapOrigin.DetermineGridChange(phRight, Directions.Right);
                }
                EditorGUILayout.EndHorizontal();

                EditorGUI.indentLevel--;
            }

            EditorGUILayout.Space();

            //Creating a fold out section on the window that lets the user set what colors the editor uses
            this.showColorPicker = EditorGUILayout.Foldout(this.showColorPicker, "Editor Colors");
            if (this.showColorPicker)
            {
                EditorGUI.indentLevel++;

                //Color pickers for the rectangle in the scene
                this.outlineColor     = EditorGUILayout.ColorField("Map Outline Color", this.outlineColor, GUILayout.MaxWidth(300));
                this.outlineEditColor = EditorGUILayout.ColorField("Map Editing Color", this.outlineEditColor, GUILayout.MaxWidth(300));

                EditorGUILayout.Space();

                //Color pickers for the grid in the editor
                this.gridColor         = EditorGUILayout.ColorField("Tile Grid Color", this.gridColor, GUILayout.MaxWidth(300));
                this.hilightTileColor  = EditorGUILayout.ColorField("Hilight Tile Color", this.hilightTileColor, GUILayout.MaxWidth(300));
                this.selectedTileColor = EditorGUILayout.ColorField("Selected Tile Color", this.selectedTileColor, GUILayout.MaxWidth(300));

                EditorGUI.indentLevel--;
            }

            EditorGUILayout.Space();

            EditorGUILayout.BeginHorizontal(GUILayout.Width(200));
            //Created a boolean input box that allows the player to toggle editing mode for the tile map
            this.enableMapEditing = EditorGUILayout.Toggle("Enable Tile Map Editing", this.enableMapEditing);

            EditorGUILayout.Space();

            //Created a boolean input box that allows the player to toggle if the tile map size should be shown
            this.showTileMapSize = EditorGUILayout.Toggle("Show Tile Map Outline", this.showTileMapSize);

            EditorGUILayout.EndHorizontal();

            EditorGUILayout.Space();

            //As long as this tile map has a source texture, this tile section will draw
            if (this.tileMapSprite != null)
            {
                //Created a fold out section on the window that lets the user select what tile they want to place
                this.showTiles = EditorGUILayout.Foldout(this.showTiles, "Tiles");
                if (this.showTiles)
                {
                    EditorGUI.indentLevel++;

                    //Created a slider to let the user determine how zoomed in the tiles are
                    this.zoom = EditorGUILayout.Slider("Zoom", this.zoom, 0.1f, 5, GUILayout.Width(300));

                    EditorGUI.indentLevel--;

                    //Starts a scroll view that displays all tiles on the current source texture
                    using (var scrollView = new EditorGUILayout.ScrollViewScope(this.scrollPos * this.zoom, false, false,
                                                                                GUILayout.MinWidth(Screen.width),
                                                                                GUILayout.MinHeight(Screen.height),
                                                                                GUILayout.Width(this.tileMapSprite.texture.width * this.zoom),
                                                                                GUILayout.Height(this.tileMapSprite.texture.height * this.zoom)))
                    {
                        scrollView.handleScrollWheel = false;

                        //First we draw the full texture for the tile map we're using
                        GUI.DrawTexture(new Rect(0, 0, this.tileMapSprite.texture.width * this.zoom, this.tileMapSprite.texture.height * this.zoom), this.tileMapSprite.texture);

                        //Then we draw lines to slice it into the individual tiles
                        Handles.BeginGUI();
                        Handles.color = this.gridColor;

                        //Loops through a number of times equal to how many tiles wide the texture is
                        for (int w = 0; w < (this.tileMapSprite.texture.width / this.mapOrigin.pixelWidth); ++w)
                        {
                            //Draws vertical lines on the texture
                            Vector3 start = new Vector3(w * this.mapOrigin.pixelWidth * this.zoom, 0);
                            Vector3 end   = new Vector3(w * this.mapOrigin.pixelWidth * this.zoom, this.tileMapSprite.texture.height * this.zoom);

                            Handles.DrawLine(start, end);
                        }

                        //Loops through a number of times equal to how many tiles high the texture is
                        for (int h = 0; h < (this.tileMapSprite.texture.height / this.mapOrigin.pixelWidth); ++h)
                        {
                            //Draws horizontal lines on the texture
                            Vector3 start = new Vector3(0, h * this.mapOrigin.pixelWidth * this.zoom);
                            Vector3 end   = new Vector3(this.tileMapSprite.texture.width * this.zoom, h * this.mapOrigin.pixelWidth * this.zoom);

                            Handles.DrawLine(start, end);
                        }


                        //Draws a box around the current tile the mouse is on as long as the mouse is over our tiles
                        if (Event.current.mousePosition.x >= 0 && Event.current.mousePosition.y >= 0 &&
                            Event.current.mousePosition.x < (this.tileMapSprite.texture.width * this.zoom) &&
                            Event.current.mousePosition.y < (this.tileMapSprite.texture.height * this.zoom))
                        {
                            //Now we draw a box around whichever tile the mouse is over
                            Handles.color = this.hilightTileColor;

                            //Finds the XY coordinate on the tile map texture
                            int xCoord = Mathf.FloorToInt(Event.current.mousePosition.x / (this.mapOrigin.pixelWidth * this.zoom));
                            int yCoord = Mathf.FloorToInt(Event.current.mousePosition.y / (this.mapOrigin.pixelWidth * this.zoom));

                            //Handles.DrawSolidRectangleWithOutline(new Rect(0, 0, Event.current.mousePosition.x, Event.current.mousePosition.y), new Color(0, 1, 0, 0.1f), Color.green);
                            Handles.DrawSolidRectangleWithOutline(new Rect(xCoord * this.mapOrigin.pixelWidth * this.zoom, yCoord * this.mapOrigin.pixelWidth * this.zoom,
                                                                           this.mapOrigin.pixelWidth * this.zoom, this.mapOrigin.pixelWidth * this.zoom),
                                                                  new Color(this.hilightTileColor.r, this.hilightTileColor.g, this.hilightTileColor.b, 0.1f), this.hilightTileColor);

                            //When the player clicks on a new tile, that one is set to the current selection
                            if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
                            {
                                this.selectedTile[0] = xCoord;
                                this.selectedTile[1] = yCoord;
                            }

                            Repaint();
                        }

                        //Draws a box around the currently selected tile
                        Handles.color = this.selectedTileColor;
                        Handles.DrawSolidRectangleWithOutline(new Rect(this.selectedTile[0] * this.mapOrigin.pixelWidth * this.zoom,
                                                                       this.selectedTile[1] * this.mapOrigin.pixelWidth * this.zoom,
                                                                       this.mapOrigin.pixelWidth * this.zoom,
                                                                       this.mapOrigin.pixelWidth * this.zoom),
                                                              new Color(this.selectedTileColor.r, this.selectedTileColor.g, this.selectedTileColor.b, 0.1f),
                                                              this.selectedTileColor);

                        Handles.EndGUI();
                    }
                }
            }

            GUILayout.EndScrollView();

            //If any properties were changed, the scene and selected tile map are set to dirty
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(this.mapOrigin.gameObject, "Tile Map Editor Change");
                EditorUtility.SetDirty(this.mapOrigin.gameObject);
                UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
            }
        }
        //If the user is selecting an object that has a Tile Map but DOESN'T have a text source, they must create one
        else if (this.mapOrigin != null && this.mapOrigin.xmlFile == null)
        {
            //Created a few labels and a text field telling the user that they have to create a file to save map data
            GUILayout.Label("This tile map has no save document.");
            GUILayout.Label("Either set the file in the Tile Map Origin");
            GUILayout.Label("component, or create a new file.");

            EditorGUILayout.Space();
            EditorGUILayout.Space();

            GUILayout.BeginHorizontal(GUILayout.Width(275));
            GUILayout.Label("New tile map file name:  ");
            this.tileMapFileName = GUILayout.TextField(this.tileMapFileName);
            GUILayout.EndHorizontal();

            //Created a button that generates a new text source for the selected tile map
            if (GUILayout.Button("Create New Save"))
            {
                TextAsset xmlFile;

                //First we check to see if a file with that name exists. If not, it's created
                if (Resources.Load("TileMapFiles/" + this.tileMapFileName, typeof(TextAsset)) == null)
                {
                    //Checking to make sure the Resources and TileMapFiles folders exists
                    if (!System.IO.Directory.Exists(Application.dataPath + "/Assets/Resources/"))
                    {
                        //If not, they are created
                        System.IO.DirectoryInfo moo = System.IO.Directory.CreateDirectory(Application.dataPath + "/Resources/");
                        System.IO.Directory.CreateDirectory(Application.dataPath + "/Resources/TileMapFiles/");
                    }
                    //If the Resources folder exists but TileMapFiles doesn't, it's created
                    else if (!System.IO.Directory.Exists(Application.dataPath + "Assets/Resources/TileMapFiles/"))
                    {
                        System.IO.Directory.CreateDirectory(Application.dataPath + "/Resources/TileMapFiles/");
                    }

                    //If the given file name is allowed (makes it past all of the checks in IsFileNameAllowed function)
                    if (this.IsFileNameAllowed(this.tileMapFileName))
                    {
                        //Created a file path for the new xml file in the Resources folder
                        string filePath = Application.dataPath + "/Resources/TileMapFiles/" + this.tileMapFileName + ".xml";

                        //Creating the file using the file path string and refreshing the asset database so it shows up in editor
                        System.IO.File.WriteAllText(filePath, "");
                        AssetDatabase.Refresh();
                    }
                }


                //Sets the xml source file for the selected map origin to the newly created xml file
                xmlFile = Resources.Load("TileMapFiles/" + this.tileMapFileName, typeof(TextAsset)) as TextAsset;
                this.mapOrigin.xmlFile = xmlFile;

                //Tells the tile map to set up the XML info for the new file
                this.mapOrigin.GenerateBaseXML();

                //Sets the selected tile map and scene as "dirty" which means that they need to be saved
                UnityEditor.Undo.RecordObject(this.mapOrigin.gameObject, "Set XML File as Text Asset");
                EditorUtility.SetDirty(this.mapOrigin.gameObject);
                UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
            }
        }
        //Otherwise, there are no options to change because no tile map is selected
        else
        {
            GUILayout.Label("No tile map selected", EditorStyles.centeredGreyMiniLabel);
            GUILayout.Label("Select an object with the TileMapOrigin component", EditorStyles.centeredGreyMiniLabel);
        }
    }
Пример #10
0
    private void OnSceneGUI(SceneView sceneView)
    {
        //获取TileMap组件
        Tilemap map = FindObjectOfType <Tilemap>();

        if (map == null)
        {
            return;
        }
        //获取鼠标位置,当前是Scene视图坐标
        Vector2 mousePos = Event.current.mousePosition;
        //获取Scene窗体的Camera
        Camera cam = sceneView.camera;
        //Scene窗体中的缩放应当被考虑进去
        float mult = EditorGUIUtility.pixelsPerPoint;

        //将Scene视图的坐标转换成屏幕坐标
        mousePos.y = cam.pixelHeight - mousePos.y * mult;
        mousePos.x = mousePos.x * mult;
        //将屏幕坐标转成世界坐标
        mousePos = sceneView.camera.ScreenToWorldPoint(mousePos);
        Vector3Int vec3 = map.WorldToCell(mousePos);

        string    str         = vec3.ToString();
        int       campID      = -1;
        int       battleUnit  = 0;
        string    terrianName = "";
        bool      opp         = false;
        BattleMap tmb         = FindObjectOfType <BattleMap>();

        if (tmb != null)
        {
            if (tmb.Map != null)
            {
                opp = true;
                int x = tmb.Convert2ArrayIndex(vec3)[0];
                int y = tmb.Convert2ArrayIndex(vec3)[1];
                if (x >= 0 && x < tmb.Map.GetLength(0) && y >= 0 && y < tmb.Map.GetLength(1))
                {
                    campID      = tmb.Map[x, y].CampID;
                    battleUnit  = tmb.Map[x, y].battleUnit;
                    terrianName = tmb.Map[x, y].CurTerrian.name;
                    //  campPlots = tmb.campdi[tmb.Map[x, y].CampID].ownedLands.Count;
                }
            }
        }
        //绘制Label
        Handles.BeginGUI();
        GUIStyle fontStyle = new GUIStyle();

        fontStyle.normal.textColor = Color.green; //设置字体颜色
        fontStyle.fontSize         = 18;          //字体大小
        GUI.Label(new Rect(0f, 120f, 500f, 100f), "当前地块坐标:" + str, fontStyle);
        GUI.Label(new Rect(0f, 150f, 500f, 100f), "当前地块阵营:" + campID.ToString(), fontStyle);
        GUI.Label(new Rect(0f, 180f, 500f, 100f), "当前地块作战单位:" + battleUnit.ToString(), fontStyle);
        GUI.Label(new Rect(0f, 210f, 500f, 100f), "当前地块地形:" + terrianName, fontStyle);
        // GUI.Label(new Rect(0f, 240f, 500f, 100f), "当前阵营地块数量:" + campPlots, fontStyle);
        GUI.Label(new Rect(0f, 270f, 500f, 100f), "地图是否为空:" + opp, fontStyle);
        Handles.EndGUI();

        //刷新界面,保证坐标实时跟随鼠标
        sceneView.Repaint();
        HandleUtility.Repaint();
    }
Пример #11
0
    private void OnGUI()
    {
        CheckDialogue();

        if (!CurrentDialogue)
        {
            GUILayout.Label("This object has no Dialogues component");
            //Add option to create
            return;
        }

        if (CurrentDialogue.Set.Count == 0)
        {
            CurrentDialogue.Set.Add(new Dialogues.WindowSet());
            CurrentDialogue.CurrentSet = 0;
            FirstSet = true;
        }

        CheckConnections();

        //If texture wasn't setup, set it up
        if (BackgroundTexture == null)
        {
            MakeTextures();
        }

        if (CurrentDialogue.TabList.Count == 0)
        {
            GUIStyle Style = GUI.skin.GetStyle("Label");
            Style.alignment = TextAnchor.MiddleCenter;

            GUILayout.Label("\n\nThere are no existing Dialogue Trees\nClick the 'New' button to add a tab", Style);
        }
        else
        {
            CurrentDialogue.CurrentSet = CurrentTab;

            //Creates large scroll view for the work area
            ScrollPosition = GUI.BeginScrollView(new Rect(0, 0, position.width, position.height), ScrollPosition, new Rect(Vector2.zero, WorkSize), GUIStyle.none, GUIStyle.none);
            //Makes the background a dark gray
            GUI.DrawTexture(new Rect(0, 0, WorkSize.x, WorkSize.y), BackgroundTexture, ScaleMode.StretchToFill);
            Handles.BeginGUI();

            //Draws the small, light squares all over the work area
            int Count = 0;
            while ((Count * 10) < WorkSize.x)
            {
                EditorGUI.DrawRect(new Rect(Count * 10, 0, 2, WorkSize.y), SmallLines);
                Count++;
            }
            Count = 0;
            while ((Count * 10) < WorkSize.y)
            {
                EditorGUI.DrawRect(new Rect(0, Count * 10, WorkSize.x, 2), SmallLines);
                Count++;
            }

            //Draws the larger, thicker lines on the work area
            for (int i = 0; i < WorkSize.x / 100; i++)
            {
                EditorGUI.DrawRect(new Rect(i * 100, 0, 2, WorkSize.y), BigLines);
            }
            for (int i = 0; i < WorkSize.y / 100; i++)
            {
                EditorGUI.DrawRect(new Rect(0, i * 100, WorkSize.x, 2), BigLines);
            }

            DrawConnections(Color.white);

            Handles.EndGUI();

            BeginWindows();
            ClearIds();

            BuildWindows();

            if (CurrentDialogue.Set[CurrentDialogue.CurrentSet].NewWindowOpen)
            {
                //if (NewTree == null) NewTree = new Rect(50, 50, 400, 150);
                NewTree = GUI.Window(99999, NewTree, AddNewWindow, "Add New Dialogue Tree");
            }

            EndWindows();

            GUI.EndScrollView();
            GUILayout.BeginArea(new Rect(0, 20, Screen.width, 20));
            CurrentTab = GUILayout.Toolbar(CurrentTab, CurrentDialogue.TabList.ToArray());
            GUILayout.EndArea();

            if (new Rect(0, 0, position.width, position.height).Contains(Event.current.mousePosition))
            {
                if (Event.current.button == 1)
                {
                    GenericMenu Menu = new GenericMenu();

                    BuildMenus(Menu);
                    if (CheckDialogueExists())
                    {
                        Menu.AddItem(new GUIContent("Clear All"), false, Clear);
                    }
                    Menu.ShowAsContext();
                }
            }

            if (new Rect(0, 0, position.width, position.height).Contains(Event.current.mousePosition))
            {
                if (Event.current.button == 2 && Event.current.type == EventType.MouseDrag)
                {
                    Vector2 CurrentPos = Event.current.mousePosition;

                    if (Vector2.Distance(CurrentPos, PreviousPosition) < 50)
                    {
                        float x = PreviousPosition.x - CurrentPos.x;
                        float y = PreviousPosition.y - CurrentPos.y;

                        ScrollPosition.x += x;
                        ScrollPosition.y += y;
                        Event.current.Use();
                    }
                    PreviousPosition = CurrentPos;
                }
            }
        }

        //Extra layouts
        GUILayout.BeginArea(new Rect(0, 0, Screen.width, 50));
        GUILayout.BeginHorizontal("GUIEditor.BreadcrumbLeft");
        if (GUILayout.Button("New Dialogue Tree", new GUIStyle("TE toolbarbutton"), GUILayout.Width(150), GUILayout.Height(18)))
        {
            CurrentDialogue.Set[CurrentDialogue.CurrentSet].NewWindowOpen = true;
            NewTree     = new Rect(50 + ScrollPosition.x, 50 + ScrollPosition.y, 400, 150);
            NewTreeName = "";
            NewTreeInfo = "";
        }

        if (GUILayout.Button("Remove Tree", new GUIStyle("TE toolbarbutton"), GUILayout.Width(100), GUILayout.Height(18)))
        {
            CurrentDialogue.Set.RemoveAt(CurrentTab);
            CurrentDialogue.TabList.RemoveAt(CurrentTab);
            CurrentDialogue.CurrentSet = 0;
            CurrentTab = 0;
        }

        GUILayout.EndHorizontal();
        GUILayout.EndArea();

        if (CurrentDialogue.Set.Count > 0 && CurrentDialogue.TabList.Count == 0)
        {
            BeginWindows();

            if (CurrentDialogue.Set[CurrentDialogue.CurrentSet].NewWindowOpen)
            {
                if (NewTree == null)
                {
                    NewTree = new Rect(50, 50, 400, 150);
                }
                NewTree = GUI.Window(99999, NewTree, AddNewWindow, "Add New Dialogue Tree");
            }

            EndWindows();
        }

        //Found this easy cut/copy/paste solution from http://answers.unity3d.com/questions/181333/how-can-i-add-copy-and-paste-support-for-my-editor.html
        TextEditor textEditor = EditorGUIUtility.GetStateObject(typeof(TextEditor), EditorGUIUtility.keyboardControl) as TextEditor;

        if (textEditor != null)
        {
            if (focusedWindow == this)
            {
                // shift + x
                if (Event.current.Equals(Event.KeyboardEvent("#x")))
                {
                    textEditor.Cut();
                }
                // shift + c
                if (Event.current.Equals(Event.KeyboardEvent("#c")))
                {
                    textEditor.Copy();
                }
                // shift + v
                if (Event.current.Equals(Event.KeyboardEvent("#v")))
                {
                    textEditor.Paste();
                }
            }
        }
    }
    void OnSceneGUI()
    {
        //get target's CoupledTris array
        //iterate through the array to find the mouseover tri
        //a) whose screenspace coord contains mousePos
        //b) if multiple tris are returned, select the one that is closest to camera pos
        //
        //clicking on the mouseover tri marks it as "Selected"
        //shift-Clike to DeSelect
        //
        //Draw suitable handles to represent various vectors and indeices of the selected tris



        Event         curEv     = Event.current;
        MeshDataClass myTarget  = (MeshDataClass)target;
        int           controlID = GUIUtility.GetControlID(FocusType.Passive);
        Camera        curCam    = Camera.current;

        if (curCam == null || myTarget.coupledTris == null)
        {
            return;
        }
        CoupledTri mouseOverTri = GetMouseOverTri(myTarget.coupledTris, curEv, curCam);
        GUIStyle   newStyle     = new GUIStyle();

        newStyle.richText = true;

        if (myTarget.isReady)
        {
            #region Control Switch
            //This switch controls input behaviour when the target gameobject is selected
            //in the hierarchy
            switch (curEv.GetTypeForControl(controlID))
            {
            case EventType.MouseDown:
                GUIUtility.hotControl = controlID;

                //CheckForPositions(curEv.mousePosition);
                curEv.Use();
                break;

            case EventType.MouseUp:
                GUIUtility.hotControl = 0;
                if (curEv.modifiers == EventModifiers.Shift)
                {
                    if (myTarget.activeZone.zoneTris.Contains(mouseOverTri))
                    {
                        myTarget.activeZone.zoneTris.Remove(mouseOverTri);
                    }

                    Debug.Log("shift click");
                    curEv.Use();
                    break;
                }

                if (!myTarget.activeZone.zoneTris.Contains(mouseOverTri) || myTarget.activeZone.zoneTris.Count == 0)
                {
                    if (mouseOverTri.triName != "ng")
                    {
                        myTarget.activeZone.zoneTris.Add(mouseOverTri);
                    }
                }
                Debug.Log("click");

                curEv.Use();
                break;

            case EventType.MouseDrag:
                GUIUtility.hotControl = controlID;
                //CheckForPositions(curEv.mousePosition);

                curEv.Use();
                break;

            case EventType.KeyDown:
                if (curEv.keyCode == KeyCode.Escape)
                {
                    // Do something on pressing Escape
                }
                if (curEv.keyCode == KeyCode.Space)
                {
                    // Do something on pressing Spcae
                }
                if (curEv.keyCode == KeyCode.S)
                {
                    // Do something on pressing S
                }
                break;

            case EventType.layout:
                HandleUtility.AddDefaultControl(controlID);
                break;
            }
            #endregion


            //drawing hover tri
            if (mouseOverTri.triName != "ng")
            {
                Handles.Label(mouseOverTri.centroid, "<color=#ffffffff>" + mouseOverTri.triIndex.ToString() + "</color>", newStyle);
                Color newColor = Color.blue;
                newColor.a   *= .2f;
                Handles.color = newColor;

                Handles.DrawAAConvexPolygon(mouseOverTri.p0, mouseOverTri.p1, mouseOverTri.p2);
            }

            //drawing zones tris
            if (myTarget.meshZones.Count != 0)
            {
                for (int i = 0; i < myTarget.meshZones.Count; i++)
                {
                    Handles.color = myTarget.meshZones[i].zoneColor;

                    if (myTarget.meshZones[i].zoneTris.Count != 0)
                    {
                        for (int j = 0; j < myTarget.meshZones[i].zoneTris.Count; j++)
                        {
                            Handles.DrawAAConvexPolygon
                                (myTarget.meshZones[i].zoneTris[j].p0,
                                myTarget.meshZones[i].zoneTris[j].p1,
                                myTarget.meshZones[i].zoneTris[j].p2);
                        }
                    }
                }
            }

            Handles.BeginGUI();
            GUILayout.BeginVertical();
            GUILayout.Button("Button", GUILayout.Width(100));            //it's here for some button action...remove if you don't need
            GUILayout.Label("Mesh Zones Count: " + myTarget.meshZones.Count.ToString());
            for (int i = 0; i < myTarget.meshZones.Count; i++)
            {
                GUILayout.Label("Mesh Zone " + i + " zone tris count: " + myTarget.meshZones[i].zoneTris.Count.ToString());
            }
            GUILayout.EndVertical();
            Handles.EndGUI();
        }

        #region alternative switch
//switch (curEv.type)
//		{
//		case EventType.mouseUp:
//
////			this works
////			Debug.Log("mousepos" + curEv.mousePosition/*TopLeft is 0, 0 */);
////			Vector3 targetPos = curCam.WorldToScreenPoint(myTarget.trans.position);
////			Vector2 correctedPos = new Vector2(targetPos.x, curCam.pixelHeight - targetPos.y);
//			//Debug.Log("targetPos" + correctedPos);
//
//			//Debug.Log("Hi");
//
//			curEv.Use();
//			break;
//
//		case EventType.layout:
//
//			HandleUtility.AddDefaultControl(controlID);
//
//			break;
//		}
        #endregion



        if (GUI.changed)
        {
            EditorUtility.SetDirty(myTarget);
        }
    }
Пример #13
0
    //if this path is selected, display small info boxes above all waypoint positions
    //also display handles for the waypoints
    void OnSceneGUI()
    {
        //again, get waypoint array
        var waypoints = GetWaypointArray();

        //do not execute further code if we have no waypoints defined
        //(just to make sure, practically this can not occur)
        if (waypoints.Length == 0)
        {
            return;
        }
        Vector3 wpPos = Vector3.zero;
        float   size  = 1f;

        //loop through waypoint array
        for (int i = 0; i < waypoints.Length; i++)
        {
            if (!waypoints[i])
            {
                continue;
            }
            wpPos = waypoints[i].position;

            size = HandleUtility.GetHandleSize(wpPos) * 0.4f;

            //do not draw waypoint header if too far away
            if (size < 3f)
            {
                //begin 2D GUI block
                Handles.BeginGUI();
                //translate waypoint vector3 position in world space into a position on the screen
                var guiPoint = HandleUtility.WorldToGUIPoint(wpPos);
                //create rectangle with that positions and do some offset
                var rect = new Rect(guiPoint.x - 50.0f, guiPoint.y - 40, 100, 20);
                //draw box at position with current waypoint name
                GUI.Box(rect, waypoints[i].name);
                Handles.EndGUI(); //end GUI block
            }

            //draw handles per waypoint, clamp size
            Handles.color = color2.colorValue;
            size          = Mathf.Clamp(size, 0, 1.2f);

            #if UNITY_5_6_OR_NEWER
            Handles.FreeMoveHandle(wpPos, Quaternion.identity, size, Vector3.zero, (controlID, position, rotation, hSize, eventType) =>
            {
                Handles.SphereHandleCap(controlID, position, rotation, hSize, eventType);
                if (controlID == GUIUtility.hotControl && GUIUtility.hotControl != 0)
                {
                    activeNode = i;
                }
            });
            #else
            Handles.FreeMoveHandle(wpPos, Quaternion.identity, size, Vector3.zero, (controlID, position, rotation, hSize) =>
            {
                Handles.SphereCap(controlID, position, rotation, hSize);
                if (controlID == GUIUtility.hotControl && GUIUtility.hotControl != 0)
                {
                    activeNode = i;
                }
            });
            #endif

            Handles.RadiusHandle(waypoints[i].rotation, wpPos, size / 2);
        }

        if (activeNode > -1)
        {
            wpPos = waypoints[activeNode].position;
            Quaternion wpRot = waypoints[activeNode].rotation;
            switch (Tools.current)
            {
            case Tool.Move:
                if (Tools.pivotRotation == PivotRotation.Global)
                {
                    wpRot = Quaternion.identity;
                }

                Vector3 newPos = Handles.PositionHandle(wpPos, wpRot);
                if (wpPos != newPos)
                {
                    Undo.RecordObject(waypoints[activeNode], "Move Handle");
                    waypoints[activeNode].position = newPos;
                }
                break;

            case Tool.Rotate:
                Quaternion newRot = Handles.RotationHandle(wpRot, wpPos);

                if (wpRot != newRot)
                {
                    Undo.RecordObject(waypoints[activeNode], "Rotate Handle");
                    waypoints[activeNode].rotation = newRot;
                }
                break;
            }
        }

        //waypoint direction handles drawing
        Vector3[] pathPoints = new Vector3[waypoints.Length + 1];
        for (int i = 0; i < pathPoints.Length - 1; i++)
        {
            pathPoints[i] = waypoints[i].position;
        }
        pathPoints[pathPoints.Length - 1] = waypoints[0].position;

        //create list of path segments (list of Vector3 list)
        List <List <Vector3> > segments = new List <List <Vector3> >();
        int   curIndex = 0;
        float lerpVal  = 0f;

        //differ between linear and curved display
        switch (check1.boolValue)
        {
        case true:
            //convert waypoints to curved path points
            pathPoints = WaypointManager.GetCurved(pathPoints);
            //calculate approximate path point amount per segment
            int detail = Mathf.FloorToInt((pathPoints.Length - 1f) / (waypoints.Length - 1f));

            for (int i = 0; i < waypoints.Length - 1; i++)
            {
                float dist = Mathf.Infinity;
                //loop over path points to find single segments
                segments.Add(new List <Vector3>());

                //we are not checking for absolute path points on standard paths, because
                //path points could also be located before or after waypoint positions.
                //instead a minimum distance is searched which marks the nearest path point
                for (int j = curIndex; j < pathPoints.Length; j++)
                {
                    //add path point to current segment
                    segments[i].Add(pathPoints[j]);

                    //start looking for distance after a certain amount of path points of this segment
                    if (j >= (i + 1) * detail)
                    {
                        //calculate distance of current path point to waypoint
                        float pointDist = Vector3.Distance(waypoints[i].position, pathPoints[j]);
                        //we are getting closer to the waypoint
                        if (pointDist < dist)
                        {
                            dist = pointDist;
                        }
                        else
                        {
                            //current path point is more far away than the last one
                            //the segment ends here, continue with new segment
                            curIndex = j + 1;
                            break;
                        }
                    }
                }
            }
            break;

        case false:
            //detail for arrows between waypoints
            int lerpMax = 16;
            //loop over waypoints to add intermediary points
            for (int i = 0; i < waypoints.Length - 1; i++)
            {
                segments.Add(new List <Vector3>());
                for (int j = 0; j < lerpMax; j++)
                {
                    //linear lerp between waypoints to get additional points for drawing arrows at
                    segments[i].Add(Vector3.Lerp(pathPoints[i], pathPoints[i + 1], j / (float)lerpMax));
                }
            }
            break;
        }

        //loop over segments
        for (int i = 0; i < segments.Count; i++)
        {
            //loop over single positions on the segment
            for (int j = 0; j < segments[i].Count; j++)
            {
                //get current lerp value for interpolating rotation
                //draw arrow handle on current position with interpolated rotation
                lerpVal = j / (float)segments[i].Count;
                #if UNITY_5_6_OR_NEWER
                Handles.SphereHandleCap(0, segments[i][j], Quaternion.Lerp(waypoints[i].rotation, waypoints[i + 1].rotation, lerpVal), 0.35f, EventType.Repaint);
                #else
                Handles.SphereCap(0, segments[i][j], Quaternion.Lerp(waypoints[i].rotation, waypoints[i + 1].rotation, lerpVal), size);
                #endif
            }
        }
    }
    /// <summary>
    /// Make it possible to easily drag the transform around.
    /// </summary>

    public void OnSceneGUI()
    {
        NGUIEditorTools.HideMoveTool(true);
        if (!UIWidget.showHandles)
        {
            return;
        }
        if (UnityEditor.Tools.current != Tool.Move)
        {
            return;
        }

        MonoBehaviour mb = target as MonoBehaviour;

        if (mb.GetComponent <UIWidget>() != null)
        {
            return;
        }
        if (mb.GetComponent <UIPanel>() != null)
        {
            return;
        }

        Transform t = mb.transform;

        UIWidget[] widgets = t.GetComponentsInChildren <UIWidget>();

        Event     e            = Event.current;
        int       id           = GUIUtility.GetControlID(mHash, FocusType.Passive);
        EventType type         = e.GetTypeForControl(id);
        bool      isWithinRect = false;

        Vector3[] corners = null;
        Vector3[] handles = null;

        if (widgets.Length > 0)
        {
            Matrix4x4 worldToLocal = t.worldToLocalMatrix;
            Matrix4x4 localToWorld = t.localToWorldMatrix;
            Bounds    bounds       = new Bounds();

            // Calculate the local bounds
            for (int i = 0; i < widgets.Length; ++i)
            {
                Vector3[] wcs = widgets[i].worldCorners;

                for (int b = 0; b < 4; ++b)
                {
                    wcs[b] = worldToLocal.MultiplyPoint3x4(wcs[b]);
                    if (i == 0 && b == 0)
                    {
                        bounds = new Bounds(wcs[b], Vector3.zero);
                    }
                    else
                    {
                        bounds.Encapsulate(wcs[b]);
                    }
                }
            }

            // Calculate the 4 local corners
            Vector3 v0 = bounds.min;
            Vector3 v1 = bounds.max;

            float z = Mathf.Min(v0.z, v1.z);
            corners    = new Vector3[4];
            corners[0] = new Vector3(v0.x, v0.y, z);
            corners[1] = new Vector3(v0.x, v1.y, z);
            corners[2] = new Vector3(v1.x, v1.y, z);
            corners[3] = new Vector3(v1.x, v0.y, z);

            // Transform the 4 corners into world space
            for (int i = 0; i < 4; ++i)
            {
                corners[i] = localToWorld.MultiplyPoint3x4(corners[i]);
            }

            handles = new Vector3[8];

            handles[0] = corners[0];
            handles[1] = corners[1];
            handles[2] = corners[2];
            handles[3] = corners[3];

            handles[4] = (corners[0] + corners[1]) * 0.5f;
            handles[5] = (corners[1] + corners[2]) * 0.5f;
            handles[6] = (corners[2] + corners[3]) * 0.5f;
            handles[7] = (corners[0] + corners[3]) * 0.5f;

            Color handlesColor = UIWidgetInspector.handlesColor;
            NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
            NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
            NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
            NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);

            isWithinRect = mIsDragging || (e.modifiers == 0 &&
                                           NGUIEditorTools.SceneViewDistanceToRectangle(corners, e.mousePosition) == 0f);
#if !UNITY_3_5
            // Change the mouse cursor to a more appropriate one
            Vector2[] screenPos = new Vector2[8];
            for (int i = 0; i < 8; ++i)
            {
                screenPos[i] = HandleUtility.WorldToGUIPoint(handles[i]);
            }

            bounds = new Bounds(screenPos[0], Vector3.zero);
            for (int i = 1; i < 8; ++i)
            {
                bounds.Encapsulate(screenPos[i]);
            }

            // Change the cursor to a move arrow when it's within the screen rectangle
            Vector2 min  = bounds.min;
            Vector2 max  = bounds.max;
            Rect    rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);
            UIWidgetInspector.SetCursorRect(rect, isWithinRect ? MouseCursor.MoveArrow : MouseCursor.Arrow);
#endif
        }

        switch (type)
        {
        case EventType.Repaint:
        {
            if (handles != null)
            {
                Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
                Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);

                if ((v2 - v0).magnitude > 60f)
                {
                    Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
                    Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);

                    Handles.BeginGUI();
                    {
                        for (int i = 0; i < 4; ++i)
                        {
                            UIWidgetInspector.DrawKnob(handles[i], false, false, id);
                        }

                        if (Mathf.Abs(v1.y - v0.y) > 80f)
                        {
                            UIWidgetInspector.DrawKnob(handles[4], false, false, id);
                            UIWidgetInspector.DrawKnob(handles[6], false, false, id);
                        }

                        if (Mathf.Abs(v3.x - v0.x) > 80f)
                        {
                            UIWidgetInspector.DrawKnob(handles[5], false, false, id);
                            UIWidgetInspector.DrawKnob(handles[7], false, false, id);
                        }
                    }
                    Handles.EndGUI();
                }
            }
        }
        break;

        case EventType.MouseDown:
        {
            mAllowSelection = true;
            mStartMouse     = e.mousePosition;

            if (e.button == 1)
            {
                GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                e.Use();
            }
            else if (e.button == 0 && isWithinRect && corners != null && UIWidgetInspector.Raycast(corners, out mStartDrag))
            {
                mCanDrag              = true;
                mStartPos             = t.position;
                GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                e.Use();
            }
        }
        break;

        case EventType.MouseDrag:
        {
            // Prevent selection once the drag operation begins
            bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
            if (dragStarted)
            {
                mAllowSelection = false;
            }

            if (GUIUtility.hotControl == id)
            {
                e.Use();

                if (mCanDrag)
                {
                    Vector3 pos;

                    if (corners != null & UIWidgetInspector.Raycast(corners, out pos))
                    {
                        // Wait until the mouse moves by more than a few pixels
                        if (!mIsDragging && dragStarted)
                        {
                            NGUIEditorTools.RegisterUndo("Move " + t.name, t);
                            mStartPos   = t.position;
                            mIsDragging = true;
                        }

                        if (mIsDragging)
                        {
                            t.position      = mStartPos + (pos - mStartDrag);
                            pos             = t.localPosition;
                            pos.x           = Mathf.Round(pos.x);
                            pos.y           = Mathf.Round(pos.y);
                            pos.z           = Mathf.Round(pos.z);
                            t.localPosition = pos;
                        }
                    }
                }
            }
        }
        break;

        case EventType.MouseUp:
        {
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;

                if (e.button == 0)
                {
                    if (mIsDragging)
                    {
                        mIsDragging = false;
                        Vector3 pos = t.localPosition;
                        pos.x           = Mathf.Round(pos.x);
                        pos.y           = Mathf.Round(pos.y);
                        pos.z           = Mathf.Round(pos.z);
                        t.localPosition = pos;
                    }
                    else if (mAllowSelection)
                    {
                        // Left-click: Select the topmost widget
                        NGUIEditorTools.SelectWidget(e.mousePosition);
                        e.Use();
                    }
                    e.Use();
                }
                else
                {
                    // Right-click: Open a context menu listing all widgets underneath
                    NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
                    e.Use();
                }
                mCanDrag = false;
            }
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                Vector3 pos = t.localPosition;
                pos.y          += 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                Vector3 pos = t.localPosition;
                pos.y          -= 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                Vector3 pos = t.localPosition;
                pos.x          -= 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                Vector3 pos = t.localPosition;
                pos.x          += 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mIsDragging)
                    {
                        mIsDragging = false;
                        t.position  = mStartPos;
                    }

                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
Пример #15
0
        protected override void DrawScene()
        {
            var dirty  = false;
            var matrix = Target.transform.localToWorldMatrix;

            Undo.RecordObject(Target, "Points Changed");

            if (Target.Paths != null && currentPath >= 0 && currentPath < Target.Paths.Count)
            {
                var path = Target.Paths[currentPath];

                if (path.Points != null)
                {
                    Handles.matrix = matrix;

                    Handles.BeginGUI();
                    {
                        for (var i = 0; i < path.Points.Count; i++)
                        {
                            var point     = path.Points[i];
                            var pointName = "Point " + i;
                            var scrPoint  = Camera.current.WorldToScreenPoint(matrix.MultiplyPoint(point));
                            var rect      = new Rect(0.0f, 0.0f, 50.0f, 20.0f); rect.center = new Vector2(scrPoint.x, Screen.height - scrPoint.y - 35.0f);
                            var rect1     = rect; rect.x += 1.0f;
                            var rect2     = rect; rect.x -= 1.0f;
                            var rect3     = rect; rect.y += 1.0f;
                            var rect4     = rect; rect.y -= 1.0f;

                            GUI.Label(rect1, pointName, EditorStyles.miniBoldLabel);
                            GUI.Label(rect2, pointName, EditorStyles.miniBoldLabel);
                            GUI.Label(rect3, pointName, EditorStyles.miniBoldLabel);
                            GUI.Label(rect4, pointName, EditorStyles.miniBoldLabel);
                            GUI.Label(rect, pointName, EditorStyles.whiteMiniLabel);
                        }

                        for (var i = 1; i < path.Points.Count; i++)
                        {
                            var pointA   = path.Points[i - 1];
                            var pointB   = path.Points[i];
                            var midPoint = (pointA + pointB) * 0.5f;
                            var scrPoint = Camera.current.WorldToScreenPoint(matrix.MultiplyPoint(midPoint));

                            if (GUI.Button(new Rect(scrPoint.x - 5.0f, Screen.height - scrPoint.y - 45.0f, 20.0f, 20.0f), "+") == true)
                            {
                                path.Points.Insert(i, midPoint); dirty = true;
                            }
                        }
                    }
                    Handles.EndGUI();

                    for (var i = 0; i < path.Points.Count; i++)
                    {
                        var oldPoint = path.Points[i];
                        var newPoint = Handles.PositionHandle(oldPoint, Quaternion.identity);

                        if (oldPoint != newPoint)
                        {
                            newPoint.x = Mathf.Round(newPoint.x);
                            newPoint.y = Mathf.Round(newPoint.y);
                            newPoint.z = Mathf.Round(newPoint.z);

                            path.Points[i] = newPoint; dirty = true;
                        }
                    }
                }
            }

            if (dirty == true)
            {
                EditorUtility.SetDirty(Target);
            }
        }
Пример #16
0
        static void Render(SceneView view)
        {
            var ev = Event.current;

            // Only let certain hotkeys pass
            if (!EditorGUIUtility.editingTextField)
            {
                GUIUtility.keyboardControl = GUIUtility.GetControlID(FocusType.Native);
            }

            var projects = DT.Projects;

            projects.Sort();

            Handles.BeginGUI();
            GUI.skin = null; // to ensure light-skin is used if set in preferences (or not Pro)
            // Get largest item for each side
            if (RecalcItemSize)
            {
                calcMaxItemDimension();
            }

            // Get starting position for each side
            _InitialRects = getInitialItemRect();
            _ItemRect     = new Rect[4];
            _InitialRects.CopyTo(_ItemRect, 0);

            DTToolbarItem lastItem = null;

            DTSelection.MuteEvents = true;

            DTToolbarItem hovering = null;

            foreach (var project in projects)
            {
                int side = (int)project.ToolbarOrientation;
                if (lastItem && lastItem.Project.ToolbarOrientation != project.ToolbarOrientation)
                {
                    lastItem = null;
                }
                var items = project.ToolbarItems;

                // Render items
                for (int i = 0; i < items.Count; i++)
                {
                    if (items[i].Visible)
                    {
                        Vector2 itemSize = items[i].GetItemSize();                       // size of current item
                        _ItemRect[side] = advanceItemRect(lastItem, items[i], itemSize); // advance by using the last itemRect and the new(current) size

                        items[i].mItemRect = _ItemRect[side];                            // Store current item rect


                        if (items[i].Enabled)
                        {
                            Handles.EndGUI();
                            EditorKeyBinding.BindingsEnabled = false;
                            if (items[i].mItemRect.Contains(DTGUI.MousePosition))
                            {
                                hovering = items[i];
                            }
                            items[i].OnSceneGUI();

                            EditorKeyBinding.BindingsEnabled = true;
                            Handles.BeginGUI();
                        }
                        GUI.enabled = items[i].Enabled;
                        items[i].Render(_ItemRect[side]);

                        GUI.enabled = true;
                        if (ev != null && items[i].Enabled && (DTToolbarItem.FocusedItem == null || DTToolbarItem.FocusedItem == items[i]))
                        {
                            items[i].HandleEvents(ev);
                        }

                        lastItem = items[i];
                    }
                }
            }
            DTSelection.MuteEvents = false;
            detailOpen             = false;
            // Render items client area (Note: itemRect contains the last rendered item, a.k.a. a way to get the number of rows/cols needed
            foreach (var project in projects)
            {
                var items = project.ToolbarItems;
                for (int i = 0; i < items.Count; i++)
                {
                    if (items[i].Visible && items[i].ShowClientArea)
                    {
                        detailOpen = true;
                        Rect clientRect = items[i].mItemRect;
                        int  side       = (int)project.ToolbarOrientation;
                        switch (project.ToolbarOrientation)
                        {
                        case DTToolbarOrientation.Left:
                            clientRect.x = _ItemRect[side].x + _MaxItemDimension[side].x + 5;
                            break;

                        case DTToolbarOrientation.Right:
                            clientRect.x = _ItemRect[side].x - 5;
                            break;

                        case DTToolbarOrientation.Top:
                            clientRect.y = _ItemRect[side].y + _MaxItemDimension[side].y + 5;
                            break;

                        case DTToolbarOrientation.Bottom:
                            clientRect.y = _ItemRect[side].y - 5;
                            break;
                        }
                        if (clientRect.width > 0 && clientRect.height > 0)
                        {
                            items[i].mBackgroundRects.Clear();
                            EditorKeyBinding.BindingsEnabled = false;
                            items[i].RenderClientArea(clientRect);
                            EditorKeyBinding.BindingsEnabled = true;
                            if (DTGUI.IsClick)
                            {
                                foreach (var r in items[i].mBackgroundRects)
                                {
                                    if (r.Contains(ev.mousePosition))
                                    {
                                        DTGUI.UseEvent(items[i].GetHashCode(), ev);
                                    }
                                }
                            }
                        }
                    }
                }
            }



            // Handle statusbar info when hovering over an item
            if (hovering != null)
            {
                DTToolbarItem._StatusBar.Set(hovering.StatusBarInfo, "Info");
            }
            else
            {
                DTToolbarItem._StatusBar.Clear("Info");
            }

            // Render Statusbar
            DTToolbarItem._StatusBar.Render(getStatusBarRect(), null, true);

            Handles.EndGUI();
        }
        void OnSceneGUI(SceneView scene)
        {
            const float WindowHeight = 140;
            const float WindowWidth  = 380;
            const float Margin       = 20;

            ResetLabelStart();

            Handles.BeginGUI();

            GUI.Window(1, new Rect(SceneView.lastActiveSceneView.position.width - (WindowWidth + Margin), SceneView.lastActiveSceneView.position.height - (WindowHeight + Margin), WindowWidth, WindowHeight), SceneWindow, "UMA Mesh Hide Geometry Selector");
            DrawNextLabel("Left click and drag to area select");
            DrawNextLabel("Hold SHIFT while dragging to paint");
            DrawNextLabel("Hold CTRL while dragging to paint inverse");
            DrawNextLabel("Hold ALT while dragging to orbit");
            DrawNextLabel("Return to original scene by pressing \"Save and Return\"");
            Handles.EndGUI();

            if (_Source == null)
            {
                return;
            }

            if (!isSelecting && Event.current.alt)
            {
                return;
            }

            Rect selectionRect = new Rect();

            if (Event.current.type == EventType.Layout)
            {
                HandleUtility.AddDefaultControl(GUIUtility.GetControlID(GetHashCode(), FocusType.Passive));
            }

            if (isSelecting)
            {
                Vector2 selectionSize = (Event.current.mousePosition - startMousePos);
                Vector2 correctedPos  = startMousePos;
                if (selectionSize.x < 0)
                {
                    selectionSize.x = Mathf.Abs(selectionSize.x);
                    correctedPos.x  = startMousePos.x - selectionSize.x;
                }
                if (selectionSize.y < 0)
                {
                    selectionSize.y = Mathf.Abs(selectionSize.y);
                    correctedPos.y  = startMousePos.y - selectionSize.y;
                }

                if (Event.current.shift || Event.current.control)
                {
                    bool selVal = setSelectedOn;
                    if (Event.current.control)
                    {
                        selVal = !selVal;
                    }

                    startMousePos = Event.current.mousePosition;
                    int mirrorHit   = -1;
                    int triangleHit = RayPick(isMirroring, out mirrorHit);
                    if (triangleHit >= 0)
                    {
                        if (_Source.selectedTriangles[triangleHit] != selVal)
                        {
                            // avoid constant rebuild.
                            _Source.selectedTriangles[triangleHit] = selVal;
                            if (isMirroring && mirrorHit != -1)
                            {
                                _Source.selectedTriangles[mirrorHit] = selVal;
                            }
                            _Source.UpdateSelectionMesh();
                        }
                    }
                }
                else if (selectionSize.x > drawTolerance || selectionSize.y > drawTolerance)
                {
                    Handles.BeginGUI();
                    selectionRect = new Rect(correctedPos, selectionSize);
                    Handles.DrawSolidRectangleWithOutline(selectionRect, selectionColor, Color.black);
                    Handles.EndGUI();
                    HandleUtility.Repaint();
                }

                if (Event.current.type == EventType.MouseDrag)
                {
                    SceneView.RepaintAll();
                    Event.current.Use();
                    return;
                }
            }

            //Single mouse click
            if (Event.current != null && Event.current.type == EventType.MouseDown && Event.current.button == 0)
            {
                isSelecting   = true;
                startMousePos = Event.current.mousePosition;
                int mirrorHit = -1;

                int triangleHit = RayPick(isMirroring, out mirrorHit);

                if (triangleHit >= 0)
                {
                    _Source.selectedTriangles[triangleHit] = !_Source.selectedTriangles[triangleHit];
                    if (isMirroring && mirrorHit != -1)
                    {
                        // Mirror triangle should be the same as the hit triangle regardless of previous selection.
                        _Source.selectedTriangles[mirrorHit] = _Source.selectedTriangles[triangleHit];
                    }
                    _Source.UpdateSelectionMesh();
                }
            }

            if (Event.current != null && Event.current.type == EventType.MouseUp && Event.current.button == 0)
            {
                if (isSelecting)
                {
                    isSelecting = false;
                    Rect screenSelectionRect = new Rect();
                    screenSelectionRect.min = HandleUtility.GUIPointToScreenPixelCoordinate(new Vector2(selectionRect.xMin, selectionRect.yMax));
                    screenSelectionRect.max = HandleUtility.GUIPointToScreenPixelCoordinate(new Vector2(selectionRect.xMax, selectionRect.yMin));


                    int[] triangles = _Source.meshAsset.asset.meshData.submeshes[0].triangles;
                    for (int i = 0; i < triangles.Length; i += 3)
                    {
                        bool    found        = false;
                        Vector3 center       = new Vector3();
                        Vector3 centerNormal = new Vector3();

                        for (int k = 0; k < 3; k++)
                        {
                            Vector3 vertex = _Source.meshAsset.asset.meshData.vertices[triangles[i + k]];
                            vertex = _Source.transform.localToWorldMatrix.MultiplyVector(vertex);

                            Vector3 normal = _Source.meshAsset.asset.meshData.normals[triangles[i + k]];
                            normal = _Source.transform.localToWorldMatrix.MultiplyVector(normal);

                            center       += vertex;
                            centerNormal += normal;

                            vertex = SceneView.currentDrawingSceneView.camera.WorldToScreenPoint(vertex);

                            if (screenSelectionRect.Contains(vertex))
                            {
                                if (backfaceCull)
                                {
                                    if (Vector3.Dot(normal, SceneView.currentDrawingSceneView.camera.transform.forward) < -0.0f)
                                    {
                                        found = true;
                                    }
                                }
                                else
                                {
                                    found = true;
                                }
                            }
                        }

                        center       = center / 3;
                        centerNormal = centerNormal / 3;
                        center       = SceneView.currentDrawingSceneView.camera.WorldToScreenPoint(center);
                        if (screenSelectionRect.Contains(center))
                        {
                            if (backfaceCull)
                            {
                                if (Vector3.Dot(centerNormal, SceneView.currentDrawingSceneView.camera.transform.forward) < -0.0f)
                                {
                                    found = true;
                                }
                            }
                            else
                            {
                                found = true;
                            }
                        }

                        if (found)
                        {
                            _Source.selectedTriangles[(i / 3)] = setSelectedOn;
                        }
                    }

                    _Source.UpdateSelectionMesh();
                }
            }

            if (Event.current.type == EventType.MouseMove)
            {
                SceneView.RepaintAll();
            }
        }
Пример #18
0
    protected virtual void OnSceneGUI()
    {
        clv = (CleverCube)target;
        if (clv == null)
        {
            return;
        }

        var t = clv.transform;

        // Handles.BeginGUI
        // Handles.EndGUI
        /* Можно рисовать GUI прямо поверх сцены */
        Handles.BeginGUI();

        //if (GUILayout.Button("Forward Arrow", GUILayout.Width(100))){
        //	forwardArrow = true;
        // Вызов Handles не GUI внутри блока BeginGUI - EndGUI не имеет смысла
        //}

        if (GUILayout.Button("Handler " + handler, GUILayout.Width(100)))
        {
            handler++;
            if (handler >= maxhandler)
            {
                handler = 0;
            }
        }

        Handles.EndGUI();


        if (handler == 0)
        {
            // Стрелка с палочкой
            Handles.ArrowHandleCap(0, t.position + t.forward, t.rotation, .2f, EventType.Repaint);
        }
        else if (handler == 1)
        {
            // Handles.Button (Make a 3D Button)
            if (Handles.Button(t.position + Vector3.up * 1.3f, t.rotation, .3f, .2f, Handles.RectangleHandleCap))
            {
                Debug.Log("The button was pressed!");
            }
        }
        else if (handler == 2)
        {
            // Окружность
            Handles.color = Handles.zAxisColor;
            Handles.CircleHandleCap(
                0,
                t.position + Vector3.forward * 1.2f,
                t.rotation * Quaternion.LookRotation(Vector3.forward),
                t.localScale.z *
                .5f,                 // под size, вероятно, подразумевается радиус, ибо всегда в два раза больше назначеррного расстояния.
                EventType.Repaint
                );
        }
        else if (handler == 3)
        {
            // Конус (ArrowHead)
            Handles.color = Handles.zAxisColor;
            Handles.ConeHandleCap(
                0,
                t.position + Vector3.forward * 1.2f,
                t.rotation * Quaternion.LookRotation(Vector3.forward),
                0.3f,
                EventType.Repaint
                );
        }
        else if (handler == 4)
        {
            // Куб (ArrowHead)
            Handles.color = Handles.zAxisColor;
            Handles.CubeHandleCap(
                0,
                t.position + Vector3.forward * 1.2f,
                t.rotation * Quaternion.LookRotation(Vector3.forward),
                0.3f,
                EventType.Repaint
                );
        }
        else if (handler == 5)
        {
            // Цилиндр (ArrowHead)
            Handles.color = Handles.zAxisColor;
            Handles.CylinderHandleCap(
                0,
                t.position + Vector3.forward * 1.2f,
                t.rotation * Quaternion.LookRotation(Vector3.forward),
                0.3f,
                EventType.Repaint
                );
        }
        else if (handler == 6)
        {
            // Make a 3D disc that can be dragged with the mouse
            // Меняет поворот по оси Vector3.up
            t.rotation = Handles.Disc(t.rotation, t.transform.position, Vector3.up, 2, false, 1);
        }
        else if (handler == 7)
        {
            // Рисует точку (Billboard Square)
            Handles.color = Color.yellow;
            Handles.DotHandleCap(
                0,
                t.position + Vector3.forward * 1.2f,
                t.rotation * Quaternion.LookRotation(Vector3.forward),
                0.03f,
                EventType.Repaint
                );
        }
        else if (handler == 8)
        {
            //Draw anti-aliased convex polygon specified with point array.
            var arrowHead = new Vector3[3];
            var arrowLine = new Vector3[2];

            Transform start = t;
            Transform end   = clv.second;
            if (!start || !end)
            {
                return;
            }

            var forward = (end.position - start.position).normalized;
            var right   = Vector3.Cross(Vector3.up, forward).normalized;
            var size    = HandleUtility.GetHandleSize(end.position);
            var width   = size * 0.1f;
            var height  = size * 0.3f;

            arrowHead[0] = end.position;
            arrowHead[1] = end.position - forward * height + right * width;
            arrowHead[2] = end.position - forward * height - right * width;

            arrowLine[0] = start.position;
            arrowLine[1] = end.position - forward * height;

            Handles.color = Color.red;
            Handles.DrawAAPolyLine(arrowLine);
            Handles.DrawAAConvexPolygon(arrowHead);
        }
        else if (handler == 9)
        {
            // Эта штука не рендерится, или я не вижу или не работает.
            //https://docs.unity3d.com/ScriptReference/Handles.MakeBezierPoints.html
            float width = HandleUtility.GetHandleSize(Vector3.zero) * 0.1f;
            Handles.DrawBezier(t.position,
                               Vector3.zero,
                               Vector3.up,
                               -Vector3.up,
                               Color.red,
                               null,
                               width);
        }
        else if (handler == 10)
        {
            Handles.DrawDottedLine(t.position, clv.second.transform.position, 20f);


            //  DrawDottedLines
            //	DrawLine
            //	DrawLines
            //	DrawPolyLine
        }
        else if (handler == 11)
        {
            Handles.DrawSolidArc(t.position,
                                 t.up,
                                 -t.right,
                                 180,
                                 clv.areaRadius);


            Handles.color  = Color.white;
            clv.areaRadius =
                Handles.ScaleValueHandle(clv.areaRadius,
                                         t.position + t.forward * clv.areaRadius,
                                         t.rotation,
                                         1,
                                         Handles.ConeHandleCap,
                                         1);

            // много всякого не особо показательного, поэтому дальше буду реализовывать только интересные.
            //https://docs.unity3d.com/ScriptReference/Handles.html
        }
        else if (handler == 12)
        {
            clv.second.position = Handles.FreeMoveHandle(clv.second.position, Quaternion.identity, 0.05f, Vector3.zero, Handles.DotHandleCap);
            Handles.DrawLine(t.position, clv.second.transform.position);
        }
        else if (handler == 13)
        {
            clv.second.rotation = Handles.FreeRotateHandle(clv.second.rotation, clv.second.position, .5f);
        }
        else if (handler == 14)
        {
            Handles.Label(t.position + Vector3.up * 1.2f, t.name + '\n' + t.tag);


            // Handles.PositionHandle - как дефолтный Tools.Move
        }
        else if (handler == 15)
        {
            clv.areaRadius = Handles.RadiusHandle(Quaternion.identity, t.transform.position, clv.areaRadius);
            // Сдвинутый на 45 получается более плотная оболочка сферы
            //Handles.RadiusHandle(Quaternion.AngleAxis(45,Vector3.up), t.transform.position, clv.areaRadius);
        }
        else if (handler == 16)
        {
            // Графоуний. Без взаимодействий.
            Handles.color = Handles.xAxisColor;
            Handles.RectangleHandleCap(
                0,
                t.position + new Vector3(.25f, 0f, 0f),
                t.rotation * Quaternion.LookRotation(Vector3.right),
                .5f,
                EventType.Repaint
                );


            // Handles.RotationHandle - как дефолтный Tools.Rotation
            // Handles.ScaleHandle - тож
        }
        else if (handler == 17)
        {
            // Одна палка от ScaleHandle
            clv.scalar = Handles.ScaleSlider(clv.scalar, clv.transform.position, clv.transform.forward, clv.transform.rotation, 1f, 0);
        }
        else if (handler == 18)
        {
            // Тут я не совсем правильно юзаю (не технически, а по смыслу), тут юзается как слайдер, хотя есть отдельная реализация слайдера
            clv.scalar = Handles.ScaleValueHandle(clv.scalar, t.position + t.forward * clv.scalar, t.rotation, 9f, Handles.ArrowHandleCap, 0);
        }
        else if (handler == 19)
        {
            clv.second.position = Handles.Slider(clv.second.position, Vector3.right, .3f, Handles.ConeHandleCap, 0);
        }

        // Там ещё всякого по мелочи есть, но оно всё работает по схожему принципу
        // https://docs.unity3d.com/ScriptReference/Handles.html
    }
Пример #19
0
    /// <summary>
    /// Draw the on-screen selection, knobs, and handle all interaction logic.
    /// </summary>

    public void OnSceneGUI()
    {
        if (Selection.objects.Length > 1)
        {
            return;
        }
        NGUIEditorTools.HideMoveTool(true);
        if (!UIWidget.showHandles)
        {
            return;
        }

        mWidget = target as UIWidget;

        Transform t = mWidget.cachedTransform;

        Event     e    = Event.current;
        int       id   = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
        EventType type = e.GetTypeForControl(id);

        Action actionUnderMouse = mAction;

        Vector3[] handles = GetHandles(mWidget.worldCorners);

        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
        NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);

        // If the widget is anchored, draw the anchors
        if (mWidget.isAnchored)
        {
            DrawAnchorHandle(mWidget.leftAnchor, mWidget.cachedTransform, handles, 0, id);
            DrawAnchorHandle(mWidget.topAnchor, mWidget.cachedTransform, handles, 1, id);
            DrawAnchorHandle(mWidget.rightAnchor, mWidget.cachedTransform, handles, 2, id);
            DrawAnchorHandle(mWidget.bottomAnchor, mWidget.cachedTransform, handles, 3, id);
        }

        if (type == EventType.Repaint)
        {
            bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
            if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control)
            {
                showDetails = true;
            }
            if (NGUITools.GetActive(mWidget) && mWidget.parent == null)
            {
                showDetails = true;
            }
            if (showDetails)
            {
                NGUIHandles.DrawSize(handles, mWidget.width, mWidget.height);
            }
        }

        // Presence of the legacy stretch component prevents resizing
        bool canResize = (mWidget.GetComponent <UIStretch>() == null);

        bool[] resizable = new bool[8];

        resizable[4] = canResize;   // left
        resizable[5] = canResize;   // top
        resizable[6] = canResize;   // right
        resizable[7] = canResize;   // bottom

        UILabel lbl = mWidget as UILabel;

        if (lbl != null)
        {
            if (lbl.overflowMethod == UILabel.Overflow.ResizeFreely)
            {
                resizable[4] = false;   // left
                resizable[5] = false;   // top
                resizable[6] = false;   // right
                resizable[7] = false;   // bottom
            }
            else if (lbl.overflowMethod == UILabel.Overflow.ResizeHeight)
            {
                resizable[5] = false;   // top
                resizable[7] = false;   // bottom
            }
        }

        if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnHeight)
        {
            resizable[4] = false;
            resizable[6] = false;
        }
        else if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnWidth)
        {
            resizable[5] = false;
            resizable[7] = false;
        }

        resizable[0] = resizable[7] && resizable[4]; // bottom-left
        resizable[1] = resizable[5] && resizable[4]; // top-left
        resizable[2] = resizable[5] && resizable[6]; // top-right
        resizable[3] = resizable[7] && resizable[6]; // bottom-right

        UIWidget.Pivot pivotUnderMouse = GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);

        switch (type)
        {
        case EventType.Repaint:
        {
            Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
            Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);

            if ((v2 - v0).magnitude > 60f)
            {
                Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
                Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);

                Handles.BeginGUI();
                {
                    for (int i = 0; i < 4; ++i)
                    {
                        DrawKnob(handles[i], mWidget.pivot == pivotPoints[i], resizable[i], id);
                    }

                    if ((v1 - v0).magnitude > 80f)
                    {
                        if (mWidget.leftAnchor.target == null || mWidget.leftAnchor.absolute != 0)
                        {
                            DrawKnob(handles[4], mWidget.pivot == pivotPoints[4], resizable[4], id);
                        }

                        if (mWidget.rightAnchor.target == null || mWidget.rightAnchor.absolute != 0)
                        {
                            DrawKnob(handles[6], mWidget.pivot == pivotPoints[6], resizable[6], id);
                        }
                    }

                    if ((v3 - v0).magnitude > 80f)
                    {
                        if (mWidget.topAnchor.target == null || mWidget.topAnchor.absolute != 0)
                        {
                            DrawKnob(handles[5], mWidget.pivot == pivotPoints[5], resizable[5], id);
                        }

                        if (mWidget.bottomAnchor.target == null || mWidget.bottomAnchor.absolute != 0)
                        {
                            DrawKnob(handles[7], mWidget.pivot == pivotPoints[7], resizable[7], id);
                        }
                    }
                }
                Handles.EndGUI();
            }
        }
        break;

        case EventType.MouseDown:
        {
            if (actionUnderMouse != Action.None)
            {
                mStartMouse     = e.mousePosition;
                mAllowSelection = true;

                if (e.button == 1)
                {
                    if (e.modifiers == 0)
                    {
                        GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                        e.Use();
                    }
                }
                else if (e.button == 0 && actionUnderMouse != Action.None && Raycast(handles, out mStartDrag))
                {
                    mWorldPos      = t.position;
                    mLocalPos      = t.localPosition;
                    mStartRot      = t.localRotation.eulerAngles;
                    mStartDir      = mStartDrag - t.position;
                    mStartWidth    = mWidget.width;
                    mStartHeight   = mWidget.height;
                    mStartLeft.x   = mWidget.leftAnchor.relative;
                    mStartLeft.y   = mWidget.leftAnchor.absolute;
                    mStartRight.x  = mWidget.rightAnchor.relative;
                    mStartRight.y  = mWidget.rightAnchor.absolute;
                    mStartBottom.x = mWidget.bottomAnchor.relative;
                    mStartBottom.y = mWidget.bottomAnchor.absolute;
                    mStartTop.x    = mWidget.topAnchor.relative;
                    mStartTop.y    = mWidget.topAnchor.absolute;

                    mDragPivot            = pivotUnderMouse;
                    mActionUnderMouse     = actionUnderMouse;
                    GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                    e.Use();
                }
            }
        }
        break;

        case EventType.MouseDrag:
        {
            // Prevent selection once the drag operation begins
            bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
            if (dragStarted)
            {
                mAllowSelection = false;
            }

            if (GUIUtility.hotControl == id)
            {
                e.Use();

                if (mAction != Action.None || mActionUnderMouse != Action.None)
                {
                    Vector3 pos;

                    if (Raycast(handles, out pos))
                    {
                        if (mAction == Action.None && mActionUnderMouse != Action.None)
                        {
                            // Wait until the mouse moves by more than a few pixels
                            if (dragStarted)
                            {
                                if (mActionUnderMouse == Action.Move)
                                {
                                    NGUISnap.Recalculate(mWidget);
                                }
                                else if (mActionUnderMouse == Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                }
                                else if (mActionUnderMouse == Action.Scale)
                                {
                                    mStartWidth  = mWidget.width;
                                    mStartHeight = mWidget.height;
                                    mDragPivot   = pivotUnderMouse;
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != Action.None)
                        {
                            NGUIEditorTools.RegisterUndo("Change Rect", t);
                            NGUIEditorTools.RegisterUndo("Change Rect", mWidget);

                            // Reset the widget before adjusting anything
                            t.position     = mWorldPos;
                            mWidget.width  = mStartWidth;
                            mWidget.height = mStartHeight;
                            mWidget.leftAnchor.Set(mStartLeft.x, mStartLeft.y);
                            mWidget.rightAnchor.Set(mStartRight.x, mStartRight.y);
                            mWidget.bottomAnchor.Set(mStartBottom.x, mStartBottom.y);
                            mWidget.topAnchor.Set(mStartTop.x, mStartTop.y);

                            if (mAction == Action.Move)
                            {
                                // Move the widget
                                t.position = mWorldPos + (pos - mStartDrag);
                                Vector3 after = t.localPosition;

                                bool      snapped = false;
                                Transform parent  = t.parent;

                                if (parent != null)
                                {
                                    UIGrid grid = parent.GetComponent <UIGrid>();

                                    if (grid != null && grid.arrangement == UIGrid.Arrangement.CellSnap)
                                    {
                                        snapped = true;
                                        if (grid.cellWidth > 0)
                                        {
                                            after.x = Mathf.Round(after.x / grid.cellWidth) * grid.cellWidth;
                                        }
                                        if (grid.cellHeight > 0)
                                        {
                                            after.y = Mathf.Round(after.y / grid.cellHeight) * grid.cellHeight;
                                        }
                                    }
                                }

                                if (!snapped)
                                {
                                    // Snap the widget
                                    after = NGUISnap.Snap(after, mWidget.localCorners, e.modifiers != EventModifiers.Control);
                                }

                                // Calculate the final delta
                                Vector3 localDelta = (after - mLocalPos);

                                // Restore the position
                                t.position = mWorldPos;

                                // Adjust the widget by the delta
                                NGUIMath.MoveRect(mWidget, localDelta.x, localDelta.y);
                            }
                            else if (mAction == Action.Rotate)
                            {
                                Vector3 dir   = pos - t.position;
                                float   angle = Vector3.Angle(mStartDir, dir);

                                if (angle > 0f)
                                {
                                    float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
                                    if (dot < 0f)
                                    {
                                        angle = -angle;
                                    }
                                    angle = mStartRot.z + angle;
                                    angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
                                            Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == Action.Scale)
                            {
                                // Move the widget
                                t.position = mWorldPos + (pos - mStartDrag);

                                // Calculate the final delta
                                Vector3 localDelta = (t.localPosition - mLocalPos);

                                // Restore the position
                                t.position = mWorldPos;

                                // Adjust the widget's position and scale based on the delta, restricted by the pivot
                                NGUIMath.ResizeWidget(mWidget, mDragPivot, localDelta.x, localDelta.y, 2, 2);
                                ReEvaluateAnchorType();
                            }
                        }
                    }
                }
            }
        }
        break;

        case EventType.MouseUp:
        {
            if (e.button == 2)
            {
                break;
            }
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;

                if (e.button < 2)
                {
                    bool handled = false;

                    if (e.button == 1)
                    {
                        // Right-click: Open a context menu listing all widgets underneath
                        NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
                        handled = true;
                    }
                    else if (mAction == Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the topmost widget
                            NGUIEditorTools.SelectWidget(e.mousePosition);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        Vector3 pos = t.localPosition;
                        pos.x           = Mathf.Round(pos.x);
                        pos.y           = Mathf.Round(pos.y);
                        pos.z           = Mathf.Round(pos.z);
                        t.localPosition = pos;
                        handled         = true;
                    }

                    if (handled)
                    {
                        e.Use();
                    }
                }

                // Clear the actions
                mActionUnderMouse = Action.None;
                mAction           = Action.None;
            }
            else if (mAllowSelection)
            {
                List <UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
                if (widgets.Count > 0)
                {
                    Selection.activeGameObject = widgets[0].gameObject;
                }
            }
            mAllowSelection = true;
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 0f, 1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 0f, -1f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, -1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                NGUIEditorTools.RegisterUndo("Nudge Rect", t);
                NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
                NGUIMath.MoveRect(mWidget, 1f, 0f);
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != Action.None)
                    {
                        Undo.PerformUndo();
                    }

                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;

                    mActionUnderMouse = Action.None;
                    mAction           = Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
Пример #20
0
    public void OnSceneGUI()
    {
        Path path = target as Path;

        if (path.isDebug == true)
        {
            for (i = 0; i < path.waypointList.Length; i++)
            {
                // Get the needed data before the handle
                controlIDBeforeHandle   = GUIUtility.GetControlID(GetHashCode(), FocusType.Passive);
                isEventUsedBeforeHandle = (Event.current.type == EventType.used);

                if (isMoveMode)
                {
                    path.waypointList [i].waypointPos =
                        Handles.PositionHandle(path.waypointList [i].waypointPos, Quaternion.identity);
                }
                else
                {
                    if (path.waypointList [i].useDefault == false)
                    {
                        path.waypointList [i].radius = Handles.ScaleValueHandle(path.waypointList [i].radius,
                                                                                path.waypointList [i].waypointPos, Quaternion.identity,
                                                                                path.waypointList [i].radius * 13, Handles.SphereCap, 1);
                    }
                    else
                    {
                        path.waypointList [i].radius = Handles.ScaleValueHandle(path.defaultRadius,
                                                                                path.waypointList [i].waypointPos, Quaternion.identity,
                                                                                path.waypointList [i].radius * 13, Handles.SphereCap, 1);
                    }
                }

                // Get the needed data after the handle
                controlIDAfterHandle = GUIUtility.GetControlID(GetHashCode(), FocusType.Passive);
                isEventUsedByHandle  = !isEventUsedBeforeHandle && (Event.current.type == EventType.used);

                if ((controlIDBeforeHandle < GUIUtility.hotControl &&
                     GUIUtility.hotControl < controlIDAfterHandle) || isEventUsedByHandle)
                {
                    path.SelectedWaypoint = i;
                }
            }

            Handles.BeginGUI();

            this.initStyles();
            GUI.Box(size, string.Empty, currentStyle);

            fontSize = GUI.skin.label.fontSize;
            GUI.skin.label.fontSize = 15;
            GUI.Label(waypointIndex, "Selected Waypoint: " + path.SelectedWaypoint);

            if (GUI.Button(insert, "Insert"))
            {
                path.insert();
            }

            if (GUI.Button(delete, "Delete"))
            {
                path.delete();
            }

            if (GUI.Button(calculateDistance, "Distance"))
            {
                isCalculateDistance = !isCalculateDistance;
            }

            if (isMoveMode == true)
            {
                if (GUI.Button(mode, "Mode: move"))
                {
                    isMoveMode = false;
                }
            }
            else
            {
                if (GUI.Button(mode, "Mode: scale"))
                {
                    isMoveMode = true;
                }
            }

            if (isCalculateDistance == true)
            {
                GUI.Box(distanceSize, string.Empty, currentStyle);

                GUI.Label(startLabel, "Start");
                startIndex = GUI.TextField(startField, startIndex);

                GUI.Label(endLabel, "End");
                endIndex = GUI.TextField(endField, endIndex);

                GUI.Label(raceLabel, "Round");
                race = GUI.TextField(raceField, race);

                if (GUI.Button(getDistance, "Calculate"))
                {
                    try {
                        int sIndex    = Int32.Parse(startIndex);
                        int dIndex    = Int32.Parse(endIndex);
                        int raceIndex = Int32.Parse(race);

                        EditorUtility.DisplayDialog("Result!", "Distance between waypoint " + sIndex +
                                                    " and waypoint " + dIndex + " (" + raceIndex + " rounds) is " +
                                                    path.getDistance(sIndex, dIndex, raceIndex), "OK");
                    } catch (Exception exception) {
                        EditorUtility.DisplayDialog("An error has occured!",
                                                    "Exception: " + exception.Message +
                                                    "\nOpen Unity console window for more details.", "OK");
                    }
                }
            }

            GUI.skin.label.fontSize = fontSize;

            Handles.EndGUI();
        }
    }
        void CallSceneGUI()
        {
            if (emitter == null)
            {
                return;
            }

            if (!emitter.isActiveAndEnabled)
            {
                return;
            }

            SceneView sceneView = SceneView.currentDrawingSceneView;

            Handles.BeginGUI();

            float screenWidth  = sceneView.position.size.x;
            float screenHeight = sceneView.position.size.y;

            float width  = 160;
            float height = 120;

            var boxRect  = new Rect(screenWidth - width - 30, screenHeight - height - 45, width + 20, height + 40);
            var areaRect = new Rect(screenWidth - width - 20, screenHeight - height - 20, width, height);

            GUI.Box(boxRect, "Effekseer Emitter");
            GUILayout.BeginArea(areaRect);

            GUILayout.BeginHorizontal();
            if (GUILayout.Button("Play"))
            {
                if (systemInitialized == false)
                {
                    InitSystem();
                }

                // avoid a bug playing effect sometimes causes craches after window size is changed.
                // Unity, Effekseer, or driver bug
                Effekseer.EffekseerSystem.Instance.renderer.CleanUp();
                emitter.Play();
            }
            if (GUILayout.Button("Stop"))
            {
                emitter.StopImmediate();

                // just in case
                Effekseer.EffekseerSystem.Instance.renderer.CleanUp();
                RepaintEffect();
            }
            GUILayout.EndHorizontal();

            GUILayout.Space(5);

            GUILayout.BeginHorizontal();
            GUILayout.Label("Loop", GUILayout.Width(50));
            loop = GUILayout.Toggle(loop, "");
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Paused", GUILayout.Width(50));
            emitter.paused = GUILayout.Toggle(emitter.paused, "");
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Speed", GUILayout.Width(50));
            emitter.speed = GUILayout.HorizontalSlider(emitter.speed, 0.0f, 2.0f);
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("Instance", GUILayout.Width(80));
            GUILayout.Label(emitter.instanceCount.ToString());
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            GUILayout.Label("RestInstance", GUILayout.Width(80));
            GUILayout.Label(EffekseerSystem.restInstanceCount.ToString());
            GUILayout.EndHorizontal();

            GUILayout.EndArea();

            Handles.EndGUI();
        }
        void OnGUI()
        {
            ResizeScrollView();
            Rect viewportRect = new Rect(0, 0, position.width - sidePanelWidth, position.height);

            EditorGUI.DrawRect(viewportRect, bgColor);
            bool repaint = false;

            foreach (var obj in Selection.objects)
            {
                if (obj is StateMachineDefinition)
                {
                    def = (StateMachineDefinition)obj;
                    break;
                }
            }

            if (def != null)
            {
                bool showSide = true;

                Event cur = Event.current;

                if (op != null)
                {
                    if (def != op.definition)
                    {
                        op.Cancel();
                        op = null;
                    }
                    else
                    {
                        op.Update();

                        if (op.done)
                        {
                            op      = null;
                            repaint = true;
                            EditorUtility.SetDirty(def);
                            dirty = true;
                        }
                    }
                }
                else
                {
                    var selected   = def.SelectState(cur.mousePosition + scrollPos);
                    var selectedTr = def.SelectTransition(cur.mousePosition + scrollPos);

                    if (selected == null)
                    {
                        if (selectedTr.t2 != lastSelectedTr)
                        {
                            repaint        = true;
                            lastSelectedTr = selectedTr.t2;
                        }

                        if (lastSelectedState != null)
                        {
                            lastSelectedState = null;
                            repaint           = true;
                        }
                    }
                    else
                    {
                        if (selected != lastSelectedState)
                        {
                            repaint           = true;
                            lastSelectedState = selected;
                        }

                        if (lastSelectedTr != null)
                        {
                            lastSelectedTr = null;
                            repaint        = true;
                        }
                    }

                    if (viewportRect.Contains(cur.mousePosition))
                    {
                        if (cur.type == EventType.MouseDown)
                        {
                            if (cur.button == 0)
                            {
                                if (selected != null)
                                {
                                    editingState         = selected;
                                    editingTransition.t1 = null;
                                    editingTransition.t2 = null;
                                    repaint  = true;
                                    showSide = false;


                                    if (cur.clickCount == 1)
                                    {
                                        op = new MoveStateOperation(def, selected);
                                    }
                                    else if (cur.clickCount == 2)
                                    {
                                        op = new RenameStateOperation(def, selected);
                                    }
                                }
                                else if (selectedTr.t1 != null)
                                {
                                    editingTransition = selectedTr;
                                    editingState      = null;
                                    repaint           = true;
                                    showSide          = false;
                                }
                                else
                                {
                                    editingState         = null;
                                    editingTransition.t1 = null;
                                    editingTransition.t2 = null;
                                    repaint  = true;
                                    showSide = false;
                                }
                            }
                            else if (cur.button == 1)
                            {
                                if (selected == null && lastSelectedTr == null)
                                {
                                    GenericMenu menu = new GenericMenu();

                                    menu.AddItem(new GUIContent("Create State"), false, () => {
                                        var s      = def.AddState();
                                        s.position = cur.mousePosition;
                                        op         = new RenameStateOperation(def, s);
                                        EditorUtility.SetDirty(def);
                                        dirty = true;
                                    });

                                    menu.ShowAsContext();
                                }
                                else if (selected != null)
                                {
                                    GenericMenu menu = new GenericMenu();

                                    menu.AddItem(new GUIContent("Delete State"), false, () => {
                                        def.RemoveState(selected);
                                        EditorUtility.SetDirty(def);
                                        dirty   = true;
                                        repaint = true;
                                    });

                                    menu.AddItem(new GUIContent("Add Transition"), false, () => {
                                        op = new MakeTransitionOperation(def, selected);
                                    });

                                    if (selected.name != def.defaultState)
                                    {
                                        menu.AddItem(new GUIContent("Make Default State"), false, () => {
                                            def.defaultState = selected.name;
                                            dirty            = true;
                                            repaint          = true;
                                        });
                                    }

                                    menu.ShowAsContext();
                                }
                                else if (selectedTr.t1 != null)
                                {
                                    GenericMenu menu = new GenericMenu();

                                    menu.AddItem(new GUIContent("Remove Transition"), false, () => {
                                        selectedTr.t1.RemoveTransition(selectedTr.t2);
                                        EditorUtility.SetDirty(def);
                                        dirty   = true;
                                        repaint = true;
                                    });

                                    menu.ShowAsContext();
                                }
                            }
                        }
                        else if (cur.type == EventType.MouseDrag && cur.button == 2)
                        {
                            scrollPos -= cur.delta;
                            repaint    = true;
                        }
                        else if (cur.type == EventType.KeyDown && cur.keyCode == KeyCode.F)
                        {
                            var state = def.GetState(def.defaultState);
                            if (state == null && def.states.Count > 0)
                            {
                                state = def.states[0];
                            }

                            if (state != null)
                            {
                                scrollPos = state.position - viewportRect.size / 2;
                                repaint   = true;
                            }
                        }
                    }
                }

                if (Event.current.type != EventType.Repaint && (repaint || (op != null && op.repaint)))
                {
                    Repaint();
                }

                Handles.BeginGUI();

                Handles.color = lineColor;
                for (float x = -scrollPos.x % MoveStateOperation.snap; x < viewportRect.width; x += MoveStateOperation.snap)
                {
                    Handles.DrawLine(new Vector3(x, 0), new Vector3(x, viewportRect.height));
                }

                for (float y = -scrollPos.y % MoveStateOperation.snap; y < viewportRect.height; y += MoveStateOperation.snap)
                {
                    Handles.DrawLine(new Vector3(0, y), new Vector3(viewportRect.width, y));
                }

                foreach (var from in def.states)
                {
                    if (from.transitions != null)
                    {
                        foreach (var tr in from.transitions)
                        {
                            if (tr != lastSelectedTr && tr != editingTransition.t2)
                            {
                                Handles.color = Color.black;
                            }
                            else
                            {
                                Handles.color = Color.blue;
                            }

                            if (def.GetState(tr.to) != null)
                            {
                                var     line = def.GetTransitionPoints(from, tr);
                                Vector2 src  = line.t1 - scrollPos;
                                Vector2 dest = line.t2 - scrollPos;

                                Vector2 v     = (dest - src).normalized;
                                Vector2 ortho = new Vector2(v.y, -v.x);

                                Vector2 arrow = ortho - v;
                                Vector2 mid   = (src + dest) / 2;

                                Handles.DrawAAPolyLine(3, src, dest);
                                Handles.DrawAAPolyLine(3, mid + v * 5, mid + arrow * 10);
                            }
                        }
                    }
                }

                Handles.EndGUI();

                foreach (var state in def.states)
                {
                    if (op == null || op.state != state || op.showBaseGUI)
                    {
                        string s = state.name;
                        if (def.defaultState == s)
                        {
                            s += "\n<default state>";
                        }

                        Rect rect = state.rect;
                        rect.position -= scrollPos;

                        if (state != lastSelectedState && state != editingState)
                        {
                            GUI.Button(rect, s);
                        }
                        else
                        {
                            GUI.Button(rect, "");

                            var centeredStyle = new GUIStyle(GUI.skin.label);
                            centeredStyle.alignment        = TextAnchor.MiddleCenter;
                            centeredStyle.normal.textColor = Color.blue;
                            centeredStyle.fontStyle        = FontStyle.Bold;

                            GUI.Label(rect, s, centeredStyle);
                        }
                    }

                    if (op != null && op.state == state)
                    {
                        op.OnGUI();
                    }
                }

                if (showSide)
                {
                    EditorGUI.DrawRect(new Rect(position.width - sidePanelWidth, 0, sidePanelWidth, position.height), panelColor);


                    float padding = 20;
                    GUILayout.BeginArea(new Rect(position.width - sidePanelWidth + padding, padding, sidePanelWidth - padding * 2, position.height - padding * 2));
                    EditorGUILayout.BeginVertical();
                    float w = EditorGUIUtility.labelWidth;
                    EditorGUIUtility.labelWidth = 1;

                    if (GUILayout.Button(dirty ? "Save *" : "Save"))
                    {
                        AssetDatabase.SaveAssets();
                        dirty = false;
                        StateMachineClassGenerator.GenerateAbstractClass(def);
                    }

                    if (GUILayout.Button("New Impl Class..."))
                    {
                        var path = EditorUtility.SaveFilePanelInProject("Save new class", def.name + "Impl.cs", "cs", "Enter a name for the new impl class");
                        if (path.Length > 0)
                        {
                            StateMachineClassGenerator.GenerateImplClass(def, path);
                        }
                    }

                    if (types == null)
                    {
                        types = typeof(StateMachine).Assembly.GetTypes()
                                .Where(p => !p.IsGenericType && typeof(StateMachine).IsAssignableFrom(p))
                                .Select(t => t.FullName).ToArray();
                    }

                    int index = Array.IndexOf(types, def.baseClass);
                    if (index < 0)
                    {
                        index = Array.IndexOf(types, typeof(StateMachine).FullName);
                    }
                    int prev = index;

                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.LabelField("Base Class");
                    index = EditorGUILayout.Popup(index, types);

                    if (prev != index)
                    {
                        dirty = true;
                    }

                    EditorGUILayout.EndHorizontal();
                    def.baseClass = types[index];

                    if (editingState != null)
                    {
                        EditorGUILayout.LabelField("State " + editingState.name);
                        EditorGUILayout.LabelField("State Events", EditorStyles.boldLabel);

                        EditorGUILayout.BeginHorizontal();
                        EditorGUILayout.LabelField("Enter: ");
                        bool enter = EditorGUILayout.Toggle(editingState.hasEnter);
                        EditorGUILayout.EndHorizontal();

                        EditorGUILayout.BeginHorizontal();
                        EditorGUILayout.LabelField("During: ");
                        bool during = EditorGUILayout.Toggle(editingState.hasDuring);
                        EditorGUILayout.EndHorizontal();

                        EditorGUILayout.BeginHorizontal();
                        EditorGUILayout.LabelField("Exit: ");
                        bool exit = EditorGUILayout.Toggle(editingState.hasExit);
                        EditorGUILayout.EndHorizontal();


                        if (enter != editingState.hasEnter || during != editingState.hasDuring || exit != editingState.hasExit)
                        {
                            editingState.hasEnter  = enter;
                            editingState.hasDuring = during;
                            editingState.hasExit   = exit;

                            dirty = true;
                            EditorUtility.SetDirty(def);
                        }
                    }
                    else if (editingTransition.t1 != null)
                    {
                        EditorGUILayout.LabelField("Transition From " + editingTransition.t1.name + " To " + editingTransition.t2.to);
                        EditorGUILayout.LabelField("Transition Events", EditorStyles.boldLabel);

                        EditorGUILayout.BeginHorizontal();
                        EditorGUILayout.LabelField("Notify: ");
                        bool notify = EditorGUILayout.Toggle(editingTransition.t2.hasNotify);
                        EditorGUILayout.EndHorizontal();

                        if (notify != editingTransition.t2.hasNotify)
                        {
                            editingTransition.t2.hasNotify = notify;

                            dirty = true;
                            EditorUtility.SetDirty(def);
                        }
                    }

                    EditorGUILayout.EndVertical();
                    EditorGUIUtility.labelWidth = w;

                    GUILayout.EndArea();
                }
            }
            else if (op != null)
            {
                op.Cancel();
                op = null;
            }
        }
Пример #23
0
        public static void ShowGUI(SceneView sceneView, bool haveOffset = true)
        {
            InitStyles();
            CSG_GUIStyleUtility.InitStyles();
            if (sceneView != null)
            {
                float height = sceneView.position.height;                   //Screen.height;
                float width  = sceneView.position.width;                    //Screen.width;
                Rect  bottomBarRect;
                if (haveOffset)
                {
#if UNITY_5_5_OR_NEWER
                    bottomBarRect = new Rect(0, height - (CSG_GUIStyleUtility.BottomToolBarHeight + 18),
                                             width, CSG_GUIStyleUtility.BottomToolBarHeight);
#else
                    bottomBarRect = new Rect(0, height - (CSG_GUIStyleUtility.BottomToolBarHeight + SceneView.kToolbarHeight + 1),
                                             width, CSG_GUIStyleUtility.BottomToolBarHeight);
#endif
                }
                else
                {
                    bottomBarRect = new Rect(0, height - (CSG_GUIStyleUtility.BottomToolBarHeight + 1), width, CSG_GUIStyleUtility.BottomToolBarHeight);
                }

                try
                {
                    Handles.BeginGUI();

                    bool prevGUIChanged = GUI.changed;
                    if (Event.current.type == EventType.Repaint)
                    {
                        CSG_GUIStyleUtility.BottomToolBarStyle.Draw(bottomBarRect, false, false, false, false);
                    }
                    OnBottomBarGUI(sceneView, bottomBarRect);
                    GUI.changed = prevGUIChanged || GUI.changed;

                    int controlID = GUIUtility.GetControlID(BottomBarGUIHash, FocusType.Keyboard, bottomBarRect);
                    var type      = Event.current.GetTypeForControl(controlID);
                    //Debug.Log(controlID + " " + GUIUtility.hotControl + " " + type + " " + bottomBarRect.Contains(Event.current.mousePosition));
                    switch (type)
                    {
                    case EventType.MouseDown: { if (bottomBarRect.Contains(Event.current.mousePosition))
                                                {
                                                    GUIUtility.hotControl = controlID; GUIUtility.keyboardControl = controlID; Event.current.Use();
                                                }
                                                break; }

                    case EventType.MouseMove: { if (bottomBarRect.Contains(Event.current.mousePosition))
                                                {
                                                    Event.current.Use();
                                                }
                                                break; }

                    case EventType.MouseUp:   { if (GUIUtility.hotControl == controlID)
                                                {
                                                    GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; Event.current.Use();
                                                }
                                                break; }

                    case EventType.MouseDrag: { if (GUIUtility.hotControl == controlID)
                                                {
                                                    Event.current.Use();
                                                }
                                                break; }

                    case EventType.ScrollWheel: { if (bottomBarRect.Contains(Event.current.mousePosition))
                                                  {
                                                      Event.current.Use();
                                                  }
                                                  break; }
                    }

                    //TooltipUtility.HandleAreaOffset(new Vector2(-bottomBarRect.xMin, -bottomBarRect.yMin));
                }
                finally
                {
                    Handles.EndGUI();
                }
            }
        }
Пример #24
0
    /*
     * Draws all joint points, curves, paths, and intersections to the scene view.
     * */
    void OnSceneGUI(SceneView sceneView)
    {
        if (data == null)
        {
            return;
        }
        if (data.jointPointA == null)
        {
            return;
        }
        if (data.jointPointB == null)
        {
            return;
        }
        if (data.jointPointC == null)
        {
            return;
        }

        GUIStyle style = new GUIStyle();

        style.normal.textColor = Color.black;

        // Real world joint points
        if (showJoints)
        {
            Handles.color = Color.red;
            Handles.SphereCap(0, data.jointPointA.getPosition(), Quaternion.identity, 0.2f);
            Handles.Label(data.jointPointA.getPosition(), data.jointPointA.getLabel(), style);
            Handles.SphereCap(0, data.jointPointA.getWalkingStartPosition(0), Quaternion.identity, 0.1f);
            Handles.SphereCap(0, data.jointPointA.getWalkingStartPosition(1), Quaternion.identity, 0.1f);
            Handles.SphereCap(0, data.jointPointA.getWalkingStartPosition(2), Quaternion.identity, 0.1f);
            Handles.SphereCap(0, data.jointPointA.getWalkingStartPosition(3), Quaternion.identity, 0.1f);

            Handles.SphereCap(0, data.jointPointB.getPosition(), Quaternion.identity, 0.2f);
            Handles.Label(data.jointPointB.getPosition(), data.jointPointB.getLabel(), style);
            Handles.SphereCap(0, data.jointPointB.getWalkingStartPosition(0), Quaternion.identity, 0.1f);
            Handles.SphereCap(0, data.jointPointB.getWalkingStartPosition(1), Quaternion.identity, 0.1f);
            Handles.SphereCap(0, data.jointPointB.getWalkingStartPosition(2), Quaternion.identity, 0.1f);
            Handles.SphereCap(0, data.jointPointB.getWalkingStartPosition(3), Quaternion.identity, 0.1f);

            Handles.SphereCap(0, data.jointPointC.getPosition(), Quaternion.identity, 0.2f);
            Handles.Label(data.jointPointC.getPosition(), data.jointPointC.getLabel(), style);
            Handles.SphereCap(0, data.jointPointC.getWalkingStartPosition(0), Quaternion.identity, 0.1f);
            Handles.SphereCap(0, data.jointPointC.getWalkingStartPosition(1), Quaternion.identity, 0.1f);
            Handles.SphereCap(0, data.jointPointC.getWalkingStartPosition(2), Quaternion.identity, 0.1f);
            Handles.SphereCap(0, data.jointPointC.getWalkingStartPosition(3), Quaternion.identity, 0.1f);
        }

        // Real world curves
        if (showCurves)
        {
            Handles.color = Color.red;

            Vector3 directionVector = data.jointPointB.getWalkingStartPosition(2) - data.curveABsmallRadius.getCircleCenter();
            Handles.DrawWireArc(data.curveABsmallRadius.getCircleCenter(), Vector3.up, directionVector, data.curveABsmallRadius.getAngle(), data.curveABsmallRadius.getRadius());

            directionVector = data.jointPointB.getWalkingStartPosition(3) - data.curveABlargeRadius.getCircleCenter();
            Handles.DrawWireArc(data.curveABlargeRadius.getCircleCenter(), Vector3.up, directionVector, data.curveABlargeRadius.getAngle(), data.curveABlargeRadius.getRadius());

            directionVector = data.jointPointC.getWalkingStartPosition(2) - data.curveBCsmallRadius.getCircleCenter();
            Handles.DrawWireArc(data.curveBCsmallRadius.getCircleCenter(), Vector3.up, directionVector, data.curveBCsmallRadius.getAngle(), data.curveBCsmallRadius.getRadius());

            directionVector = data.jointPointC.getWalkingStartPosition(3) - data.curveBClargeRadius.getCircleCenter();
            Handles.DrawWireArc(data.curveBClargeRadius.getCircleCenter(), Vector3.up, directionVector, data.curveBClargeRadius.getAngle(), data.curveBClargeRadius.getRadius());

            directionVector = data.jointPointA.getWalkingStartPosition(2) - data.curveACsmallRadius.getCircleCenter();
            Handles.DrawWireArc(data.curveACsmallRadius.getCircleCenter(), Vector3.up, directionVector, data.curveACsmallRadius.getAngle(), data.curveACsmallRadius.getRadius());

            directionVector = data.jointPointA.getWalkingStartPosition(3) - data.curveAClargeRadius.getCircleCenter();
            Handles.DrawWireArc(data.curveAClargeRadius.getCircleCenter(), Vector3.up, directionVector, data.curveAClargeRadius.getAngle(), data.curveAClargeRadius.getRadius());
        }

        // Virtual world intersections
        if (showIntersections)
        {
            Handles.color = Color.green;
            foreach (VirtualIntersection intersection in data.intersections)
            {
                // Change color for currently chosen intersection
                if (intersection.Equals(data.intersections[intersectionIndex]))
                {
                    Handles.color = Color.yellow;
                }
                else
                {
                    Handles.color = Color.green;
                }

                Handles.SphereCap(0, intersection.getPosition(), Quaternion.identity, 0.2f);
                Handles.Label(intersection.getPosition(), intersection.getLabel(), style);
                Handles.SphereCap(0, intersection.getWalkingStartPosition(0), Quaternion.identity, 0.1f);
                Handles.SphereCap(0, intersection.getWalkingStartPosition(1), Quaternion.identity, 0.1f);
                Handles.SphereCap(0, intersection.getWalkingStartPosition(2), Quaternion.identity, 0.1f);
                Handles.SphereCap(0, intersection.getWalkingStartPosition(3), Quaternion.identity, 0.1f);
            }
        }

        // Virtual world paths
        if (showPaths)
        {
            foreach (VirtualPath path in data.paths)
            {
                int sign      = data.getSignOfCurve(path.getEndPoints()[0].getJoint(), path.getEndPoints()[1].getJoint());
                int pathIndex = data.getPathIndex(path.getEndPoints()[0].getJoint(), path.getCurve());

                Handles.color = Color.green;
                Vector3 directionVector = path.getEndPoints()[0].getWalkingStartPosition(pathIndex) - path.getCircleCenter();
                Handles.DrawWireArc(path.getCircleCenter(), Vector3.up, directionVector, sign * path.getAngle(), path.getRadius());
            }
        }

        Handles.BeginGUI();
        // GUI stuff comes here
        Handles.EndGUI();
    }
Пример #25
0
    void OnSceneGUI()
    {
        Event e = Event.current;

        if (e.type == EventType.mouseDown)
        {
            Undo.RegisterCompleteObjectUndo(spline, "change spline topography");
            // if alt key pressed, we will have to create a new node if node position is changed
            if (e.alt)
            {
                mustCreateNewNode = true;
            }
        }
        if (e.type == EventType.mouseUp)
        {
            mustCreateNewNode = false;
        }

        // listen for delete key
        if (e.type == EventType.keyDown && e.keyCode == KeyCode.Delete)
        {
            Undo.RegisterCompleteObjectUndo(spline, "delete spline node");
            DeleteNode(selection);
            selection = null;
            e.Use();
        }

        // disable game object transform gyzmo
        if (Selection.activeGameObject == spline.gameObject)
        {
            Tools.current = Tool.None;
            if (selection == null && spline.nodes.Count > 0)
            {
                selection = spline.nodes[0];
            }
        }

        // draw a bezier curve for each curve in the spline
        foreach (CubicBezierCurve curve in spline.GetCurves())
        {
            Handles.DrawBezier(spline.transform.TransformPoint(curve.n1.position),
                               spline.transform.TransformPoint(curve.n2.position),
                               spline.transform.TransformPoint(curve.n1.direction),
                               spline.transform.TransformPoint(curve.GetInverseDirection()),
                               CURVE_COLOR,
                               null,
                               3);
        }

        // draw the selection handles
        switch (selectionType)
        {
        case SelectionType.Node:
            // place a handle on the node and manage position change
            Vector3 newPosition = spline.transform.InverseTransformPoint(Handles.PositionHandle(spline.transform.TransformPoint(selection.Position), Quaternion.identity));
            if (newPosition != selection.Position)
            {
                // position handle has been moved
                if (mustCreateNewNode)
                {
                    mustCreateNewNode    = false;
                    selection            = AddClonedNode(selection);
                    selection.Direction += newPosition - selection.Position;
                    selection.Position   = newPosition;
                }
                else
                {
                    selection.Direction += newPosition - selection.Position;
                    selection.Position   = newPosition;
                }
            }
            break;

        case SelectionType.Direction:
            selection.Direction = spline.transform.InverseTransformPoint(Handles.PositionHandle(spline.transform.TransformPoint(selection.Direction), Quaternion.identity));
            break;

        case SelectionType.InverseDirection:
            selection.Direction = 2 * selection.Position - spline.transform.InverseTransformPoint(Handles.PositionHandle(2 * spline.transform.TransformPoint(selection.Position) - spline.transform.TransformPoint(selection.Direction), Quaternion.identity));
            break;
        }

        // draw the handles of all nodes, and manage selection motion
        Handles.BeginGUI();
        foreach (SplineNode n in spline.nodes)
        {
            Vector3 guiPos = HandleUtility.WorldToGUIPoint(spline.transform.TransformPoint(n.Position));
            if (n == selection)
            {
                Vector3 guiDir    = HandleUtility.WorldToGUIPoint(spline.transform.TransformPoint(n.Direction));
                Vector3 guiInvDir = HandleUtility.WorldToGUIPoint(spline.transform.TransformPoint(2 * n.Position - n.Direction));

                // for the selected node, we also draw a line and place two buttons for directions
                Handles.color = Color.red;
                Handles.DrawLine(guiDir, guiInvDir);

                // draw quads direction and inverse direction if they are not selected
                if (selectionType != SelectionType.Node)
                {
                    if (Button(guiPos, directionButtonStyle))
                    {
                        selectionType = SelectionType.Node;
                    }
                }
                if (selectionType != SelectionType.Direction)
                {
                    if (Button(guiDir, directionButtonStyle))
                    {
                        selectionType = SelectionType.Direction;
                    }
                }
                if (selectionType != SelectionType.InverseDirection)
                {
                    if (Button(guiInvDir, directionButtonStyle))
                    {
                        selectionType = SelectionType.InverseDirection;
                    }
                }
            }
            else
            {
                if (Button(guiPos, nodeButtonStyle))
                {
                    selection     = n;
                    selectionType = SelectionType.Node;
                }
            }
        }
        Handles.EndGUI();

        if (GUI.changed)
        {
            EditorUtility.SetDirty(target);
        }
    }
Пример #26
0
    public static bool SelectPoints(IEditablePoint points, Transform cloudTransform, ref List <int> selection, bool firstSelect)
    {
        int controlID = GUIUtility.GetControlID(FocusType.Passive);

        if (Event.current.alt && (Event.current.type != EventType.Repaint))
        {
            return(false);
        }
        bool  flag2   = false;
        Event current = Event.current;

        switch (current.GetTypeForControl(controlID))
        {
        case EventType.MouseDown:
            if (((HandleUtility.nearestControl == controlID) || firstSelect) && (current.button == 0))
            {
                if (!current.shift && !EditorGUI.actionKey)
                {
                    selection.Clear();
                    flag2 = true;
                }
                s_SelectionStart         = new List <int>(selection);
                GUIUtility.hotControl    = controlID;
                s_StartMouseDragPosition = current.mousePosition;
                s_StartDragSelection     = new List <int>(selection);
                current.Use();
            }
            goto Label_02F5;

        case EventType.MouseUp:
        {
            if ((GUIUtility.hotControl != controlID) || (current.button != 0))
            {
                goto Label_02F5;
            }
            if (s_DidDrag)
            {
                goto Label_0275;
            }
            int item = FindNearest(s_StartMouseDragPosition, cloudTransform, points);
            if (item != -1)
            {
                if (current.shift || EditorGUI.actionKey)
                {
                    int index = selection.IndexOf(item);
                    if (index != -1)
                    {
                        selection.RemoveAt(index);
                    }
                    else
                    {
                        selection.Add(item);
                    }
                    break;
                }
                selection.Add(item);
            }
            break;
        }

        case EventType.MouseDrag:
            if ((GUIUtility.hotControl == controlID) && (current.button == 0))
            {
                s_DidDrag = true;
                selection.Clear();
                selection.AddRange(s_StartDragSelection);
                Rect      rect   = FromToRect(s_StartMouseDragPosition, current.mousePosition);
                Matrix4x4 matrix = Handles.matrix;
                Handles.matrix = cloudTransform.localToWorldMatrix;
                for (int i = 0; i < points.Count; i++)
                {
                    Vector2 point = HandleUtility.WorldToGUIPoint(points.GetPosition(i));
                    if (rect.Contains(point))
                    {
                        if (EditorGUI.actionKey)
                        {
                            if (s_SelectionStart.Contains(i))
                            {
                                selection.Remove(i);
                            }
                        }
                        else if (!s_SelectionStart.Contains(i))
                        {
                            selection.Add(i);
                        }
                    }
                }
                Handles.matrix = matrix;
                GUI.changed    = true;
                current.Use();
            }
            goto Label_02F5;

        case EventType.Repaint:
            if ((GUIUtility.hotControl == controlID) && (current.mousePosition != s_StartMouseDragPosition))
            {
                GUIStyle style = "SelectionRect";
                Handles.BeginGUI();
                style.Draw(FromToRect(s_StartMouseDragPosition, current.mousePosition), false, false, false, false);
                Handles.EndGUI();
            }
            goto Label_02F5;

        case EventType.Layout:
            HandleUtility.AddDefaultControl(controlID);
            goto Label_02F5;

        default:
            goto Label_02F5;
        }
        GUI.changed = true;
        flag2       = true;
Label_0275:
        s_StartDragSelection     = null;
        s_StartMouseDragPosition = Vector2.zero;
        s_DidDrag             = false;
        GUIUtility.hotControl = 0;
        current.Use();
Label_02F5:
        if (flag2)
        {
            selection = selection.Distinct <int>().ToList <int>();
        }
        return(flag2);
    }
Пример #27
0
    /// <summary>
    /// Draw the on-screen selection, knobs, and handle all interaction logic.
    /// </summary>

    public void OnSceneGUI()
    {
        if (!UIWidget.showHandles)
        {
            return;
        }

        mWidget = target as UIWidget;

        Handles.color = mOutlineColor;
        Transform t = mWidget.cachedTransform;

        Event     e    = Event.current;
        int       id   = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
        EventType type = e.GetTypeForControl(id);

        Vector3[] corners = NGUIMath.CalculateWidgetCorners(mWidget);
        Handles.DrawLine(corners[0], corners[1]);
        Handles.DrawLine(corners[1], corners[2]);
        Handles.DrawLine(corners[2], corners[3]);
        Handles.DrawLine(corners[0], corners[3]);

        Vector3[] worldPos = new Vector3[8];

        worldPos[0] = corners[0];
        worldPos[1] = corners[1];
        worldPos[2] = corners[2];
        worldPos[3] = corners[3];

        worldPos[4] = (corners[0] + corners[1]) * 0.5f;
        worldPos[5] = (corners[1] + corners[2]) * 0.5f;
        worldPos[6] = (corners[2] + corners[3]) * 0.5f;
        worldPos[7] = (corners[0] + corners[3]) * 0.5f;

        Vector2[] screenPos = new Vector2[8];
        for (int i = 0; i < 8; ++i)
        {
            screenPos[i] = HandleUtility.WorldToGUIPoint(worldPos[i]);
        }

        Bounds b = new Bounds(screenPos[0], Vector3.zero);

        for (int i = 1; i < 8; ++i)
        {
            b.Encapsulate(screenPos[i]);
        }

        // Time to figure out what kind of action is underneath the mouse
        Action actionUnderMouse = mAction;

        UIWidget.Pivot pivotUnderMouse = UIWidget.Pivot.Center;

        if (actionUnderMouse == Action.None)
        {
            int   index = 0;
            float dist  = GetScreenDistance(worldPos, e.mousePosition, out index);

            if (mWidget.showResizeHandles && dist < 10f)
            {
                pivotUnderMouse  = mPivots[index];
                actionUnderMouse = Action.Scale;
            }
            else if (e.modifiers == 0 && SceneViewDistanceToRectangle(corners, e.mousePosition) == 0f)
            {
                actionUnderMouse = Action.Move;
            }
            else if (dist < 30f)
            {
                actionUnderMouse = Action.Rotate;
            }
        }

        // Change the mouse cursor to a more appropriate one
#if !UNITY_3_5
        {
            Vector2 min = b.min;
            Vector2 max = b.max;

            min.x -= 30f;
            max.x += 30f;
            min.y -= 30f;
            max.y += 30f;

            Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);

            if (actionUnderMouse == Action.Rotate)
            {
                SetCursorRect(rect, MouseCursor.RotateArrow);
            }
            else if (actionUnderMouse == Action.Move)
            {
                SetCursorRect(rect, MouseCursor.MoveArrow);
            }
            else if (mWidget.showResizeHandles && actionUnderMouse == Action.Scale)
            {
                SetCursorRect(rect, MouseCursor.ScaleArrow);
            }
            else
            {
                SetCursorRect(rect, MouseCursor.Arrow);
            }
        }
#endif

        switch (type)
        {
        case EventType.Repaint:
        {
            if (mWidget.showResizeHandles)
            {
                Handles.BeginGUI();
                {
                    for (int i = 0; i < 8; ++i)
                    {
                        DrawKnob(worldPos[i], mWidget.pivot == mPivots[i], id);
                    }
                }
                Handles.EndGUI();
            }
        }
        break;

        case EventType.MouseDown:
        {
            mStartMouse     = e.mousePosition;
            mAllowSelection = true;

            if (e.button == 1)
            {
                if (e.modifiers == 0)
                {
                    GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                    e.Use();
                }
            }
            else if (e.button == 0 && actionUnderMouse != Action.None && Raycast(corners, out mStartDrag))
            {
                mStartPos             = t.position;
                mStartRot             = t.localRotation.eulerAngles;
                mStartDir             = mStartDrag - t.position;
                mStartScale           = t.localScale;
                mDragPivot            = pivotUnderMouse;
                mActionUnderMouse     = actionUnderMouse;
                GUIUtility.hotControl = GUIUtility.keyboardControl = id;
                e.Use();
            }
        }
        break;

        case EventType.MouseDrag:
        {
            // Prevent selection once the drag operation begins
            bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
            if (dragStarted)
            {
                mAllowSelection = false;
            }

            if (GUIUtility.hotControl == id)
            {
                e.Use();

                if (mAction != Action.None || mActionUnderMouse != Action.None)
                {
                    Vector3 pos;

                    if (Raycast(corners, out pos))
                    {
                        if (mAction == Action.None && mActionUnderMouse != Action.None)
                        {
                            // Wait until the mouse moves by more than a few pixels
                            if (dragStarted)
                            {
                                if (mActionUnderMouse == Action.Move)
                                {
                                    mStartPos = t.position;
                                    NGUIEditorTools.RegisterUndo("Move widget", t);
                                }
                                else if (mActionUnderMouse == Action.Rotate)
                                {
                                    mStartRot = t.localRotation.eulerAngles;
                                    mStartDir = mStartDrag - t.position;
                                    NGUIEditorTools.RegisterUndo("Rotate widget", t);
                                }
                                else if (mActionUnderMouse == Action.Scale)
                                {
                                    mStartPos   = t.localPosition;
                                    mStartScale = t.localScale;
                                    mDragPivot  = pivotUnderMouse;
                                    NGUIEditorTools.RegisterUndo("Scale widget", t);
                                }
                                mAction = actionUnderMouse;
                            }
                        }

                        if (mAction != Action.None)
                        {
                            if (mAction == Action.Move)
                            {
                                t.position      = mStartPos + (pos - mStartDrag);
                                pos             = t.localPosition;
                                pos.x           = Mathf.RoundToInt(pos.x);
                                pos.y           = Mathf.RoundToInt(pos.y);
                                t.localPosition = pos;
                            }
                            else if (mAction == Action.Rotate)
                            {
                                Vector3 dir   = pos - t.position;
                                float   angle = Vector3.Angle(mStartDir, dir);

                                if (angle > 0f)
                                {
                                    float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
                                    if (dot < 0f)
                                    {
                                        angle = -angle;
                                    }
                                    angle = mStartRot.z + angle;
                                    if (e.modifiers != EventModifiers.Shift)
                                    {
                                        angle = Mathf.Round(angle / 15f) * 15f;
                                    }
                                    else
                                    {
                                        angle = Mathf.Round(angle);
                                    }
                                    t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
                                }
                            }
                            else if (mAction == Action.Scale)
                            {
                                // World-space delta since the drag started
                                Vector3 delta = pos - mStartDrag;

                                // Adjust the widget's position and scale based on the delta, restricted by the pivot
                                AdjustPosAndScale(mWidget, mStartPos, mStartScale, delta, mDragPivot);
                            }
                        }
                    }
                }
            }
        }
        break;

        case EventType.MouseUp:
        {
            if (GUIUtility.hotControl == id)
            {
                GUIUtility.hotControl      = 0;
                GUIUtility.keyboardControl = 0;

                if (e.button < 2)
                {
                    bool handled = false;

                    if (e.button == 1)
                    {
                        // Right-click: Select the widget below
                        SelectWidget(mWidget, e.mousePosition, false);
                        handled = true;
                    }
                    else if (mAction == Action.None)
                    {
                        if (mAllowSelection)
                        {
                            // Left-click: Select the widget above
                            SelectWidget(mWidget, e.mousePosition, true);
                            handled = true;
                        }
                    }
                    else
                    {
                        // Finished dragging something
                        mAction           = Action.None;
                        mActionUnderMouse = Action.None;
                        Vector3 pos   = t.localPosition;
                        Vector3 scale = t.localScale;

                        if (mWidget.pixelPerfectAfterResize)
                        {
                            t.localPosition = pos;
                            t.localScale    = scale;

                            mWidget.MakePixelPerfect();
                        }
                        else
                        {
                            pos.x   = Mathf.Round(pos.x);
                            pos.y   = Mathf.Round(pos.y);
                            scale.x = Mathf.Round(scale.x);
                            scale.y = Mathf.Round(scale.y);

                            t.localPosition = pos;
                            t.localScale    = scale;
                        }
                        handled = true;
                    }

                    if (handled)
                    {
                        mActionUnderMouse = Action.None;
                        mAction           = Action.None;
                        e.Use();
                    }
                }
            }
            else if (mAllowSelection)
            {
                BetterList <UIWidget> widgets = SceneViewRaycast(mWidget.panel, e.mousePosition);
                if (widgets.size > 0)
                {
                    Selection.activeGameObject = widgets[0].gameObject;
                }
            }
            mAllowSelection = true;
        }
        break;

        case EventType.KeyDown:
        {
            if (e.keyCode == KeyCode.UpArrow)
            {
                Vector3 pos = t.localPosition;
                pos.y          += 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.DownArrow)
            {
                Vector3 pos = t.localPosition;
                pos.y          -= 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.LeftArrow)
            {
                Vector3 pos = t.localPosition;
                pos.x          -= 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.RightArrow)
            {
                Vector3 pos = t.localPosition;
                pos.x          += 1f;
                t.localPosition = pos;
                e.Use();
            }
            else if (e.keyCode == KeyCode.Escape)
            {
                if (GUIUtility.hotControl == id)
                {
                    if (mAction != Action.None)
                    {
                        if (mAction == Action.Move)
                        {
                            t.position = mStartPos;
                        }
                        else if (mAction == Action.Rotate)
                        {
                            t.localRotation = Quaternion.Euler(mStartRot);
                        }
                        else if (mAction == Action.Scale)
                        {
                            t.position   = mStartPos;
                            t.localScale = mStartScale;
                        }
                    }

                    GUIUtility.hotControl      = 0;
                    GUIUtility.keyboardControl = 0;

                    mActionUnderMouse = Action.None;
                    mAction           = Action.None;
                    e.Use();
                }
                else
                {
                    Selection.activeGameObject = null;
                }
            }
        }
        break;
        }
    }
Пример #28
0
        public static bool SplineCPSelector(ObiPath path, bool[] selectionStatus)
        {
            int  controlID              = GUIUtility.GetControlID(splineSelectorHash, FocusType.Passive);
            int  selectedCPIndex        = -1;
            bool selectionStatusChanged = false;

            // select vertex on mouse click:
            switch (Event.current.GetTypeForControl(controlID))
            {
            case EventType.MouseDown:
            {
                if ((Event.current.modifiers & EventModifiers.Control) == 0 &&
                    (HandleUtility.nearestControl != controlID || Event.current.button != 0))
                {
                    break;
                }

                startPos = Event.current.mousePosition;
                marquee.Set(0, 0, 0, 0);

                // If the user is pressing shift, accumulate selection.
                if ((Event.current.modifiers & EventModifiers.Shift) == 0 && (Event.current.modifiers & EventModifiers.Alt) == 0)
                {
                    for (int i = 0; i < selectionStatus.Length; i++)
                    {
                        selectionStatus[i] = false;
                    }
                }

                // If the user is holding down control, dont allow selection of other objects and use marquee tool.
                if ((Event.current.modifiers & EventModifiers.Control) != 0)
                {
                    GUIUtility.hotControl = controlID;
                }

                float minSqrDistance          = System.Single.MaxValue;
                float sqrMinSelectionDistance = minSelectionDistance * minSelectionDistance;

                for (int i = 0; i < path.ControlPointCount; i++)
                {
                    // get particle position in gui space:
                    Vector2 pos = HandleUtility.WorldToGUIPoint(path.points[i].position);

                    // get distance from mouse position to particle position:
                    float sqrDistance = Vector2.SqrMagnitude(startPos - pos);

                    // check if this control point is closer to the cursor that any previously considered point.
                    if (sqrDistance < sqrMinSelectionDistance && sqrDistance < minSqrDistance)
                    {
                        minSqrDistance  = sqrDistance;
                        selectedCPIndex = i;
                    }
                }

                if (selectedCPIndex >= 0)
                {         // toggle particle selection status.
                    selectionStatus[selectedCPIndex] = !selectionStatus[selectedCPIndex];
                    selectionStatusChanged           = true;

                    // Prevent spline deselection if we have selected a particle:
                    GUIUtility.hotControl = controlID;
                    Event.current.Use();
                }
                else if (Event.current.modifiers == EventModifiers.None)
                {         // deselect all particles:
                    for (int i = 0; i < selectionStatus.Length; i++)
                    {
                        selectionStatus[i] = false;
                    }

                    selectionStatusChanged = true;
                }
            }
            break;

            case EventType.MouseDrag:

                if (GUIUtility.hotControl == controlID)
                {
                    currentPos = Event.current.mousePosition;
                    if (!dragging && Vector2.Distance(startPos, currentPos) > 5)
                    {
                        dragging = true;
                    }
                    else
                    {
                        GUIUtility.hotControl = controlID;
                        Event.current.Use();
                    }

                    //update marquee rect:
                    float left   = Mathf.Min(startPos.x, currentPos.x);
                    float right  = Mathf.Max(startPos.x, currentPos.x);
                    float bottom = Mathf.Min(startPos.y, currentPos.y);
                    float top    = Mathf.Max(startPos.y, currentPos.y);

                    marquee = new Rect(left, bottom, right - left, top - bottom);
                }

                break;

            case EventType.MouseUp:

                if (GUIUtility.hotControl == controlID)
                {
                    dragging = false;

                    for (int i = 0; i < path.ControlPointCount; i++)
                    {
                        // get particle position in gui space:
                        Vector2 pos = HandleUtility.WorldToGUIPoint(path.points[i].position);

                        if (pos.x > marquee.xMin && pos.x < marquee.xMax && pos.y > marquee.yMin && pos.y < marquee.yMax)
                        {
                            selectionStatus[i]     = true;
                            selectionStatusChanged = true;
                        }
                    }

                    GUIUtility.hotControl = 0;
                    Event.current.Use();
                }

                break;

            case EventType.Repaint:

                if (dragging)
                {
                    GUISkin oldSkin = GUI.skin;
                    GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene);
                    Handles.BeginGUI();
                    GUI.Box(new Rect(marquee.xMin, marquee.yMin, marquee.width, marquee.height), "");
                    Handles.EndGUI();
                    GUI.skin = oldSkin;
                }

                break;


            case EventType.Layout:
            {
                float minSqrDistance          = System.Single.MaxValue;
                float sqrMinSelectionDistance = minSelectionDistance * minSelectionDistance;

                for (int i = 0; i < path.ControlPointCount; i++)
                {
                    // get particle position in gui space:
                    Vector2 pos = HandleUtility.WorldToGUIPoint(path.points[i].position);

                    // get distance from mouse position to particle position:
                    float sqrDistance = Vector2.SqrMagnitude(Event.current.mousePosition - pos);

                    // check if this control point is closer to the cursor that any previously considered point.
                    if (sqrDistance < sqrMinSelectionDistance && sqrDistance < minSqrDistance)
                    {         //magic number 900 = 30*30, where 30 is min distance in pixels to select a particle.
                        minSqrDistance = sqrDistance;
                    }
                }

                HandleUtility.AddControl(controlID, Mathf.Sqrt(minSqrDistance));
            }
            break;
            }

            return(selectionStatusChanged);
        }
Пример #29
0
    public void OnSceneGUI()
    {
        if (tk2dPreferences.inst.enableSpriteHandles == false)
        {
            return;
        }

        tk2dUIMask mask         = (tk2dUIMask)target;
        Transform  t            = mask.transform;
        Vector3    anchorOffset = tk2dSceneHelper.GetAnchorOffset(mask.size, mask.anchor);
        Rect       localRect    = new Rect(anchorOffset.x, anchorOffset.y, mask.size.x, mask.size.y);

        // Draw rect outline
        Handles.color = new Color(1, 1, 1, 0.5f);
        tk2dSceneHelper.DrawRect(localRect, t);

        Handles.BeginGUI();
        // Resize handles
        if (tk2dSceneHelper.RectControlsToggle())
        {
            EditorGUI.BeginChangeCheck();
            Rect resizeRect = tk2dSceneHelper.RectControl(999888, localRect, t);
            if (EditorGUI.EndChangeCheck())
            {
                Vector2 newDim = new Vector2(resizeRect.width, resizeRect.height);
                newDim.x = Mathf.Abs(newDim.x);
                newDim.y = Mathf.Abs(newDim.y);
                tk2dUndo.RecordObjects(new Object[] { t, mask }, "Resize");
                if (newDim != mask.size)
                {
                    mask.size = newDim;
                    mask.Build();
                    Vector2 newAnchorOffset = tk2dSceneHelper.GetAnchorOffset(new Vector2(resizeRect.width, resizeRect.height), mask.anchor);
                    Vector3 toNewAnchorPos  = new Vector3(resizeRect.xMin - newAnchorOffset.x, resizeRect.yMin - newAnchorOffset.y, 0);
                    Vector3 newPosition     = t.TransformPoint(toNewAnchorPos);
                    if (newPosition != t.position)
                    {
                        t.position = newPosition;
                    }

                    tk2dUtil.SetDirty(mask);
                }
            }
        }
        // Rotate handles
        if (!tk2dSceneHelper.RectControlsToggle())
        {
            EditorGUI.BeginChangeCheck();
            float theta = tk2dSceneHelper.RectRotateControl(888999, localRect, t, new List <int>());
            if (EditorGUI.EndChangeCheck())
            {
                if (Mathf.Abs(theta) > Mathf.Epsilon)
                {
                    tk2dUndo.RecordObject(t, "Rotate");
                    t.Rotate(t.forward, theta, Space.World);
                }
            }
        }
        Handles.EndGUI();

        // Sprite selecting
        tk2dSceneHelper.HandleSelectSprites();

        // Move targeted sprites
        tk2dSceneHelper.HandleMoveSprites(t, localRect);
    }
Пример #30
0
    private void OnDrawGizmos()
    {
        if (!enabled)
        {
            return;
        }
        if (GetComponent <MeshFilter>() != null || gameObject.collider != null)
        {
            CanDrawBounds = GetComponent <CharacterController>() == null;
        }
        else
        {
            CanDrawBounds = false;
        }
        CanDrawCamera = GetComponent <Camera>();
        Color     tmp = Gizmos.color;
        Matrix4x4 mat = Gizmos.matrix;

        switch (GizmoType)
        {
        case GizmoTypes.Anchor:
            Gizmos.color = Outline;
            Gizmos.DrawWireSphere(transform.position, GizmoSize);
            Gizmos.DrawRay(transform.position, transform.forward * GizmoSize * 2);
            Gizmos.color = Extra;
            Gizmos.DrawRay(transform.position, transform.up * GizmoSize * 2);
            Gizmos.DrawLine(transform.position - transform.forward * 0.1f * GizmoSize,
                            transform.position - transform.forward * 0.1f * GizmoSize + transform.right * 0.4f * GizmoSize * 2);
            Gizmos.DrawLine(transform.position - transform.forward * 0.1f * GizmoSize,
                            transform.position - transform.forward * 0.1f * GizmoSize - transform.right * 0.4f * GizmoSize * 2);
            Gizmos.color = GizmoLine;
            Gizmos.DrawRay(transform.position, transform.right * GizmoSize * 2);
            Gizmos.color = TextColor;
            Gizmos.DrawRay(transform.position, -transform.up * GizmoSize * 2);
            Gizmos.DrawRay(transform.position, -transform.right * GizmoSize * 2);
            Gizmos.DrawRay(transform.position, -transform.forward * GizmoSize * 2);
            if (DrawVolumetric)
            {
                Gizmos.color = Volumetric;
                Gizmos.DrawSphere(transform.position, Radius * GizmoSize);
            }
            break;

        case GizmoTypes.Arrows:
            HELPER.DrawArrow(transform.position, transform.forward * GizmoSize, Color.blue);
            HELPER.DrawArrow(transform.position, transform.up * GizmoSize, Color.green);
            HELPER.DrawArrow(transform.position, transform.right * GizmoSize, Color.red);
            break;

        case GizmoTypes.Box:
            Gizmos.color = GizmoLine;
            Gizmos.DrawWireCube(transform.position, Size * GizmoSize);
            if (DrawVolumetric)
            {
                Gizmos.color = Volumetric;
                Gizmos.DrawCube(transform.position, Size * GizmoSize);
            }
            break;

        case GizmoTypes.Circle:
            HELPER.DrawCircle(transform.position, Radius, Sections, CircleRotation, Angle, GizmoLine);
            break;

        case GizmoTypes.Direction:
            if (Direction != Vector3.zero)
            {
                HELPER.DrawArrow(transform.position, Direction, GizmoLine);
            }
            break;

        case GizmoTypes.Sphere:
            Gizmos.color = GizmoLine;
            Gizmos.DrawWireSphere(transform.position, Radius * GizmoSize);
            if (DrawVolumetric)
            {
                Gizmos.color = Volumetric;
                Gizmos.DrawSphere(transform.position, Radius * GizmoSize);
            }
            break;

        case GizmoTypes.Text:
            if (!string.IsNullOrEmpty(Text) && TextOffset != Vector3.zero)
            {
                Gizmos.color = new Color(TextColor.r, TextColor.g, TextColor.b, 0.3f);
                Gizmos.DrawLine(transform.position, transform.position + TextOffset);
            }
            GUIStyle style = new GUIStyle("box");
            style.normal.textColor = TextColor;
            Handles.BeginGUI();
            Vector3 pos   = transform.position + TextOffset;
            Vector2 pos2D = HandleUtility.WorldToGUIPoint(pos);
            GUI.Label(new Rect(pos2D.x, pos2D.y, 100, 30), Text, style);
            Handles.EndGUI();
            break;

        case GizmoTypes.Capsule:
            HELPER.DrawCapsule(transform, transform.position, Radius, Height, GizmoLine);
            break;

        case GizmoTypes.Character:
            // TODO: Future Gizmo for the npc/Enemy motor script !
            break;

        case GizmoTypes.Player:
            if (GetComponent <RPGPlayerMotor>() != null)
            {
                Vector3 position = transform.position + GetComponent <CharacterController>().center;
                position = new Vector3(position.x, position.y - GetComponent <CharacterController>().height / 2f, position.z);
                HELPER.DrawCapsule(transform, position, GetComponent <CharacterController>().radius, GetComponent <CharacterController>().height, GizmoLine);
                HELPER.DrawArrow(transform.position, RPGPlayerMotor.Instance.MoveDirection, Extra);
            }
            break;

        case GizmoTypes.None:
            break;
        }
        if (PointSphere)
        {
            Gizmos.color = pointSphereColor;
            Gizmos.DrawSphere(transform.position, PoinSpehereRadius * GizmoSize);
        }
        if (DrawBoundings)
        {
            if (GetComponent <MeshFilter>() != null || gameObject.collider != null)
            {
                Gizmos.color = Outline;
                if (GetComponent <SphereCollider>() == null && GetComponent <CapsuleCollider>() == null && GetComponent <CharacterController>() == null)
                {
                    var bounds = GetComponent <MeshFilter>()
                        ? GetComponent <MeshFilter>().sharedMesh.bounds
                        : gameObject.collider.bounds;
                    if (UseLocalMatrix)
                    {
                        Gizmos.matrix = transform.localToWorldMatrix;
                    }
                    Gizmos.DrawWireCube(bounds.center, bounds.size);
                    if (DrawVolumetric)
                    {
                        Gizmos.color = Volumetric;
                        Gizmos.DrawCube(bounds.center, bounds.size);
                    }
                    Gizmos.matrix = mat;
                }
                else if (GetComponent <SphereCollider>())
                {
                    Gizmos.DrawWireSphere(transform.position, GetComponent <SphereCollider>().radius);
                    if (DrawVolumetric)
                    {
                        Gizmos.color = Volumetric;
                        Gizmos.DrawSphere(transform.position, GetComponent <SphereCollider>().radius);
                    }
                }
                else if (GetComponent <CapsuleCollider>())
                {
                    var     radius   = GetComponent <CapsuleCollider>().radius;
                    var     height   = GetComponent <CapsuleCollider>().height;
                    Vector3 position = transform.position + GetComponent <CapsuleCollider>().center;
                    position = new Vector3(position.x, position.y - height / 2f, position.z);
                    HELPER.DrawCapsule(transform, position, radius, height, GizmoLine);
                }
            }
        }
        if (DrawCamera && GetComponent <Camera>())
        {
            Vector3[] nearCorners = new Vector3[4];
            Vector3[] farCorners  = new Vector3[4];
            Plane[]   camPlanes   = GeometryUtility.CalculateFrustumPlanes(GetComponent <Camera>());
            Plane     temp        = camPlanes[1];
            camPlanes[1] = camPlanes[2];
            camPlanes[2] = temp;
            for (int i = 0; i < 4; i++)
            {
                nearCorners[i] = HELPER.Plan2Intersect(camPlanes[4], camPlanes[i], camPlanes[(i + 1) % 4]);
                farCorners[i]  = HELPER.Plan2Intersect(camPlanes[5], camPlanes[i], camPlanes[(i + 1) % 4]);
            }
            for (int i = 0; i < 4; i++)
            {
                Debug.DrawLine(nearCorners[i], nearCorners[(i + 1) % 4], Outline, Time.deltaTime, true);
                Debug.DrawLine(farCorners[i], farCorners[(i + 1) % 4], Outline, Time.deltaTime, true);
                Debug.DrawLine(nearCorners[i], farCorners[i], GizmoLine, Time.deltaTime, true);
            }
        }
        if (DrawTexture && !string.IsNullOrEmpty(Icon))
        {
            Gizmos.DrawIcon(transform.position + IconOffset, Icon);
            Gizmos.color = new Color(Outline.r, Outline.g, Outline.b, 0.3f);
            Gizmos.DrawLine(transform.position, transform.position + IconOffset);
        }
        if (PointBehavior == PointBehaviors.PlayerSpawn || PointBehavior == PointBehaviors.EnemySpawn ||
            PointBehavior == PointBehaviors.NPCSpawn)
        {
            HELPER.DrawCircle(transform.position, 0.4f, 24, Vector3.zero, 360, GizmoLine);
        }
        Gizmos.color = tmp;
    }