Exemple #1
0
        private void GizmoRotate(GizmoMode mode, float newAngle)
        {
            if (_control != null)
            {
                var model     = _control.Model;
                var animation = _editor.CurrentAnim;
                if (animation == null || _control.SelectedMesh == null)
                {
                    return;
                }

                var meshIndex      = model.Meshes.IndexOf(_control.SelectedMesh);
                var rotationVector = _editor.CurrentKeyFrame.Rotations[meshIndex];
                var delta          = 0f;
                var axis           = Vector3.Zero;

                switch (mode)
                {
                case GizmoMode.RotateX: delta = newAngle - rotationVector.X; axis = Vector3.UnitX; break;

                case GizmoMode.RotateY: delta = newAngle - rotationVector.Y; axis = Vector3.UnitY; break;

                case GizmoMode.RotateZ: delta = newAngle - rotationVector.Z; axis = Vector3.UnitZ; break;
                }

                var quat = _editor.CurrentKeyFrame.Quaternions[meshIndex] * Quaternion.CreateFromAxisAngle(axis, delta);
                _editor.UpdateTransform(meshIndex, MathC.QuaternionToEuler(quat), _editor.CurrentKeyFrame.Translations[0]);

                _control.Model.BuildAnimationPose(_editor.CurrentKeyFrame);
                _control.Invalidate();
            }
        }
Exemple #2
0
    public void SetGizmoMode(int val)
    {
        transform.localRotation = Quaternion.identity;
        switch (val)
        {
        case 0:
            gizmoMode = GizmoMode.translate;
            break;

        case 1:
            gizmoMode = GizmoMode.rotate;
            break;

        case 2:
            gizmoMode = GizmoMode.scale;
            break;

        case 3:
            gizmoMode = GizmoMode.extrude;
            //Set selection mode to face, so that extrude tool can be used.
            if (MeshEdit.selectionMode == 0)
            {
                ui.DROPDOWN_SELMODE.value = 1;
            }
            SetExtrudeAngle();
            break;

        default:
            Debug.LogError("Cannot set gizmo mode to " + val + ". Must be between 0 and 3"); break;
        }
        SetGizmoStates(gizmoMode);
        SetPositionAuto();
    }
        public static GizmoMode ToggleGizmoType(GizmoMode mode = GizmoMode.Null)
        {
            ScreenUnclicked();

            if (mode == GizmoMode.Null)
            {
                if (CurrentGizmoMode == GizmoMode.Position)
                {
                    CurrentGizmoMode = GizmoMode.Rotation;
                }
                else if (CurrentGizmoMode == GizmoMode.Rotation)
                {
                    CurrentGizmoMode = GizmoMode.Scale;
                }
                else if (CurrentGizmoMode == GizmoMode.Scale)
                {
                    CurrentGizmoMode = GizmoMode.PositionLocal;
                }
                else if (CurrentGizmoMode == GizmoMode.PositionLocal)
                {
                    CurrentGizmoMode = GizmoMode.Position;
                }
            }
            else
            {
                CurrentGizmoMode = mode;
            }

            return(CurrentGizmoMode);
        }
Exemple #4
0
        /// <returns>If the parent should be redrawn</returns>
        public bool MouseUp()
        {
            GizmoMode oldMode = _mode;

            _mode = GizmoMode.None;
            return(oldMode != GizmoMode.None);
        }
Exemple #5
0
        public void Hook(SerializedProperty property, Quaternion rotation, GizmoMode gizmoMode = GizmoMode.Rotate)
        {
            Mode = gizmoMode;

            Unhook();
            StartPicker(Vector3.zero, rotation);
            CurrentPropertyPath       = property.propertyPath;
            SceneView.duringSceneGui += OnSceneGUI;
            SceneView.RepaintAll();
        }
Exemple #6
0
        public static void Update()
        {
            gizmoMode = GizmoMode.Translate;
            if (SelectedObject == null)
            {
                return;
            }


            Gizmo.Position = SelectedObject.Position;
        }
Exemple #7
0
        public void ActivateGizmo(PickingResultGizmo pickingResult)
        {
            _mode = pickingResult.Mode;

            _scaleBase               = SupportScale ? Scale : Vector3.One;
            _rotationPickAngle       = SimplifyAngle(pickingResult.RotationPickAngle);
            _rotationPickAngleOffset = SimplifyAngle(
                (pickingResult.Mode == GizmoMode.RotateY ? RotationY :
                 pickingResult.Mode == GizmoMode.RotateX ? RotationX :
                 pickingResult.Mode == GizmoMode.RotateZ ? RotationZ : 0.0f) - pickingResult.RotationPickAngle);
            _rotationLastMouseAngle  = SimplifyAngle(pickingResult.RotationPickAngle);
            _rotationLastMouseRadius = pickingResult.Distance;
        }
Exemple #8
0
        /// <returns>If the parent should be redrawn</returns>
        public bool GizmoUpdateHoverEffect(PickingResultGizmo pickingResult)
        {
            GizmoMode oldHoveredMode = _hoveredMode;

            // Disable hover mode
            if (pickingResult == null)
            {
                _hoveredMode = GizmoMode.None;
                return(oldHoveredMode != _hoveredMode);
            }

            // Set hover mode
            _hoveredMode = pickingResult.Mode;
            return(oldHoveredMode != _hoveredMode);
        }
        void Start()
        {
            gizmoMaterial = Instantiate(MaterialsDatabase.GizmoMaterial); //copy material so we can modify it

            CreateMove();
            CreateRotate();
            CreateScale();

            Mode = GizmoMode.Move;

            EditWindowClickDetection.beginDragHandlers.Add(HandleBeginDrag, 0);
            EditWindowClickDetection.dragHandlers.Add(HandleDrag, 0);
            EditWindowClickDetection.endDragHandlers.Add(HandleEndDrag, 0);

            Visible = false;
        }
Exemple #10
0
    private void SetGizmoStates(GizmoMode mode)
    {
        Color colorInactive = new Color(1, 1, 1, 0.5f);
        Color colorActive   = new Color(1, 1, 1, 1);

        translateRoot.SetActive(mode == GizmoMode.translate);
        //BUTTON_TRANSLATE.color = mode == GizmoMode.translate ? colorActive : colorInactive;

        rotateRoot.SetActive(mode == GizmoMode.rotate);
        //BUTTON_ROTATE.color = mode == GizmoMode.rotate ? colorActive : colorInactive;

        scaleRoot.SetActive(mode == GizmoMode.scale);
        //BUTTON_SCALE.color = mode == GizmoMode.scale ? colorActive : colorInactive;

        extrudeRoot.SetActive(mode == GizmoMode.extrude);
        //BUTTON_EXTRUDE.color = mode == GizmoMode.extrude ? colorActive : colorInactive;
    }
        protected void HandleGizmoMode()
        {
            GizmoMode oldGizmoMode = m_GizmoMode;
            var       evt          = eventSystem.current;

            if (evt.control)
            {
                m_GizmoMode = GizmoMode.BorderEditing;
            }
            else
            {
                m_GizmoMode = GizmoMode.RectEditing;
            }

            if (oldGizmoMode != m_GizmoMode && (evt.type == EventType.KeyDown || evt.type == EventType.KeyUp) && (evt.keyCode == KeyCode.LeftControl || evt.keyCode == KeyCode.RightControl || evt.keyCode == KeyCode.LeftAlt || evt.keyCode == KeyCode.RightAlt))
            {
                Repaint();
            }
        }
Exemple #12
0
        private static void comboGizmoMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ignoreGizmoModeChange)
            {
                return;
            }

            if (Program.main.comboGizmoMode.SelectedIndex == 0) //Translation
            {
                GizmoMode = GizmoMode.TRANSLATION;
                Renderer.InvalidateView();
                Renderer.Invalidate();
            }
            else if (Program.main.comboGizmoMode.SelectedIndex == 1) //Rotation
            {
                GizmoMode = GizmoMode.ROTATION;
                Renderer.InvalidateView();
                Renderer.Invalidate();
            }
        }
Exemple #13
0
        public static void KeyDown()
        {
            if (ActionKey.IsDown(Action.MODE_TRANSLATION))
            {
                GizmoMode = GizmoMode.TRANSLATION;
                Renderer.InvalidateView();
                Renderer.Invalidate();
            }
            else if (ActionKey.IsDown(Action.MODE_ROTATION))
            {
                bool allowRotation = true;
                foreach (ISelectable selectable in Selected)
                {
                    if (!selectable.AllowRotation)
                    {
                        allowRotation = false;
                        break;
                    }
                }

                if (allowRotation) //Don't allow rotation changes if the object cannot be rotated
                {
                    GizmoMode = GizmoMode.ROTATION;
                    Renderer.InvalidateView();
                    Renderer.Invalidate();
                }
                else
                {
                    SystemSounds.Beep.Play();
                }
            }

            if (ActionKey.IsDown(Action.CAM_FOCUS_SELECTION))
            {
                if (Selected.Count > 0)
                {
                    Program.Camera.LookAt = AveragePosition;
                    Renderer.InvalidateView();
                    Renderer.Invalidate();
                }
                else
                {
                    SystemSounds.Beep.Play();
                }
            }
            if (ActionKey.IsDown(Action.SELECTION_DELETE))
            {
                if (Selected.Count > 0)
                {
                    new ActionDelete(Selected.ToArray());
                }
                else
                {
                    SystemSounds.Beep.Play();
                }
            }
            if (ActionKey.IsDown(Action.SELECTION_COPY))
            {
                Copied = Selected.ToList();
            }
            else if (ActionKey.IsDown(Action.SELECTION_PASTE))
            {
                Selected.Clear();

                foreach (IElement obj in Copied)
                {
                    Selected.Add((IElement)obj.Copy());
                }
            }
        }
Exemple #14
0
        public void Draw(Matrix4x4 viewProjection)
        {
            if (!DrawGizmo)
            {
                return;
            }

            bool upside = Orientation == GizmoOrientation.UpsideDown;

            _device.SetRasterizerState(_device.RasterizerStates.CullNone);

            var       solidEffect = _effect;
            GizmoMode highlight   = _mode == GizmoMode.None ? _hoveredMode : _mode;

            // Rotation
            if (SupportRotationX | SupportRotationY | SupportRotationZ)
            {
                // Setup torus model
                float requiredTorusRadius = LineThickness * 0.5f / Size;
                if (_torusRadius != requiredTorusRadius)
                {
                    _torus?.Dispose();
                    _torus       = GeometricPrimitive.Torus.New(_device, 1.0f, requiredTorusRadius, 48, _lineRadiusTesselation);
                    _torusRadius = requiredTorusRadius;
                }
                _torus.SetupForRendering(_device);

                // Rotation Y
                if (SupportRotationY)
                {
                    var model = Matrix4x4.CreateScale(Size * 2.0f) *
                                RotateMatrixY *
                                Matrix4x4.CreateTranslation(Position);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_yAxisColor + (highlight == GizmoMode.RotateY ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _torus.IndexBuffer.ElementCount);
                }

                // Rotation X
                if (SupportRotationX)
                {
                    var model = Matrix4x4.CreateScale(Size * 2.0f) *
                                Matrix4x4.CreateRotationZ((float)Math.PI / 2.0f) *
                                RotateMatrixX *
                                Matrix4x4.CreateTranslation(Position);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_xAxisColor + (highlight == GizmoMode.RotateX ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _torus.IndexBuffer.ElementCount);
                }

                // Rotation Z
                if (SupportRotationZ)
                {
                    var model = Matrix4x4.CreateScale(Size * 2.0f) *
                                Matrix4x4.CreateRotationX((float)Math.PI / 2.0f) *
                                RotateMatrixZ *
                                Matrix4x4.CreateTranslation(Position);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_zAxisColor + (highlight == GizmoMode.RotateZ ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();

                    _device.DrawIndexed(PrimitiveType.TriangleList, _torus.IndexBuffer.ElementCount);
                }
            }

            // Scale
            if (SupportScale)
            {
                _cylinder.SetupForRendering(_device);

                // X axis
                {
                    var model = Matrix4x4.CreateTranslation(new Vector3(0.0f, 0.5f, 0.0f)) *
                                Matrix4x4.CreateScale(new Vector3(LineThickness * 1.1f, (upside ? -Size : Size) / 2.0f, LineThickness * 1.1f)) *
                                Matrix4x4.CreateRotationZ(-(float)Math.PI / 2.0f) *
                                Matrix4x4.CreateTranslation(Position);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_xAxisColor + (highlight == GizmoMode.ScaleX ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cylinder.IndexBuffer.ElementCount);
                }

                // Y axis
                {
                    var model = Matrix4x4.CreateTranslation(new Vector3(0.0f, 0.5f, 0.0f)) *
                                Matrix4x4.CreateScale(new Vector3(LineThickness * 1.1f, (upside ? -Size : Size) / 2.0f, LineThickness * 1.1f)) *
                                Matrix4x4.CreateTranslation(Position);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_yAxisColor + (highlight == GizmoMode.ScaleY ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cylinder.IndexBuffer.ElementCount);
                }

                // Z axis
                {
                    var model = Matrix4x4.CreateTranslation(new Vector3(0.0f, 0.5f, 0.0f)) *
                                Matrix4x4.CreateScale(new Vector3(LineThickness * 1.1f, (upside ? -Size : Size) / 2.0f, LineThickness * 1.1f)) *
                                Matrix4x4.CreateRotationX(-(float)Math.PI / 2.0f) *
                                Matrix4x4.CreateTranslation(Position);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_zAxisColor + (highlight == GizmoMode.ScaleZ ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cylinder.IndexBuffer.ElementCount);
                }

                _cube.SetupForRendering(_device);

                // X axis scale
                {
                    var model = Matrix4x4.CreateScale(ScaleCubeSize) *
                                Matrix4x4.CreateTranslation(Position + Vector3.UnitX * (upside ? -Size : Size) / 2.0f);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_xAxisColor + (highlight == GizmoMode.ScaleX ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cube.IndexBuffer.ElementCount);
                }

                // Y axis scale
                {
                    var model = Matrix4x4.CreateScale(ScaleCubeSize) *
                                Matrix4x4.CreateTranslation(Position + Vector3.UnitY * (upside ? -Size : Size) / 2.0f);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_yAxisColor + (highlight == GizmoMode.ScaleY ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cube.IndexBuffer.ElementCount);
                }

                // Z axis scale
                {
                    var model = Matrix4x4.CreateScale(ScaleCubeSize) *
                                Matrix4x4.CreateTranslation(Position - Vector3.UnitZ * (upside ? -Size : Size) / 2.0f);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_zAxisColor + (highlight == GizmoMode.ScaleZ ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cube.IndexBuffer.ElementCount);
                }
            }


            // Translation
            {
                _cylinder.SetupForRendering(_device);

                // X axis
                if (SupportTranslateX)
                {
                    var model = Matrix4x4.CreateTranslation(new Vector3(0.0f, 0.5f, 0.0f)) *
                                Matrix4x4.CreateScale(new Vector3(LineThickness, (upside ? -Size : Size) * _arrowHeadOffsetMultiplier, LineThickness)) *
                                Matrix4x4.CreateRotationZ(-(float)Math.PI / 2.0f) *
                                Matrix4x4.CreateTranslation(Position);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_xAxisColor + (highlight == GizmoMode.TranslateX ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cylinder.IndexBuffer.ElementCount);
                }

                // Y axis
                if (SupportTranslateY)
                {
                    var model = Matrix4x4.CreateTranslation(new Vector3(0.0f, 0.5f, 0.0f)) *
                                Matrix4x4.CreateScale(new Vector3(LineThickness, (upside ? -Size : Size) * _arrowHeadOffsetMultiplier, LineThickness)) *
                                Matrix4x4.CreateTranslation(Position);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_yAxisColor + (highlight == GizmoMode.TranslateY ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cylinder.IndexBuffer.ElementCount);
                }

                // Z axis
                if (SupportTranslateZ)
                {
                    var model = Matrix4x4.CreateTranslation(new Vector3(0.0f, 0.5f, 0.0f)) *
                                Matrix4x4.CreateScale(new Vector3(LineThickness, (upside ? -Size : Size) * _arrowHeadOffsetMultiplier, LineThickness)) *
                                Matrix4x4.CreateRotationX(-(float)Math.PI / 2.0f) *
                                Matrix4x4.CreateTranslation(Position);
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_zAxisColor + (highlight == GizmoMode.TranslateZ ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cylinder.IndexBuffer.ElementCount);
                }

                _cone.SetupForRendering(_device);

                // X axis translation
                if (SupportTranslateX)
                {
                    var model = Matrix4x4.CreateRotationY((float)(upside ? -Math.PI * 1.5f : -Math.PI * 0.5f)) *
                                Matrix4x4.CreateScale(TranslationConeSize) *
                                Matrix4x4.CreateTranslation(Position + (Vector3.UnitX + new Vector3(0.1f, 0, 0)) * ((upside ? -Size : Size) * _arrowHeadOffsetMultiplier));
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_xAxisColor + (highlight == GizmoMode.TranslateX ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cone.IndexBuffer.ElementCount);
                }

                // Y axis translation
                if (SupportTranslateY)
                {
                    var model = Matrix4x4.CreateRotationX((float)(upside ? Math.PI * 1.5f : Math.PI * 0.5f)) *
                                Matrix4x4.CreateScale(TranslationConeSize) *
                                Matrix4x4.CreateTranslation(Position + (Vector3.UnitY + new Vector3(0, 0.1f, 0)) * ((upside ? -Size : Size) * _arrowHeadOffsetMultiplier));
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_yAxisColor + (highlight == GizmoMode.TranslateY ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cone.IndexBuffer.ElementCount);
                }

                // Z axis translation
                if (SupportTranslateZ)
                {
                    var model = Matrix4x4.CreateRotationY((float)(upside ? Math.PI : 0.0f)) *
                                Matrix4x4.CreateScale(TranslationConeSize) *
                                Matrix4x4.CreateTranslation(Position - (Vector3.UnitZ + new Vector3(0, 0, 0.1f)) * ((upside ? -Size : Size) * _arrowHeadOffsetMultiplier));
                    solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                    solidEffect.Parameters["Color"].SetValue(_zAxisColor + (highlight == GizmoMode.TranslateZ ? _hoveredAddition : new Vector4()));
                    solidEffect.CurrentTechnique.Passes[0].Apply();
                    _device.DrawIndexed(PrimitiveType.TriangleList, _cone.IndexBuffer.ElementCount);
                }
            }

            // All time geometry
            {
                /*_device.SetVertexBuffer(_cube.VertexBuffer);
                 * _device.SetVertexInputLayout(VertexInputLayout.FromBuffer(0, _cube.VertexBuffer));
                 * _device.SetIndexBuffer(_cube.IndexBuffer, _cube.IsIndex32Bits);
                 *
                 * // center cube
                 * {
                 *  var model = Matrix4x4.CreateScale(CentreCubeSize) * Matrix4x4.CreateTranslation(Position);
                 *  solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                 *  solidEffect.Parameters["Color"].SetValue(_centerColor);
                 *  solidEffect.CurrentTechnique.Passes[0].Apply();
                 *
                 *  _device.DrawIndexed(PrimitiveType.TriangleList, _cube.IndexBuffer.ElementCount);
                 * }*/
            }

            _device.SetRasterizerState(_device.RasterizerStates.CullBack);

            // Rotation display vertices
            switch (_mode)
            {
            case GizmoMode.RotateY:
            case GizmoMode.RotateX:
            case GizmoMode.RotateZ:

                // Figure out relevant angle
                float     startAngle;
                float     endAngle;
                float     lastMouseAngle;
                Matrix4x4 baseMatrix;
                Vector4   color;
                switch (_mode)
                {
                case GizmoMode.RotateY:
                    startAngle     = _rotationPickAngle;
                    endAngle       = RotationY - _rotationPickAngleOffset;
                    lastMouseAngle = _rotationLastMouseAngle;
                    baseMatrix     = RotateMatrixY;
                    color          = _yAxisColor;
                    break;

                case GizmoMode.RotateX:
                    startAngle     = -((float)Math.PI * 0.5f) - _rotationPickAngle;
                    endAngle       = -((float)Math.PI * 0.5f) - (RotationX - _rotationPickAngleOffset);
                    lastMouseAngle = -((float)Math.PI * 0.5f) - _rotationLastMouseAngle;
                    baseMatrix     = Matrix4x4.CreateRotationZ((float)Math.PI / 2.0f) * RotateMatrixX;
                    color          = _xAxisColor;
                    break;

                case GizmoMode.RotateZ:
                    startAngle     = (float)Math.PI + _rotationPickAngle;
                    endAngle       = (float)Math.PI + RotationZ - _rotationPickAngleOffset;
                    lastMouseAngle = (float)Math.PI + _rotationLastMouseAngle;
                    baseMatrix     = Matrix4x4.CreateRotationX((float)Math.PI / 2.0f) * RotateMatrixZ;
                    color          = _zAxisColor;
                    break;

                default:
                    throw new NotImplementedException();
                }
                {     // Choose shortest path
                    float shortestAngle = endAngle - startAngle;
                    shortestAngle = (float)(shortestAngle - Math.Round(shortestAngle / (Math.PI * 2)) * (Math.PI * 2));
                    endAngle      = startAngle + shortestAngle;
                }
                if (startAngle > endAngle)
                {
                    float temp = startAngle;
                    startAngle = endAngle;
                    endAngle   = temp;
                }

                // Build rotation geometry
                var   rotationHelperGeometry = new SolidVertex[_rotationTrianglesCount * 3 + 2];
                float angleStep    = (endAngle - startAngle) / _rotationTrianglesCount;
                var   middleVertex = new SolidVertex(new Vector3());
                var   lastVertex   = new SolidVertex(new Vector3((float)Math.Cos(startAngle), 0, (float)-Math.Sin(startAngle)));
                for (int i = 0; i < _rotationTrianglesCount; ++i)
                {
                    float currentAngle  = startAngle + (i + 1) * angleStep;
                    var   currentVertex = new SolidVertex(new Vector3((float)Math.Cos(currentAngle), 0, (float)-Math.Sin(currentAngle)));
                    rotationHelperGeometry[i * 3 + 0] = middleVertex;
                    rotationHelperGeometry[i * 3 + 1] = lastVertex;
                    rotationHelperGeometry[i * 3 + 2] = currentVertex;
                    lastVertex = currentVertex;
                }

                rotationHelperGeometry[_rotationTrianglesCount * 3] = new SolidVertex(new Vector3(
                                                                                          _rotationLastMouseRadius / Size * (float)Math.Cos(lastMouseAngle), 0,
                                                                                          _rotationLastMouseRadius / Size * (float)-Math.Sin(lastMouseAngle)));
                rotationHelperGeometry[_rotationTrianglesCount * 3 + 1] = middleVertex;
                _rotationHelperGeometry.SetData(rotationHelperGeometry);

                // Draw
                _device.SetRasterizerState(_device.RasterizerStates.CullNone);
                _device.SetVertexBuffer(_rotationHelperGeometry);
                _device.SetVertexInputLayout(VertexInputLayout.FromBuffer(0, _rotationHelperGeometry));
                var model = Matrix4x4.CreateScale(Size) * baseMatrix * Matrix4x4.CreateTranslation(Position);
                solidEffect.Parameters["ModelViewProjection"].SetValue((model * viewProjection).ToSharpDX());
                solidEffect.Parameters["Color"].SetValue(color * _rotationAlpha);
                solidEffect.CurrentTechnique.Passes[0].Apply();
                _device.Draw(PrimitiveType.TriangleList, _rotationTrianglesCount * 3);

                solidEffect.Parameters["Color"].SetValue(Vector4.One);
                solidEffect.CurrentTechnique.Passes[0].Apply();
                _device.SetRasterizerState(_rasterizerWireframe);
                _device.Draw(PrimitiveType.LineList, 2, _rotationTrianglesCount * 3);

                // FIXME: Temporary fix for text corruption problem! Remove when SharpDX is not used.
                _device.SetRasterizerState(_device.RasterizerStates.Default);
                break;
            }
        }
Exemple #15
0
 internal PickingResultGizmo(GizmoMode mode, float rotationPickAngle, float rotationPickDistance)
 {
     Mode = mode;
     RotationPickAngle    = rotationPickAngle;
     RotationPickDistance = rotationPickDistance;
 }
Exemple #16
0
 internal PickingResultGizmo(GizmoMode mode)
 {
     Mode = mode;
 }
        public void Draw3D()
        {
            return;

            if (m_IsEnabled == false) { return; }

            m_ActiveMode = GizmoMode.TRANSLATE;
            m_ActiveAxis = GizmoAxis.XY;
            m_ActivePivot = PivotType.OBJECT_CENTER;

            GameFiles.GraphicsDevice.DepthStencilState = DepthStencilState.None;

            m_LineEffect.World = m_GizmoWorld;
            m_LineEffect.View = GameFiles.ViewMatrix;
            m_LineEffect.Projection = GameFiles.ProjectionMatrix;

            m_LineEffect.CurrentTechnique.Passes[0].Apply();
            GameFiles.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, m_TranslationLineVertices, 0, m_TranslationLineVertices.Length / 2);

            if (m_ActiveMode == GizmoMode.TRANSLATE || m_ActiveMode == GizmoMode.NON_LINEAR_SCALE)
            {
                if (m_ActiveAxis == GizmoAxis.XY || m_ActiveAxis == GizmoAxis.YZ || m_ActiveAxis == GizmoAxis.ZX)
                {
                    GameFiles.GraphicsDevice.BlendState = BlendState.AlphaBlend;
                    GameFiles.GraphicsDevice.RasterizerState = RasterizerState.CullNone;

                    m_QuadEffect.World = m_GizmoWorld;
                    m_QuadEffect.View = GameFiles.ViewMatrix;
                    m_QuadEffect.Projection = GameFiles.ProjectionMatrix;

                    m_QuadEffect.CurrentTechnique.Passes[0].Apply();

                    Quad activeQuad = new Quad();
                    switch (m_ActiveAxis)
                    {
                        case GizmoAxis.XY:
                            activeQuad = m_Quads[0];
                            break;
                        case GizmoAxis.ZX:
                            activeQuad = m_Quads[1];
                            break;
                        case GizmoAxis.YZ:
                            activeQuad = m_Quads[2];
                            break;
                    }

                    GameFiles.GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList,
                        activeQuad.Vertices, 0, 4,
                        activeQuad.Indexes, 0, 2);

                    GameFiles.GraphicsDevice.BlendState = BlendState.Opaque;
                    GameFiles.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
                }

                if (m_ActiveMode == GizmoMode.TRANSLATE)
                {
                    for (int loop = 0; loop < 3; loop++)
                    {
                        for (int meshLoop = 0; meshLoop < m_TranslationModel.Meshes.Count; meshLoop++)
                        {
                            ModelMesh tempModelMesh = m_TranslationModel.Meshes[meshLoop];
                            for (int meshPartLoop = 0; meshPartLoop < m_TranslationModel.Meshes.Count; meshPartLoop++)
                            {
                                ModelMeshPart tempModelMeshPart = tempModelMesh.MeshParts[meshPartLoop];

                                BasicEffect effect = (BasicEffect)tempModelMeshPart.Effect;
                                Vector3 color = m_AxisColors[loop].ToVector3();

                                effect.World = m_ModelLocalSpace[loop] * m_GizmoWorld;
                                effect.DiffuseColor = color;
                                effect.EmissiveColor = color;

                                effect.EnableDefaultLighting();

                                effect.View = GameFiles.ViewMatrix;
                                effect.Projection = GameFiles.ProjectionMatrix;
                            }

                            tempModelMesh.Draw();
                        }
                    }
                }
                else
                {
                    for (int loop = 0; loop < 3; loop++)
                    {
                        for (int meshLoop = 0; meshLoop < m_ScaleModel.Meshes.Count; meshLoop++)
                        {
                            ModelMesh tempModelMesh = m_ScaleModel.Meshes[meshLoop];
                            for (int meshPartLoop = 0; meshPartLoop < m_ScaleModel.Meshes.Count; meshPartLoop++)
                            {
                                ModelMeshPart tempModelMeshPart = tempModelMesh.MeshParts[meshPartLoop];

                                BasicEffect effect = (BasicEffect)tempModelMeshPart.Effect;
                                Vector3 color = m_AxisColors[meshPartLoop].ToVector3();

                                effect.World = m_ModelLocalSpace[meshPartLoop] * m_GizmoWorld;
                                effect.DiffuseColor = color;
                                effect.EmissiveColor = color;

                                effect.EnableDefaultLighting();

                                effect.View = GameFiles.ViewMatrix;
                                effect.Projection = GameFiles.ProjectionMatrix;
                            }

                            tempModelMesh.Draw();
                        }
                    }
                }
            }
            else if (m_ActiveMode == GizmoMode.ROTATE)
            {
                for (int loop = 0; loop < 3; loop++)
                {
                    for (int meshLoop = 0; meshLoop < m_RotationModel.Meshes.Count; meshLoop++)
                    {
                        ModelMesh tempModelMesh = m_RotationModel.Meshes[meshLoop];
                        for (int meshPartLoop = 0; meshPartLoop < m_RotationModel.Meshes.Count; meshPartLoop++)
                        {
                            ModelMeshPart tempModelMeshPart = tempModelMesh.MeshParts[meshPartLoop];

                            BasicEffect effect = (BasicEffect)tempModelMeshPart.Effect;
                            Vector3 color = m_AxisColors[meshPartLoop].ToVector3();

                            effect.World = m_ModelLocalSpace[meshPartLoop] * m_GizmoWorld;
                            effect.DiffuseColor = color;
                            effect.EmissiveColor = color;

                            effect.EnableDefaultLighting();

                            effect.View = GameFiles.ViewMatrix;
                            effect.Projection = GameFiles.ProjectionMatrix;
                        }

                        tempModelMesh.Draw();
                    }
                }
            }
            else if (m_ActiveMode == GizmoMode.SCALE)
            {
                for (int loop = 0; loop < 3; loop++)
                {
                    for (int meshLoop = 0; meshLoop < m_RotationModel.Meshes.Count; meshLoop++)
                    {
                        ModelMesh tempModelMesh = m_RotationModel.Meshes[meshLoop];
                        for (int meshPartLoop = 0; meshPartLoop < m_RotationModel.Meshes.Count; meshPartLoop++)
                        {
                            ModelMeshPart tempModelMeshPart = tempModelMesh.MeshParts[meshPartLoop];

                            BasicEffect effect = (BasicEffect)tempModelMeshPart.Effect;
                            Vector3 color = m_AxisColors[meshPartLoop].ToVector3();

                            effect.World = m_ModelLocalSpace[meshPartLoop] * m_GizmoWorld;
                            effect.DiffuseColor = color;
                            effect.EmissiveColor = color;

                            effect.EnableDefaultLighting();

                            effect.View = GameFiles.ViewMatrix;
                            effect.Projection = GameFiles.ProjectionMatrix;
                        }

                        tempModelMesh.Draw();
                    }
                }

                if (m_ActiveAxis != GizmoAxis.NONE)
                {
                    GameFiles.GraphicsDevice.BlendState = BlendState.AlphaBlend;
                    GameFiles.GraphicsDevice.RasterizerState = RasterizerState.CullNone;

                    m_QuadEffect.World = m_GizmoWorld;
                    m_QuadEffect.View = GameFiles.ViewMatrix;
                    m_QuadEffect.Projection = GameFiles.ProjectionMatrix;

                    m_QuadEffect.CurrentTechnique.Passes[0].Apply();

                    for (int loop = 0; loop < m_Quads.Length; loop++)
                    {
                        GameFiles.GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList,
                            m_Quads[loop].Vertices, 0, 4,
                            m_Quads[loop].Indexes, 0, 2);
                    }

                    GameFiles.GraphicsDevice.BlendState = BlendState.Opaque;
                    GameFiles.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
                }
            }

            GameFiles.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        }
        public static void HandleInput(MyGuiInput input)
        {
            // -- Select Gizmo Mode -- //
            if (input.IsEditorControlNewPressed(MyEditorControlEnums.SWITCH_GIZMO_MODE) && !input.IsAnyCtrlKeyPressed())
            {
                SwitchGizmoMode();
            }

            // -- Select Gizmo Mode -- //
            if (input.IsEditorControlNewPressed(MyEditorControlEnums.SWITCH_GIZMO_MODE) && input.IsAnyCtrlKeyPressed() )
            {
                SwitchRotateSnapping();
            }



            // -- Cycle TransformationSpaces -- //
            if (input.IsEditorControlNewPressed(MyEditorControlEnums.SWITCH_GIZMO_SPACE))
            {
                if (ActiveSpace == TransformSpace.LOCAL)
                    ActiveSpace = TransformSpace.WORLD;
                else
                {
                    ActiveSpace = TransformSpace.LOCAL;
                }
            }

            // Below are options, that we can add later, but gizmo is prepared for them
            // however, key mappings will be probably changed
            // -- Cycle PivotTypes -- //
            //if (input.IsNewKeyPress(Keys.P))
            //{
            //    ActivePivot++;
            //}

            // -- Toggle PrecisionMode -- //
            //if (input.IsKeyPress(Keys.K))
            //{
            //    m_precisionMode = true;
            //}
            //else
            //{
            //    m_precisionMode = false;
            //}

            // -- Toggle Snapping -- //
            //if (MyEditor.Static.IsEditingPrefabContainer() == false)
            //{
            if (input.IsNewKeyPress(Keys.G))            
            {
                SnapEnabled = !SnapEnabled;
            }
            //}

            if (Enabled)
            {
                if (input.IsEditorControlNewPressed(MyEditorControlEnums.PRIMARY_ACTION_KEY))
                {
                    // reset for intersection (plane vs. ray)
                    m_translationDelta = Vector3.Zero;
                    m_intersectPosition = Vector3.Zero;
                    // reset for snapping
                    m_translationScaleSnapDelta = Vector3.Zero;
                    m_rotationSnapDelta = 0;
                    m_lastCursorPosition = MyGuiManager.MouseCursorPosition;
                    m_oldCursorPosition = MyGuiManager.MouseCursorPosition;
                    m_gizmoDelta = null;
                    m_gizmoStartPosition = null;
                    m_mouseStartPosition = m_lastCursorPosition;

                    m_startCameraForward = MyCamera.ForwardVector;
                    m_startCameraUp = MyCamera.UpVector;
                    m_startObjectPosition = Position;
                }

                m_lastIntersectionPosition = m_intersectPosition;
                TransformationActive = false;

                if (input.IsEditorControlPressed(MyEditorControlEnums.PRIMARY_ACTION_KEY))
                {
                    if (MyEditor.TransformLocked)
                    {
                        ActiveAxis = LastActiveAxis;
                    }

                    if (ActiveAxis != GizmoAxis.NONE)
                    {

                        //this will help to disable rectangular selection of multiple objects during object transformation with mouse
                        TransformationActive = true;

                        if (ActiveMode == GizmoMode.TRANSLATE)
                        {
                            #region Translate

                            if (HasTransformationStarted())
                            {
                                StartTransformationData();
                            }
                            //if (input.IsAnyShiftKeyPressed() && input.IsNewLeftMousePressed())
                            //{
                            //    MyEditor.Static.CopySelected(false);
                            //}
                            //else if (HasTransformationStarted())
                            //{
                            //    StartTransformationData();
                            //}

                            Vector3 delta = Vector3.Zero;

                            Vector3 worldPosition = Position;

                            if (ActiveAxis == GizmoAxis.XY)
                            {
                                GizmoTranslation(Vector3.Left, Vector3.Up, ref worldPosition);
                            }
                            else if (ActiveAxis == GizmoAxis.YZ)
                            {
                                GizmoTranslation(Vector3.Up, Vector3.Forward, ref worldPosition);
                            }
                            else if (ActiveAxis == GizmoAxis.ZX)
                            {
                                GizmoTranslation(Vector3.Left, Vector3.Forward, ref worldPosition);
                            }
                            else if (ActiveAxis == GizmoAxis.X)
                            {
                                GizmoTranslation(Vector3.Left, null, ref worldPosition);
                            }
                            else if (ActiveAxis == GizmoAxis.Y)
                            {
                                GizmoTranslation(Vector3.Up, null, ref worldPosition);
                            }
                            else if (ActiveAxis == GizmoAxis.Z)
                            {
                                GizmoTranslation(Vector3.Forward, null, ref worldPosition);
                            }

                            // When object is half distance to far, stop it's movement
                            Plane maxMovePlane = MyCamera.GetBoundingFrustum().Far;
                            maxMovePlane.D *= TRANSLATION_MAX_DISTANCE_FROM_CAMERA / MyCamera.FAR_PLANE_DISTANCE;

                            Vector3 moveVector = worldPosition - Position;
                            Ray moveRay = new Ray(Position, -moveVector);

                            float? intersection = moveRay.Intersects(maxMovePlane);

                            Vector3 cam = MyCamera.Position;

                            // Intersection found and moving object towards far clip plane
                            if (intersection.HasValue && Vector3.Dot(MyCamera.ForwardVector, moveVector) > 0 && (worldPosition - cam).Length() > Math.Abs(maxMovePlane.D))
                            {
                                Vector3 intersectionPoint = (moveRay.Position + (moveRay.Direction * intersection.Value));
                                worldPosition = intersectionPoint;
                            }

                            moveVector = worldPosition - Position;

                            // copy selected object only when moved from his original position + LMB + Shift
                            bool copySelected = (moveVector.LengthSquared() >= 0f &&
                                input.IsAnyShiftKeyPressed() &&
                                input.IsNewLeftMousePressed());

                            if (copySelected)
                            {
                                MyEditor.Static.CopySelected(false);
                            }

                            bool applyTranslation = true;

                            PrepareSafeSelectedEntitiesIterationHelper();
                            foreach (var entity in m_safeIterationHelper)
                            {
                                Vector3 newPosition = entity.GetPosition() + moveVector;

                                BoundingSphere sphere = new BoundingSphere(newPosition + entity.LocalVolumeOffset, entity.WorldVolume.Radius);
                                if (!entity.CanMoveAndRotate(newPosition, entity.GetWorldRotation()) || MyMwcSectorConstants.SECTOR_SIZE_FOR_PHYS_OBJECTS_BOUNDING_BOX.Contains(sphere) != MinerWarsMath.ContainmentType.Contains)
                                {
                                    applyTranslation = false;
                                    break;
                                }
                            }

                            if (applyTranslation)
                            {
                                PrepareSafeSelectedEntitiesIterationHelper();

                                List<MyEntity> transformedEntities = new List<MyEntity>();

                                // apply
                                foreach (MyEntity entity in m_safeIterationHelper)
                                {
                                    // skip already transformed linked entities
                                    if (transformedEntities.Contains(entity))
                                    {
                                        continue;
                                    }

                                    Vector3 newPosition = entity.GetPosition() + moveVector;

                                    //snaping after mouse over
                                    /*
                                    // Snap to grid
                                    if (SnapEnabled && ActiveSpace == TransformSpace.WORLD && !MyEditor.Static.IsLinked(entity))
                                    {
                                        SnapToGrid(ref newPosition, TranslationSnapValue);
                                    }
                                    */


                                    MoveAndRotateObject(newPosition, entity.GetWorldRotation(), entity);

                                    MyEditor.Static.FixLinkedEntities(entity, transformedEntities, null);
                                    transformedEntities.Add(entity);
                                }

                                // test if some entities are intersection
                                //CheckCollisions(m_safeIterationHelper); 
                                //MyEditor.Static.CheckAllCollidingObjects();                                
                                MyEditor.Static.HighlightCollisions(m_safeIterationHelper);

                            }

                            #endregion
                        }
                        else if (ActiveMode == GizmoMode.ROTATE)
                        {
                            #region Rotate

                            if (HasTransformationStarted()) StartTransformationData();
                            Vector2 deltaCursorPosition;
                            float delta;
                            if (!MyVideoModeManager.IsHardwareCursorUsed())
                            {
                                Vector2 minMouseCoord = MyGuiManager.GetMinMouseCoord();
                                Vector2 maxMouseCoord = MyGuiManager.GetMaxMouseCoord();

                                Vector2 newCursorPosition = MyGuiManager.MouseCursorPosition;
                                if (MyGuiManager.MouseCursorPosition.X <= minMouseCoord.X) newCursorPosition = new Vector2(maxMouseCoord.X, MyGuiManager.MouseCursorPosition.Y);
                                if (MyGuiManager.MouseCursorPosition.X >= maxMouseCoord.X) newCursorPosition = new Vector2(minMouseCoord.X, MyGuiManager.MouseCursorPosition.Y);
                                if (MyGuiManager.MouseCursorPosition.Y <= minMouseCoord.Y) newCursorPosition = new Vector2(MyGuiManager.MouseCursorPosition.X, maxMouseCoord.Y);
                                if (MyGuiManager.MouseCursorPosition.Y >= maxMouseCoord.Y) newCursorPosition = new Vector2(MyGuiManager.MouseCursorPosition.X, minMouseCoord.Y);
                                MyGuiManager.MouseCursorPosition = newCursorPosition;
                                //KeenSoftwareHouse.Library.Trace.Trace.SendMsgLastCall(MyGuiManager.MouseCursorPosition.ToString() + " " + MyGuiManager.MouseCursorPosition.ToString());

                                float deltaX = MathHelper.ToRadians(input.GetMouseXForGamePlay() - MyMinerGame.ScreenSizeHalf.X);
                                float deltaY = MathHelper.ToRadians(input.GetMouseYForGamePlay() - MyMinerGame.ScreenSizeHalf.Y);

                                deltaX = MathHelper.Clamp(deltaX, -1, 1);
                                deltaY = MathHelper.Clamp(deltaY, -1, 1);

                                delta = deltaY + deltaX;
                                Vector2 cursorDelta = Vector2.Zero;
                                if (MyGuiManager.MouseCursorPosition.Y != 0.0 && MyGuiManager.MouseCursorPosition.Y != 1.0)
                                {
                                    cursorDelta = MyGuiManager.MouseCursorPosition - m_lastCursorPosition;
                                }
                                m_inputScale = MathHelper.Clamp(Math.Abs(cursorDelta.Y) * 100, 0, 1);
                                delta *= m_inputScale;
                                m_oldCursorPosition = MyGuiManager.MouseCursorPosition;

                            }
                            else
                            {

                                Vector2 minMouseCoord = MyGuiManager.GetMinMouseCoord();
                                Vector2 maxMouseCoord = MyGuiManager.GetMaxMouseCoord();
                                Vector2 newCursorPosition = MyGuiManager.MouseCursorPosition;

                                deltaCursorPosition = MyGuiManager.MouseCursorPosition - m_oldCursorPosition;

                                if (MyGuiManager.MouseCursorPosition.X - 0.03f <= minMouseCoord.X)
                                {
                                    deltaCursorPosition = new Vector2(0, 0);
                                    newCursorPosition = new Vector2(maxMouseCoord.X - 0.05f, MyGuiManager.MouseCursorPosition.Y);
                                }
                                if (MyGuiManager.MouseCursorPosition.X + 0.03f >= maxMouseCoord.X * 0.98f)
                                {
                                    deltaCursorPosition = new Vector2(0, 0);
                                    newCursorPosition = new Vector2(minMouseCoord.X + 0.05f, MyGuiManager.MouseCursorPosition.Y);
                                }
                                if (MyGuiManager.MouseCursorPosition.Y - 0.03f <= minMouseCoord.Y)
                                {
                                    deltaCursorPosition = new Vector2(0, 0);
                                    newCursorPosition = new Vector2(MyGuiManager.MouseCursorPosition.X, maxMouseCoord.Y - 0.05f);
                                }
                                if (MyGuiManager.MouseCursorPosition.Y + 0.03f >= maxMouseCoord.Y)
                                {
                                    deltaCursorPosition = new Vector2(0, 0);
                                    newCursorPosition = new Vector2(MyGuiManager.MouseCursorPosition.X, minMouseCoord.Y + 0.05f);
                                }
                                MyGuiManager.MouseCursorPosition = newCursorPosition;

                                delta = (deltaCursorPosition.X + deltaCursorPosition.Y) * 4.0f;
                                delta = MathHelper.Clamp(delta, -2.0f, 2.0f);
                                m_oldCursorPosition = MyGuiManager.MouseCursorPosition;
                            }

                            // Allow snapping of gizmo to make it move depending on the selected grid scale
                            if (ActiveRotateSnapping!=RotateSnapping.NONE)
                            {
                                float snapValue = MathHelper.ToRadians(GetRotateSnapValue());
                                if (m_precisionMode)
                                {
                                    delta *= m_precisionModeScale;
                                    snapValue *= m_precisionModeScale;
                                }

                                m_rotationSnapDelta += delta;

                                float snapped = (int)(m_rotationSnapDelta / snapValue) * snapValue;
                                m_rotationSnapDelta -= snapped;
                                delta = snapped;
                            }
                            else if (m_precisionMode)
                            {
                                delta *= m_precisionModeScale;
                            }

                            // rotation matrix to transform - if more than one objects selected, always use world-space.
                            Matrix rot = Matrix.Identity;
                            rot.Forward = m_sceneWorld.Forward;
                            rot.Up = m_sceneWorld.Up;
                            rot.Right = m_sceneWorld.Right;

                            // Create rotation delta matrix
                            if (ActiveAxis == GizmoAxis.X)
                            {
                                rot *= Matrix.CreateFromAxisAngle(Rotation.Right, delta);
                            }
                            else if (ActiveAxis == GizmoAxis.Y)
                            {
                                rot *= Matrix.CreateFromAxisAngle(Rotation.Up, delta);
                            }
                            else if (ActiveAxis == GizmoAxis.Z)
                            {
                                rot *= Matrix.CreateFromAxisAngle(Rotation.Forward, delta);
                            }

                            // store rotation parameters so that we can calculate the difference in rotation of "before" rotation and "after"
                            CalculateYawPitchRollFromRotationDelta(rot);

                            PrepareSafeSelectedEntitiesIterationHelper();

                            List<MyEntity> transformedEntities = new List<MyEntity>();

                            // -- Apply rotation -- //
                            foreach (MyEntity entity in m_safeIterationHelper)
                            {
                                // skip already transformed linked entities
                                if (transformedEntities.Contains(entity))
                                {
                                    continue;
                                }

                                // VoxelMaps cannot be rotated
                                if (entity is MyVoxelMap == false)
                                {
                                    // use gizmo position for all PivotTypes except for object-center, it should use the entity.position instead.
                                    Vector3 newPosition;
                                    Matrix newRotation;
                                    GetRotationAndPosition(entity, rot, out newPosition, out newRotation);


                                    Matrix normalizedMat = new Matrix();
                                    normalizedMat.Right = Vector3.Normalize(newRotation.Right);
                                    normalizedMat.Forward = Vector3.Normalize(Vector3.Cross(Vector3.Normalize(newRotation.Up), normalizedMat.Right));
                                    normalizedMat.Up = Vector3.Normalize(Vector3.Cross(normalizedMat.Right, normalizedMat.Forward));
                                    normalizedMat.Translation = newRotation.Translation;
                                    normalizedMat.M44 = newRotation.M44;

                                    //KeenSoftwareHouse.Library.Trace.Trace.SendMsgLastCall("{");
                                    //KeenSoftwareHouse.Library.Trace.Trace.SendMsgLastCall(normalizedMat.ToString());
                                    //KeenSoftwareHouse.Library.Trace.Trace.SendMsgLastCall(newRotation.ToString());
                                    //KeenSoftwareHouse.Library.Trace.Trace.SendMsgLastCall("}");

                                    MoveAndRotateObject(newPosition, normalizedMat, entity);

                                    MyEditor.Static.FixLinkedEntities(entity, transformedEntities, null);
                                    transformedEntities.Add(entity);
                                }
                            }

                            SetPosition();
                            Vector3 moveVector = m_startObjectPosition - Position;
                            PrepareSafeSelectedEntitiesIterationHelper();
                            transformedEntities = new List<MyEntity>();
                            // apply
                            foreach (MyEntity entity in m_safeIterationHelper)
                            {
                                // skip already transformed linked entities
                                if (transformedEntities.Contains(entity))
                                {
                                    continue;
                                }

                                Vector3 newPosition = entity.GetPosition() + moveVector;

                                MoveAndRotateObject(newPosition, entity.GetWorldRotation(), entity);

                                MyEditor.Static.FixLinkedEntities(entity, transformedEntities, null);
                                transformedEntities.Add(entity);
                            }

                            #endregion
                        }
                    }
                }
                else
                {
                    PrepareSafeSelectedEntitiesIterationHelper();

                    foreach (MyEntity entity in m_safeIterationHelper)
                    {

                        float moveObjectDistanceInMeters = MyEditorGrid.GetGridStepInMeters();
                        float rotationAngleInRadians = MathHelper.ToRadians(GetRotationDelta());
                        Matrix entityOrientation = entity.GetWorldRotation();

                        bool isVoxelMap = entity is MyVoxelMap;

                        Vector3 entityPosition = entity.GetPosition();

                        #region Translate and Rotate with keyboard

                        Vector3 newPosition = entityPosition;
                        Matrix newRotation = entityOrientation;

                        // Keyboard translation
                        if (IsTransformationKeyPressed(input, Keys.NumPad1))
                        {
                            newPosition = GetTransformInAxis(GizmoAxis.X, entityPosition, Rotation, -moveObjectDistanceInMeters);
                        }
                        if (IsTransformationKeyPressed(input, Keys.NumPad3))
                        {
                            newPosition = GetTransformInAxis(GizmoAxis.X, entityPosition, Rotation, +moveObjectDistanceInMeters);
                        }
                        if (IsTransformationKeyPressed(input, Keys.NumPad2))
                        {
                            newPosition = GetTransformInAxis(GizmoAxis.Z, entityPosition, Rotation, +moveObjectDistanceInMeters);
                        }
                        if (IsTransformationKeyPressed(input, Keys.NumPad5))
                        {
                            newPosition = GetTransformInAxis(GizmoAxis.Z, entityPosition, Rotation, -moveObjectDistanceInMeters);

                        }
                        if (IsTransformationKeyPressed(input, Keys.NumPad9))
                        {
                            newPosition = GetTransformInAxis(GizmoAxis.Y, entityPosition, Rotation, +moveObjectDistanceInMeters);
                        }
                        if (IsTransformationKeyPressed(input, Keys.NumPad6))
                        {
                            newPosition = GetTransformInAxis(GizmoAxis.Y, entityPosition, Rotation, -moveObjectDistanceInMeters);
                        }

                        // Keyboard rotation
                        Matrix oneStepRotationDelta = Matrix.Identity;
                        if (IsTransformationKeyPressed(input, Keys.NumPad7) && !isVoxelMap)
                        {
                            oneStepRotationDelta = Matrix.CreateFromAxisAngle(Rotation.Right, rotationAngleInRadians);
                            GetRotationAndPosition(entity, oneStepRotationDelta, out newPosition, out newRotation);
                        }
                        if (IsTransformationKeyPressed(input, Keys.NumPad4) && !isVoxelMap)
                        {
                            oneStepRotationDelta = Matrix.CreateFromAxisAngle(Rotation.Up, rotationAngleInRadians);
                            GetRotationAndPosition(entity, oneStepRotationDelta, out newPosition, out newRotation);
                        }
                        if (IsTransformationKeyPressed(input, Keys.NumPad8) && !isVoxelMap)
                        {
                            oneStepRotationDelta = Matrix.CreateFromAxisAngle(Rotation.Forward, rotationAngleInRadians);
                            GetRotationAndPosition(entity, oneStepRotationDelta, out newPosition, out newRotation);
                        }

                        if (HasTransformationStarted()) StartTransformationData();

                        // Transform
                        bool translated = newPosition != entityPosition;
                        bool rotated = newRotation != entityOrientation;

                        if (translated || rotated)
                        {
                            if (translated) ActiveMode = GizmoMode.TRANSLATE;
                            if (rotated)
                            {
                                ActiveMode = GizmoMode.ROTATE;
                                if (IsDelayForSmoothMovementReached())
                                {
                                    RotationAmountInDegrees += (int)GetRotationDelta();
                                }
                                else
                                {
                                    RotationAmountInDegrees = (int)GetRotationDelta();
                                }
                            }

                            MoveAndRotateObject(newPosition, newRotation, entity);
                        }
                        #endregion
                    }


                    UpdateAxisSelection(MyGuiManager.GetScreenCoordinateFromNormalizedCoordinate(MyGuiManager.MouseCursorPosition));

                    /*
                    if (GetSnapPoint(true) == null)
                    {
                        
                    }
                    else
                    {
                        ActiveAxis = GizmoAxis.NONE;
                    }
                    */
                }

                if (HasTransformationEnded()) EndTransformationData();

                // previous is used to detect, when is right time to create undo/redo editor action(start of transform, and end of transform)
                TransformationActivePrevious = TransformationActive;
            }
            else
            {
                ActiveAxis = GizmoAxis.NONE;
            }
        }
        public void HandleInput(InputState input)
        {
            // -- Select Gizmo Mode -- //
            if (input.WasKeyPressed(Keys.D1))
            {
                ActiveMode = GizmoMode.Translate;
            }
            else if (input.WasKeyPressed(Keys.D2))
            {
                ActiveMode = GizmoMode.Rotate;
            }
            else if (input.WasKeyPressed(Keys.D3))
            {
                ActiveMode = GizmoMode.NonUniformScale;
            }
            else if (input.WasKeyPressed(Keys.D4))
            {
                ActiveMode = GizmoMode.UniformScale;
            }

            // -- Cycle TransformationSpaces -- //
            if (input.WasKeyPressed(Keys.Space))
            {
                if (ActiveSpace == TransformSpace.Local)
                    ActiveSpace = TransformSpace.World;
                else
                    ActiveSpace = TransformSpace.Local;
            }

            // -- Cycle PivotTypes -- //
            if (input.WasKeyPressed(Keys.P))
            {
                if (ActivePivot == PivotType.WorldOrigin)
                    ActivePivot = PivotType.ObjectCenter;
                else
                    ActivePivot++;
            }

            // -- Toggle PrecisionMode -- //
            if (input.IsKeyDown(Keys.LeftShift))
            {
                precisionMode = true;
            }
            else
                precisionMode = false;

            // -- Toggle Snapping -- //
            if (input.WasKeyPressed(Keys.C))
            {
                SnapEnabled = !SnapEnabled;
            }
            if (input.Mouse.WasButtonPressed(Framework.MouseButtons.Left) && ActiveAxis == GizmoAxis.None)
            {
                // add to selection or clear current selection
                if (input.IsKeyUp(addToSelection) && input.IsKeyUp(removeFromSelection) || input.IsKeyDown(Keys.LeftAlt))
                {
                    Selection.Clear();
                }

                PickObject(input.Mouse.Position, input.IsKeyDown(removeFromSelection));
            }
            else if (input.WasKeyPressed(Keys.R))
            {
                Selection.Clear();
            }

            if (Enabled)
            {
                if (input.Mouse.WasButtonPressed(Framework.MouseButtons.Left))
                {
                    // reset for intersection (plane vs. ray)
                    intersectPosition = Vector3.Zero;
                    // reset for snapping
                    translationScaleSnapDelta = Vector3.Zero;
                    rotationSnapDelta = 0;
                }

                lastIntersectionPosition = intersectPosition;

                if (input.Mouse.WasButtonHeld(Framework.MouseButtons.Left) && ActiveAxis != GizmoAxis.None)
                {
                    if (ActiveMode == GizmoMode.Translate || ActiveMode == GizmoMode.NonUniformScale || ActiveMode == GizmoMode.UniformScale)
                    {
                        #region Translate & Scale
                        Vector3 delta = Vector3.Zero;
                        Ray ray = Engine.ray;

                        Matrix transform = Matrix.Invert(rotationMatrix);
                        ray.Position = Vector3.Transform(ray.Position, transform);
                        ray.Direction = Vector3.TransformNormal(ray.Direction, transform);

                        if (ActiveAxis == GizmoAxis.X || ActiveAxis == GizmoAxis.XY)
                        {
                            Plane plane = new Plane(Vector3.Forward, Vector3.Transform(position,
                                Matrix.Invert(rotationMatrix)).Z);

                            float? intersection = ray.Intersects(plane);
                            if (intersection.HasValue)
                            {
                                intersectPosition = (ray.Position + (ray.Direction *
                                    intersection.Value));
                                if (lastIntersectionPosition != Vector3.Zero)
                                {
                                    translationDelta = intersectPosition -
                                        lastIntersectionPosition;
                                }
                                if (ActiveAxis == GizmoAxis.X)
                                    delta = new Vector3(translationDelta.X, 0, 0);
                                else
                                    delta = new Vector3(translationDelta.X, translationDelta.Y, 0);
                            }
                        }
                        else if (ActiveAxis == GizmoAxis.Y || ActiveAxis == GizmoAxis.YZ || ActiveAxis == GizmoAxis.Z)
                        {
                            Plane plane = new Plane(Vector3.Left, Vector3.Transform(position,
                                Matrix.Invert(rotationMatrix)).X);

                            float? intersection = ray.Intersects(plane);
                            if (intersection.HasValue)
                            {
                                intersectPosition = (ray.Position + (ray.Direction *
                                    intersection.Value));
                                if (lastIntersectionPosition != Vector3.Zero)
                                {
                                    translationDelta = intersectPosition -
                                        lastIntersectionPosition;
                                }
                                if (ActiveAxis == GizmoAxis.Y)
                                    delta = new Vector3(0, translationDelta.Y, 0);
                                else if (ActiveAxis == GizmoAxis.Z)
                                    delta = new Vector3(0, 0, translationDelta.Z);
                                else
                                    delta = new Vector3(0, translationDelta.Y, translationDelta.Z);
                            }
                        }
                        else if (ActiveAxis == GizmoAxis.ZX)
                        {
                            Plane plane = new Plane(Vector3.Down, Vector3.Transform(position,
                                Matrix.Invert(rotationMatrix)).Y);

                            float? intersection = ray.Intersects(plane);
                            if (intersection.HasValue)
                            {
                                intersectPosition = (ray.Position + (ray.Direction *
                                    intersection.Value));
                                if (lastIntersectionPosition != Vector3.Zero)
                                {
                                    translationDelta = intersectPosition -
                                        lastIntersectionPosition;
                                }
                            }

                            delta = new Vector3(translationDelta.X, 0, translationDelta.Z);
                        }

                        if (SnapEnabled)
                        {
                            float snapValue = TranslationSnapValue;
                            if (ActiveMode == GizmoMode.UniformScale || ActiveMode == GizmoMode.NonUniformScale)
                                snapValue = ScaleSnapValue;
                            if (precisionMode)
                            {
                                delta *= precisionModeScale;
                                snapValue *= precisionModeScale;
                            }

                            translationScaleSnapDelta += delta;

                            delta = new Vector3(
                                (int)(translationScaleSnapDelta.X / snapValue) * snapValue,
                                (int)(translationScaleSnapDelta.Y / snapValue) * snapValue,
                                (int)(translationScaleSnapDelta.Z / snapValue) * snapValue);

                            translationScaleSnapDelta -= delta;
                        }
                        else if (precisionMode)
                            delta *= precisionModeScale;

                        if (ActiveMode == GizmoMode.Translate)
                        {
                            // transform (local or world)
                            delta = Vector3.Transform(delta, rotationMatrix);

                            // apply
                            foreach (Framework.SceneEntity entity in Selection)
                            {
                                entity.position += delta;
                            }

                        }
                        else if (ActiveMode == GizmoMode.NonUniformScale)
                        {
                            // -- Apply Scale -- //
                            foreach (Framework.SceneEntity entity in Selection)
                            {
                                entity.scale += delta;
                                entity.scale = Vector3.Clamp(entity.scale, Vector3.Zero,
                                    entity.scale);
                            }
                        }
                        else if (ActiveMode == GizmoMode.UniformScale)
                        {

                            float diff = 1 + ((delta.X + delta.Y + delta.Z) / 3);
                            foreach (Framework.SceneEntity entity in Selection)
                            {
                                entity.scale *= diff;

                                entity.scale = Vector3.Clamp(entity.scale, Vector3.Zero,
                                    entity.scale);
                            }
                        }
                        #endregion
                    }
                    else if (ActiveMode == GizmoMode.Rotate)
                    {
                        #region Rotate
                        float delta = input.Mouse.Delta.X;
                        delta *= inputScale;

                        if (SnapEnabled)
                        {
                            float snapValue = MathHelper.ToRadians(RotationSnapValue);
                            if (precisionMode)
                            {
                                delta *= precisionModeScale;
                                snapValue *= precisionModeScale;
                            }

                            rotationSnapDelta += delta;

                            float snapped = (int)(rotationSnapDelta / snapValue) * snapValue;
                            rotationSnapDelta -= snapped;

                            delta = snapped;
                        }
                        else if (precisionMode)
                        {
                            delta *= precisionModeScale;
                        }

                        // rotation matrix to transform - if more than one objects selected, always use world-space.
                        Matrix rot = Matrix.Identity;
                        rot.Forward = sceneWorld.Forward;
                        rot.Up = sceneWorld.Up;
                        rot.Right = sceneWorld.Right;

                        if (ActiveAxis == GizmoAxis.X)
                        {
                            rot *= Matrix.CreateFromAxisAngle(rotationMatrix.Right, delta);
                        }
                        else if (ActiveAxis == GizmoAxis.Y)
                        {
                            rot *= Matrix.CreateFromAxisAngle(rotationMatrix.Up, delta);
                        }
                        else if (ActiveAxis == GizmoAxis.Z)
                        {
                            rot *= Matrix.CreateFromAxisAngle(rotationMatrix.Forward, delta);
                        }

                        // -- Apply rotation -- //
                        foreach (Framework.SceneEntity entity in Selection)
                        {
                            // use gizmo position for all PivotTypes except for object-center, it should use the entity.position instead.
                            Vector3 pos = position;
                            if (ActivePivot == PivotType.ObjectCenter)
                            {
                                pos = entity.position;
                            }

                            Matrix localRot = Matrix.Identity;
                            localRot.Forward = entity.forward;
                            localRot.Up = entity.up;
                            localRot.Right = Vector3.Cross(entity.forward, entity.up);
                            localRight.Normalize();
                            localRot.Translation = entity.position - pos;

                            Matrix newRot = localRot * rot;

                            entity.forward = newRot.Forward;
                            entity.up = newRot.Up;
                            entity.position = newRot.Translation + pos;

                        }
                        #endregion
                    }
                }
                else
                {
                    UpdateAxisSelection(input.Mouse.Position);
                }
            }

            // Enable only if something is selected.
            if (Selection.Count < 1)
                Enabled = false;
            else
                Enabled = true;
        }
Exemple #20
0
 public void SetGizmoMode(GizmoMode gizmoMode)
 {
     _gizmoMode = gizmoMode;
 }
 public void RotateMode()
 {
     m_ActiveMode = GizmoMode.ROTATE;
 }
 public void NonLinearScaleMode()
 {
     m_ActiveMode = GizmoMode.NON_LINEAR_SCALE;
 }
 private void HandleGizmoMode()
 {
     if (Event.current.control)
     {
         this.m_GizmoMode = GizmoMode.BorderEditing;
     }
     else
     {
         this.m_GizmoMode = GizmoMode.RectEditing;
     }
     Event current = Event.current;
     if (((current.type == EventType.KeyDown) || (current.type == EventType.KeyUp)) && (((current.keyCode == KeyCode.LeftControl) || (current.keyCode == KeyCode.RightControl)) || ((current.keyCode == KeyCode.LeftAlt) || (current.keyCode == KeyCode.RightAlt))))
     {
         base.Repaint();
     }
 }
 public void SetGizmoMode(GizmoMode mode)
 {
     _gizmo.ActiveMode = mode;
     _isEnabled        = true;
 }
 public void ScaleMode()
 {
     m_ActiveMode = GizmoMode.SCALE;
 }
 internal void setActiveMode(GizmoMode inGizmoMode)
 {
     ActiveMode = inGizmoMode;
 }
 public void TranslateMode()
 {
     m_ActiveMode = GizmoMode.TRANSLATE;
 }
 /// <summary>
 /// Switch gizmo mode
 /// </summary>
 public static void SwitchGizmoMode()
 {
     if (ActiveMode == GizmoMode.TRANSLATE)
     {
         if (IsAnyVoxelMapSelected() == false)
         {
             ActiveMode = GizmoMode.ROTATE;
         }
         else
         {
             ActiveMode = GizmoMode.TRANSLATE;
         }
     }
     else
     {
         ActiveMode = GizmoMode.TRANSLATE;
     }
 }