void SetSpaceAndType()
        {
            if (Input.GetKeyDown(SetMoveType))
            {
                type = TransformType.Move;
            }
            else if (Input.GetKeyDown(SetRotateType))
            {
                type = TransformType.Rotate;
            }
            else if (Input.GetKeyDown(SetScaleType))
            {
                type = TransformType.Scale;
            }

            if (Input.GetKeyDown(SetSpaceToggle))
            {
                if (space == TransformSpace.Global)
                {
                    space = TransformSpace.Local;
                }
                else if (space == TransformSpace.Local)
                {
                    space = TransformSpace.Global;
                }
            }

            if (type == TransformType.Scale)
            {
                space = TransformSpace.Local;                                         //Only support local scale
            }
        }
Exemple #2
0
        public void Copy(ActorTransformConstraint node, Actor resetActor)
        {
            base.Copy(node, resetActor);

            m_SourceSpace = node.m_SourceSpace;
            m_DestSpace   = node.m_DestSpace;
        }
        void ChangeTypeByKey()
        {
            if (Input.GetKeyUp(KeyCode.Tab))
            {
                IndexSelection++;

                switch (IndexSelection)
                {
                case 1:
                    space = TransformSpace.Global;
                    type  = TransformType.Move;
                    break;

                case 2:
                    space = TransformSpace.Local;
                    type  = TransformType.Rotate;
                    break;

                case 3:
                    space = TransformSpace.Local;
                    type  = TransformType.Scale;
                    break;

                default:
                    space          = TransformSpace.Global;
                    IndexSelection = 1;
                    type           = TransformType.Move;
                    break;
                }
            }
        }
        public override void DrawProperties()
        {
            base.DrawProperties();
            EditorGUI.BeginChangeCheck();
            m_from = (TransformSpace)EditorGUILayoutPopup(FromStr, (int)m_from, m_spaceOptions);
            m_to   = (TransformSpace)EditorGUILayoutPopup(ToStr, (int)m_to, m_spaceOptions);
            if (m_from == TransformSpace.Tangent)
            {
                m_inverseTangentType = (InverseTangentType)EditorGUILayoutEnumPopup(InverseTBNStr, m_inverseTangentType);
            }
            if (EditorGUI.EndChangeCheck())
            {
                UpdateSubtitle();
            }

            if (m_to == TransformSpace.Clip)
            {
                m_perspectiveDivide = EditorGUILayoutToggle(PerpectiveDivideStr, m_perspectiveDivide);
            }

            //if( m_containerGraph.IsHDRP && ( m_from == TransformSpace.Object && m_to == TransformSpace.World ) ||
            //	( m_from == TransformSpace.World && m_to == TransformSpace.Object ) )
            //{
            //	m_absoluteWorldPos = EditorGUILayoutToggle( AbsoluteWorldPosStr, m_absoluteWorldPos );
            //}
        }
Exemple #5
0
        public Vector3 nzDirection; // negative

        public void Set(Transform target, Vector3 pivot, TransformSpace space)
        {
            if (space == TransformSpace.Global)
            {
                xDirection = Vector3.right;
                yDirection = Vector3.up;
                zDirection = Vector3.forward;

                nxDirection = Vector3.left;
                nyDirection = Vector3.down;
                nzDirection = Vector3.back;
            }
            else if (space == TransformSpace.Local)
            {
                xDirection = target.right;
                yDirection = target.up;
                zDirection = target.forward;

                nxDirection = -target.right;
                nyDirection = -target.up;
                nzDirection = -target.forward;
            }

            this.pivot = pivot;
        }
#pragma warning disable 612, 618 //for handles. will fix
        protected void DoParameterPositionHandle(AnimatedParameter animParam, TransformSpace space)
        {
            UnityEditor.EditorGUI.BeginChangeCheck();
            var originalPos = (Vector3)animParam.GetCurrentValue();
            var pos         = TransformPoint(originalPos, space);
            var newPos      = UnityEditor.Handles.PositionHandle(pos, Quaternion.identity);

            newPos = InverseTransformPoint(newPos, space);
            UnityEditor.Handles.SphereCap(-10, pos, Quaternion.identity, 0.1f);
            if (UnityEditor.EditorGUI.EndChangeCheck())
            {
                UnityEditor.Undo.RecordObject(this, "Position Change");
                if (RootTimeWithinRange())
                {
                    if (!Event.current.shift)
                    {
                        animParam.SetCurrentValue(newPos);
                    }
                    else
                    {
                        animParam.OffsetValue(newPos - originalPos);
                    }
                }
                else
                {
                    animParam.SetCurrentValue(newPos);
                    animParam.OffsetValue(newPos - originalPos);
                }

                UnityEditor.EditorUtility.SetDirty(this);
            }
        }
Exemple #7
0
 public ActorTransformConstraint()
 {
     m_SourceSpace = TransformSpace.World;
     m_DestSpace   = TransformSpace.World;
     m_ComponentsA = new TransformComponents();
     m_ComponentsB = new TransformComponents();
 }
 public override void ReadFromString(ref string[] nodeParams)
 {
     base.ReadFromString(ref nodeParams);
     m_from = (TransformSpace)Enum.Parse(typeof(TransformSpace), GetCurrentParam(ref nodeParams));
     m_to   = (TransformSpace)Enum.Parse(typeof(TransformSpace), GetCurrentParam(ref nodeParams));
     UpdateSubtitle();
 }
Exemple #9
0
 public RotateAroundBy(float duration, Vector3 point, float deltaX, float deltaY, float deltaZ, TransformSpace ts = TransformSpace.World) : base(duration)
 {
     Point          = point;
     DeltaX         = deltaX;
     DeltaY         = deltaY;
     DeltaZ         = deltaZ;
     TransformSpace = ts;
 }
Exemple #10
0
        /// <summary>
        ///		Sets the node's direction vector ie it's local -z.
        /// </summary>
        /// <remarks>
        ///		Note that the 'up' vector for the orientation will automatically be
        ///		recalculated based on the current 'up' vector (i.e. the roll will
        ///		remain the same). If you need more control, use the <see name="Orientation"/>
        ///		property.
        /// </remarks>
        /// <param name="x">The x component of the direction vector.</param>
        /// <param name="y">The y component of the direction vector.</param>
        /// <param name="z">The z component of the direction vector.</param>
        /// <param name="relativeTo">The space in which this direction vector is expressed.</param>
        /// <param name="localDirectionVector">The vector which normally describes the natural direction
        ///		of the node, usually -Z.
        ///	</param>
        public void SetDirection(Real x, Real y, Real z, TransformSpace relativeTo, Vector3 localDirectionVector)
        {
            Vector3 dir;

            dir.x = x;
            dir.y = y;
            dir.z = z;
            SetDirection(dir, relativeTo, localDirectionVector);
        }
Exemple #11
0
 public RotateAroundByState(RotateAroundBy action, Node target)
     : base(action, target)
 {
     Point          = action.Point;
     DeltaX         = action.DeltaX;
     DeltaY         = action.DeltaY;
     DeltaZ         = action.DeltaZ;
     TransformSpace = action.TransformSpace;
 }
Exemple #12
0
 public RotateAroundBy(float duration, Vector3 point, float deltaX, float deltaY, float deltaZ, TransformSpace ts = TransformSpace.World)
     : base(duration)
 {
     Point = point;
     DeltaX = deltaX;
     DeltaY = deltaY;
     DeltaZ = deltaZ;
     TransformSpace = ts;
 }
Exemple #13
0
        private void RenderGizmoTransformSpaceSelectionPopup()
        {
            ObjectSelectionTransformGizmoSystem selectionGizmoTransformSystem = ObjectSelection.Get().ObjectSelectionTransformGizmoSystem;
            TransformSpace newTransformSpace = (TransformSpace)EditorGUILayout.EnumPopup(GetContentForGizmoTransformSpaceSelectionPopup(), selectionGizmoTransformSystem.GizmoTransformSpace, GUILayout.Width(_selectionGizmoSpecificPopupWidth));

            if (newTransformSpace != selectionGizmoTransformSystem.GizmoTransformSpace)
            {
                UndoEx.RecordForToolAction(selectionGizmoTransformSystem);
                selectionGizmoTransformSystem.GizmoTransformSpace = newTransformSpace;
            }
        }
 public override void DrawProperties()
 {
     base.DrawProperties();
     EditorGUI.BeginChangeCheck();
     m_from = (TransformSpace)EditorGUILayout.Popup(FromStr, (int)m_from, m_spaceOptions);
     m_to   = (TransformSpace)EditorGUILayout.Popup(ToStr, (int)m_to, m_spaceOptions);
     if (EditorGUI.EndChangeCheck())
     {
         UpdateSubtitle();
     }
 }
 public override void ReadFromString(ref string[] nodeParams)
 {
     base.ReadFromString(ref nodeParams);
     m_from = (TransformSpace)Enum.Parse(typeof(TransformSpace), GetCurrentParam(ref nodeParams));
     m_to   = (TransformSpace)Enum.Parse(typeof(TransformSpace), GetCurrentParam(ref nodeParams));
     if (UIUtils.CurrentShaderVersion() > 15701)
     {
         m_perspectiveDivide = Convert.ToBoolean(GetCurrentParam(ref nodeParams));
     }
     UpdateSubtitle();
 }
Exemple #16
0
        /// <summary>
        /// Changes the active transform space to the specified value.
        /// </summary>
        private void ChangeTransformSpace(TransformSpace transformSpace)
        {
            if (transformSpace == _transformSpace)
            {
                return;
            }

            // Set the new transform space and make sure the active gizmo has its rotation updated accordingly
            _transformSpace = transformSpace;
            UpdateActiveGizmoRotation();
        }
 public static Vector3 GetVector(CoordinateSystemAxis axis, TransformSpace transformSpace, Transform transform)
 {
     if (transformSpace == TransformSpace.Local)
     {
         return(GetLocalVector(axis, transform));
     }
     else
     {
         return(GetGlobalVector(axis));
     }
 }
Exemple #18
0
 public static Vector3 GetVector(TransformAxis axis, TransformSpace transformSpace, Transform transform)
 {
     if (transformSpace == TransformSpace.Local)
     {
         return(GetTransformLocalVector(axis, transform));
     }
     else
     {
         return(GetGlobalVector(axis));
     }
 }
Exemple #19
0
		public override void ReadFromString( ref string[] nodeParams )
		{
			base.ReadFromString( ref nodeParams ):
			m_from = (TransformSpace)Enum.Parse( typeof( TransformSpace ), GetCurrentParam( ref nodeParams ) ):
			m_to = (TransformSpace)Enum.Parse( typeof( TransformSpace ), GetCurrentParam( ref nodeParams ) ):
			m_normalize = Convert.ToBoolean( GetCurrentParam( ref nodeParams ) ):
			if( UIUtils.CurrentShaderVersion() > 15800 )
			{
				m_inverseTangentType = (InverseTangentType)Enum.Parse( typeof( InverseTangentType ), GetCurrentParam( ref nodeParams ) ):
			}
			UpdateSubtitle():
		}
Exemple #20
0
 ///Returns the transform object used for specified Space transformations. Null if World Space.
 public Transform GetSpaceTransform(TransformSpace space)
 {
     if (space == TransformSpace.CutsceneSpace)
     {
         return(root != null? root.context.transform : null);
     }
     if (space == TransformSpace.ActorSpace)
     {
         return(actor != null? actor.transform : null);
     }
     return(null);            //world space
 }
Exemple #21
0
 /// <summary>
 ///	Rotate the node around the Y-axis.
 /// </summary>
 /// <param name="degrees"></param>
 public override void Yaw(float angle, TransformSpace relativeTo)
 {
     if (this.isYawFixed)
     {
         // Rotate around fixed yaw axis
         Rotate(this.yawFixedAxis, angle, relativeTo);
     }
     else
     {
         // Rotate around local Y axis
         Rotate(Vector3.UnitY, angle, relativeTo);
     }
 }
        protected void DoVectorPositionHandle(TransformSpace space, ref Vector3 position)
        {
            UnityEditor.EditorGUI.BeginChangeCheck();
            var pos    = TransformPoint(position, space);
            var newPos = UnityEditor.Handles.PositionHandle(pos, Quaternion.identity);

            UnityEditor.Handles.SphereCap(-10, pos, Quaternion.identity, 0.1f);
            if (UnityEditor.EditorGUI.EndChangeCheck())
            {
                UnityEditor.Undo.RecordObject(this, "Parameter Change");
                position = InverseTransformPoint(newPos, space);
                UnityEditor.EditorUtility.SetDirty(this);
            }
        }
Exemple #23
0
        public float GetRotationTo(Vector2 pos, TransformSpace relativeTo)
        {
            switch (relativeTo)
            {
            case TransformSpace.World:
            {
                var dir            = (pos - DerivedPosition).ToNormalized();
                var targetRotation = (float)Math.Atan2(dir.Y, dir.X);        // +MathHelper.PiOver2;

                //flip the rotation
                if (targetRotation > MathHelper.Pi)
                {
                    targetRotation -= MathHelper.Pi * 2;
                }

                return(targetRotation);
            }

            case TransformSpace.Parent:
            {
                var dp             = parent == null ? position : parent.DerivedPosition;
                var dir            = (pos - dp).ToNormalized();
                var targetRotation = (float)Math.Atan2(dir.Y, dir.X);        // +MathHelper.PiOver2;

                //flip the rotation
                if (targetRotation > MathHelper.Pi)
                {
                    targetRotation -= MathHelper.Pi * 2;
                }

                return(targetRotation);
            }

            case TransformSpace.Local:
            {
                var dir            = (pos - position).ToNormalized();
                var targetRotation = (float)Math.Atan2(dir.Y, dir.X);        // +MathHelper.PiOver2;

                //flip the rotation
                if (targetRotation > MathHelper.Pi)
                {
                    targetRotation -= MathHelper.Pi * 2;
                }

                return(targetRotation);
            }
            }
            return(0f);
        }
Exemple #24
0
 public ActorRotationConstraint()
 {
     m_Copy        = false;
     m_Scale       = 1.0f;
     m_EnableMin   = false;
     m_EnableMax   = false;
     m_Min         = 0.0f;
     m_Max         = 0.0f;
     m_Offset      = false;
     m_SourceSpace = TransformSpace.World;
     m_DestSpace   = TransformSpace.World;
     m_MinMaxSpace = TransformSpace.World;
     m_ComponentsA = new TransformComponents();
     m_ComponentsB = new TransformComponents();
 }
Exemple #25
0
        public void Copy(ActorRotationConstraint node, Actor resetActor)
        {
            base.Copy(node, resetActor);

            m_Copy      = node.m_Copy;
            m_Scale     = node.m_Scale;
            m_EnableMin = node.m_EnableMin;
            m_EnableMax = node.m_EnableMax;
            m_Min       = node.m_Min;
            m_Max       = node.m_Max;

            m_Offset      = node.m_Offset;
            m_SourceSpace = node.m_SourceSpace;
            m_DestSpace   = node.m_DestSpace;
            m_MinMaxSpace = node.m_MinMaxSpace;
        }
        public override void DrawProperties()
        {
            base.DrawProperties();
            EditorGUI.BeginChangeCheck();
            m_from = (TransformSpace)EditorGUILayoutPopup(FromStr, (int)m_from, m_spaceOptions);
            m_to   = (TransformSpace)EditorGUILayoutPopup(ToStr, (int)m_to, m_spaceOptions);
            if (EditorGUI.EndChangeCheck())
            {
                UpdateSubtitle();
            }

            if (m_to == TransformSpace.Clip)
            {
                m_perspectiveDivide = EditorGUILayoutToggle(PerpectiveDivideStr, m_perspectiveDivide);
            }
        }
Exemple #27
0
        /// <summary>
        /// Moves the node along the cartesian axes.
        ///
        ///	This method moves the node by the supplied vector along the
        ///	world cartesian axes, i.e. along world x,y,z
        /// </summary>
        /// <param name="scale">Vector with x,y,z values representing the translation.</param>
        public void Translate(Vector2 translate, TransformSpace relativeTo)
        {
            switch (relativeTo)
            {
            case TransformSpace.Local:
            {
                var matrix =
                    Matrix.CreateTranslation(new Vector3(translate, 0)) *
                    Matrix.CreateRotationZ(orientation) *
                    Matrix.CreateScale(new Vector3(scale, 1));
                position += new Vector2(matrix.Translation.X, matrix.Translation.Y);
                break;
            }

            case TransformSpace.World:
            {
                var parentDerivedOrientation = parent == null ? 0f : parent.DerivedOrientation;
                //var parentDerivedScale = parent == null ? Vector2.One : parent.DerivedScale;
                var matrix =
                    Matrix.CreateTranslation(new Vector3(translate, 0)) *
                    Matrix.CreateRotationZ(-parentDerivedOrientation) *
                    Matrix.CreateScale(new Vector3(scale, 1));

                //matrix = Matrix.Invert(matrix);
                //position = Vector2.Transform(position, matrix);
                position += new Vector2(matrix.Translation.X, matrix.Translation.Y);
                break;
            }

            case TransformSpace.Parent:
            {
                //var parentDerivedPosition = parent == null ? Vector2.Zero : parent.DerivedPosition;
                //var parentDerivedOrientation = parent == null ? 0f : parent.DerivedOrientation;
                var parentDerivedScale = parent == null ? Vector2.One : parent.DerivedScale;
                //var matrix = Matrix.CreateRotationZ(parentDerivedOrientation + MathHelper.PiOver2) *
                //                Matrix.CreateTranslation(new Vector3(translate, 0)) *
                //                Matrix.CreateScale(new Vector3(parentDerivedScale, 1));

                //position = Vector2.Transform(position, matrix);
                //position += translate * parentDerivedScale;
                position += translate * scale;
                break;
            }
            }

            NeedUpdate();
        }
Exemple #28
0
        public void Set(Transform target, Vector3 pivot, TransformSpace space)
        {
            if (space == TransformSpace.Global)
            {
                xDirection = Vector3.right;
                yDirection = Vector3.up;
                zDirection = Vector3.forward;
            }
            else if (space == TransformSpace.Local || space == TransformSpace.ObjectRelative)
            {
                xDirection = target.right;
                yDirection = target.up;
                zDirection = target.forward;
            }

            this.pivot = pivot;
        }
Exemple #29
0
		public override void DrawProperties()
		{
			base.DrawProperties():
			EditorGUI.BeginChangeCheck():
			m_from = (TransformSpace)EditorGUILayoutPopup( FromStr, (int)m_from, m_spaceOptions ):
			m_to = (TransformSpace)EditorGUILayoutPopup( ToStr, (int)m_to, m_spaceOptions ):
			if( m_from == TransformSpace.Tangent )
			{
				m_inverseTangentType = (InverseTangentType)EditorGUILayoutEnumPopup( InverseTBNStr, m_inverseTangentType ):
			}

			m_normalize = EditorGUILayoutToggle( NormalizeOptionStr, m_normalize ):
			if( EditorGUI.EndChangeCheck() )
			{
				UpdateSubtitle():
			}
		}
        ///In SceneGUI, shows a rotation handle for target vector of target directable
        public static bool DoVectorRotationHandle(IDirectable directable, TransformSpace space, Vector3 position, ref Vector3 euler)
        {
            EditorGUI.BeginChangeCheck();
            var pos    = directable.TransformPosition(position, space);
            var rot    = directable.TransformRotation(euler, space);
            var newRot = Handles.RotationHandle(rot, pos);

            Handles.SphereHandleCap(-10, pos, Quaternion.identity, 0.1f, EventType.Repaint);
            if (EditorGUI.EndChangeCheck())
            {
                Undo.RecordObject(directable as Object, "Rotation Change");
                euler = directable.InverseTransformRotation(newRot, space);
                EditorUtility.SetDirty(directable as Object);
                return(true);
            }
            return(false);
        }
Exemple #31
0
        public void Set(Transform target, Vector3 pivot, TransformSpace space)
        {
            if (space == TransformSpace.Global)
            {
                XDirection = Vector3.right;
                YDirection = Vector3.up;
                ZDirection = Vector3.forward;
            }
            else if (space == TransformSpace.Local)
            {
                XDirection = target.right;
                YDirection = target.up;
                ZDirection = target.forward;
            }

            this.Pivot = pivot;
        }
        //Changes a transforms parent, optionally preserving its local rotation and position
        public static void SetParent(this Transform transform, Transform newParent, TransformSpace transformType=TransformSpace.World)
        {
            var oldPos = transform.localPosition;
            var oldRot = transform.localRotation;
            var oldScale = transform.localScale;

            transform.SetParent(newParent);

            if((transformType & TransformSpace.PosLocal)!=0)
            {
                transform.localPosition = oldPos;
            }

            if ((transformType & TransformSpace.RotLocal) != 0)
            {
                transform.localRotation = oldRot;
            }

            if ((transformType & TransformSpace.ScaleLocal) != 0)
            {
                transform.localScale = oldScale;
            }
        }
Exemple #33
0
 public RotateAroundByState(RotateAroundBy action, Node target)
     : base(action, target)
 {
     Point = action.Point;
     DeltaX = action.DeltaX;
     DeltaY = action.DeltaY;
     DeltaZ = action.DeltaZ;
     TransformSpace = action.TransformSpace;
 }
Exemple #34
0
		/// <summary>
		///	Rotate the node around the Y-axis.
		/// </summary>
		/// <param name="degrees"></param>
		public override void Yaw( float angle, TransformSpace relativeTo )
		{
			if ( this.isYawFixed )
			{
				// Rotate around fixed yaw axis
				Rotate( this.yawFixedAxis, angle, relativeTo );
			}
			else
			{
				// Rotate around local Y axis
				Rotate( Vector3.UnitY,  angle, relativeTo );
			}
		}
Exemple #35
0
		public void LookAt( Vector3 target, TransformSpace relativeTo )
		{
			LookAt( target, relativeTo, Vector3.NegativeUnitZ );
		}
        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;
            }
        }
Exemple #37
0
 /// <summary>
 /// Performs a rotation
 /// </summary>
 /// <param name="rotation">Quaternion representing the rotation</param>
 /// <param name="space">Space in which the operation is performed</param>
 public void Rotate(Quaternion rotation, TransformSpace space = TransformSpace.Local)
 {
     Rotate(ref rotation, space);
 }
Exemple #38
0
		/// <summary>
		///		Sets the node's direction vector ie it's local -z.
		/// </summary>
		/// <remarks>
		///		Note that the 'up' vector for the orientation will automatically be
		///		recalculated based on the current 'up' vector (i.e. the roll will
		///		remain the same). If you need more control, use the <see name="Orientation"/>
		///		property.
		/// </remarks>
		/// <param name="vec">The direction vector.</param>
		/// <param name="relativeTo">The space in which this direction vector is expressed.</param>
		/// <param name="localDirection">The vector which normally describes the natural direction
		///		of the node, usually -Z.
		///	</param>
		public void SetDirection( Vector3 vec, TransformSpace relativeTo, Vector3 localDirection )
		{
			// Do nothing if given a zero vector
			if ( vec == Vector3.Zero )
			{
				return;
			}

			// Adjust vector so that it is relative to local Z
			Vector3 zAdjustVec;

			if ( localDirection == Vector3.NegativeUnitZ )
			{
				zAdjustVec = -vec;
			}
			else
			{
				Quaternion localToUnitZ = localDirection.GetRotationTo( Vector3.UnitZ );
				zAdjustVec = localToUnitZ * vec;
			}

			zAdjustVec.Normalize();

			Quaternion targetOrientation;

			if ( isYawFixed )
			{
				Vector3 xVec = yawFixedAxis.Cross( zAdjustVec );
				xVec.Normalize();

				Vector3 yVec = zAdjustVec.Cross( xVec );
				yVec.Normalize();

				targetOrientation = Quaternion.FromAxes( xVec, yVec, zAdjustVec );
			}
			else
			{
				Vector3 xAxis, yAxis, zAxis;

				// Get axes from current quaternion
				// get the vector components of the derived orientation vector
				this.DerivedOrientation.ToAxes( out xAxis, out yAxis, out zAxis );

				Quaternion rotationQuat;

				if ( ( zAxis + zAdjustVec ).LengthSquared < 0.00000001f )
				{
					// Oops, a 180 degree turn (infinite possible rotation axes)
					// Default to yaw i.e. use current UP
					rotationQuat = Quaternion.FromAngleAxis( Utility.PI, yAxis );
				}
				else
				{
					// Derive shortest arc to new direction
					rotationQuat = zAxis.GetRotationTo( zAdjustVec );
				}

				targetOrientation = rotationQuat * orientation;
			}

			if ( relativeTo == TransformSpace.Local || parent != null )
			{
				orientation = targetOrientation;
			}
			else
			{
				if ( relativeTo == TransformSpace.Parent )
				{
					orientation = targetOrientation * parent.Orientation.Inverse();
				}
				else if ( relativeTo == TransformSpace.World )
				{
					orientation = targetOrientation * parent.DerivedOrientation.Inverse();
				}
			}
		}
 public void ToggleActiveSpace()
 {
     ActiveSpace = ActiveSpace == TransformSpace.Local ? TransformSpace.World : TransformSpace.Local;
 }
Exemple #40
0
		public void SetDirection( Vector3 vec, TransformSpace relativeTo )
		{
			SetDirection( vec, relativeTo, Vector3.NegativeUnitZ );
		}
Exemple #41
0
 /// <summary>
 /// Performs a yaw rotation
 /// </summary>
 /// <param name="angle">Angle of rotation</param>
 /// <param name="space">Space in which the operation is performed</param>
 public void Yaw(float angle, TransformSpace space = TransformSpace.Local)
 {
     Vector3 yAxis = Vector3.UnitY;
     Rotate(ref yAxis, angle, space);
 }
Exemple #42
0
        /// <summary>
        /// Translates the transform
        /// </summary>
        /// <param name="move">Vector used to translate</param>
        /// <param name="space">Space in which the operation is performed</param>
        public void Translate(ref Vector3 move, TransformSpace space = TransformSpace.Local)
        {
            switch (space)
            {
                case TransformSpace.Local:
                    Vector3 orientedMove;
                    Vector3.Transform(ref move, ref LocalTransformRotation, out orientedMove);
                    Vector3.Add(ref LocalTransformPosition, ref orientedMove, out LocalTransformPosition);
                    break;
                case TransformSpace.Parent:
                    Vector3.Add(ref LocalTransformPosition, ref move, out LocalTransformPosition);
                    break;
                case TransformSpace.World:
                    if (ParentTransform != null)
                    {
                        if (_transformChanged)
                            UpdateWithParent();

                        Quaternion invertedRotation;
                        Vector3 transformedMove;
                        Quaternion.Inverse(ref ParentTransform.WorldTransformRotation, out invertedRotation);
                        Vector3.Transform(ref move, ref invertedRotation, out transformedMove);
                        Vector3.Divide(ref transformedMove, ref ParentTransform.WorldTransformScale, out transformedMove);
                        Vector3.Add(ref LocalTransformPosition, ref transformedMove, out LocalTransformPosition);
                    }
                    else
                        Vector3.Add(ref LocalTransformPosition, ref move, out LocalTransformPosition);
                    break;
            }

            RequireUpdate();
        }
Exemple #43
0
 /// <summary>
 /// Translates the transform
 /// </summary>
 /// <param name="move">Vector used to translate</param>
 /// <param name="space">Space in which the operation is performed</param>
 public void Translate(Vector3 move, TransformSpace space = TransformSpace.Local)
 {
     Translate(ref move, space);
 }
Exemple #44
0
        /// <summary>
        /// Performs a rotation
        /// </summary>
        /// <param name="rotation">Quaternion representing the rotation</param>
        /// <param name="space">Space in which the operation is performed</param>
        public void Rotate(ref Quaternion rotation, TransformSpace space = TransformSpace.Local)
        {
            Quaternion normRotation;
            Quaternion.Normalize(ref rotation, out normRotation);
            switch (space)
            {
                case TransformSpace.Local:
                    Quaternion.Multiply(ref LocalTransformRotation, ref normRotation, out LocalTransformRotation);
                    break;
                case TransformSpace.Parent:
                    Quaternion.Multiply(ref normRotation, ref LocalTransformRotation, out LocalTransformRotation);
                    break;
                case TransformSpace.World:
                    if(_transformChanged)
                        UpdateWithParent();

                    Quaternion invertedWorld;
                    Quaternion.Inverse(ref WorldTransformRotation, out invertedWorld);
                    Quaternion.Multiply(ref LocalTransformRotation, ref invertedWorld, out LocalTransformRotation);
                    Quaternion.Multiply(ref LocalTransformRotation, ref normRotation, out LocalTransformRotation);
                    Quaternion.Multiply(ref LocalTransformRotation, ref WorldTransformRotation, out LocalTransformRotation);
                    break;
            }

            RequireUpdate();
        }
Exemple #45
0
 /// <summary>
 /// Performs a pitch rotation
 /// </summary>
 /// <param name="angle">Angle of rotation</param>
 /// <param name="space">Space in which the operation is performed</param>
 public void Pitch(float angle, TransformSpace space = TransformSpace.Local)
 {
     Vector3 xAxis = Vector3.UnitX;
     Rotate(ref xAxis, angle, space);
 }
Exemple #46
0
	    /// <summary>
	    /// Moves the node along arbitrary axes.
	    /// </summary>
	    /// <remarks>
	    ///	This method translates the node by a vector which is relative to
	    ///	a custom set of axes.
	    ///	</remarks>
	    /// <param name="axes">3x3 Matrix containg 3 column vectors each representing the
	    ///	X, Y and Z axes respectively. In this format the standard cartesian axes would be expressed as:
	    ///		1 0 0
	    ///		0 1 0
	    ///		0 0 1
	    ///		i.e. The Identity matrix.
	    ///	</param>
	    /// <param name="move">Vector relative to the supplied axes.</param>
	    /// <param name="relativeTo"></param>
	    public virtual void Translate( Matrix3 axes, Vector3 move, TransformSpace relativeTo )
		{
			Vector3 derived = axes * move;
			Translate( derived, relativeTo );
		}
Exemple #47
0
		/// <summary>
		/// Rotate the node around an arbitrary axis.
		/// </summary>
		public virtual void Rotate( Vector3 axis, float degrees, TransformSpace relativeTo )
		{
			Quaternion q = Quaternion.FromAngleAxis( Utility.DegreesToRadians( (Real)degrees ), axis );
			Rotate( q, relativeTo );
		}
Exemple #48
0
	    /// <summary>
	    /// Moves the node along the cartesian axes.
	    ///
	    ///	This method moves the node by the supplied vector along the
	    ///	world cartesian axes, i.e. along world x,y,z
	    /// </summary>
	    /// <param name="translate">Vector with x,y,z values representing the translation.</param>
	    ///<param name="relativeTo"></param>
	    public virtual void Translate( Vector3 translate, TransformSpace relativeTo )
		{
			switch ( relativeTo )
			{
				case TransformSpace.Local:
					// position is relative to parent so transform downwards
					position += orientation * translate;
					break;

				case TransformSpace.World:
					if ( parent != null )
					{
						position += ( parent.DerivedOrientation.Inverse() * translate ) / parent.DerivedScale;
					}
					else
					{
						position += translate;
					}

					break;

				case TransformSpace.Parent:
					position += translate;
					break;
			}

			NeedUpdate();
		}
Exemple #49
0
		/// <summary>
		///		Points the local Z direction of this node at a point in space.
		/// </summary>
		/// <param name="target">A vector specifying the look at point.</param>
		/// <param name="relativeTo">The space in which the point resides.</param>
		/// <param name="localDirection">
		///		The vector which normally describes the natural direction of the node, usually -Z.
		///	</param>
		public void LookAt( Vector3 target, TransformSpace relativeTo, Vector3 localDirection )
		{
			SetDirection( target - this.DerivedPosition, relativeTo, localDirection );
		}
Exemple #50
0
		/// <summary>
		/// Rotate the node around the Y-axis.
		/// </summary>
		public virtual void Yaw( float degrees, TransformSpace relativeTo )
		{
			Rotate( Vector3.UnitY, degrees, relativeTo );
		}
Exemple #51
0
		public void SetDirection( Real x, Real y, Real z, TransformSpace relativeTo )
		{
			SetDirection( x, y, z, relativeTo, Vector3.NegativeUnitZ );
		}
Exemple #52
0
		/// <summary>
		/// Rotate the node around an arbitrary axis using a Quaternion.
		/// </summary>
		public virtual void Rotate( Quaternion rotation, TransformSpace relativeTo )
		{
			rotation.Normalize(); // avoid drift

			switch ( relativeTo )
			{
				case TransformSpace.Parent:
					// Rotations are normally relative to local axes, transform up
					orientation = rotation * orientation;
					break;

				case TransformSpace.World:
					orientation = orientation * DerivedOrientation.Inverse() * rotation * DerivedOrientation;
					break;

				case TransformSpace.Local:
					// Note the order of the mult, i.e. q comes after
					orientation = orientation * rotation;
					break;
			}

			NeedUpdate();
		}
        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;
        }
        public static void LoadData()
        {
            ActiveSpace = TransformSpace.LOCAL;
            SelectedEntities.Clear();
            m_safeIterationHelper = new List<MyEntity>(100);

            m_sceneWorld = Matrix.Identity;

            // -- Set local-space offset -- //
            m_modelLocalSpace = new Matrix[3];
            m_modelLocalSpace[0] = Matrix.CreateWorld(new Vector3(m_lineLength, 0, 0), Vector3.Up, Vector3.Right);
            m_modelLocalSpace[1] = Matrix.CreateWorld(new Vector3(0, m_lineLength, 0), Vector3.Left, Vector3.Up);
            m_modelLocalSpace[2] = Matrix.CreateWorld(new Vector3(0, 0, m_lineLength), Vector3.Right, Vector3.Backward);

            // -- Colors: X,Y,Z,Highlight -- //
            m_axisColors = new Color[3];
            m_axisColors[0] = Color.Red;
            m_axisColors[1] = Color.Green;
            m_axisColors[2] = Color.Blue;
            m_highlightColor = Color.Gold;

            m_axisTexts = new List<MyTextsWrapperEnum>();
            m_axisTexts.Add(MyTextsWrapperEnum.AxisX);
            m_axisTexts.Add(MyTextsWrapperEnum.AxisY);
            m_axisTexts.Add(MyTextsWrapperEnum.AxisZ);

            // fill array with vertex-data
            #region Fill Axis-Line array
            List<MyPositionColor> vertexList = new List<MyPositionColor>(18);

            // helper to apply colors
            Color xColor = m_axisColors[0];
            Color yColor = m_axisColors[1];
            Color zColor = m_axisColors[2];

            float doubleLineOffset = m_lineOffset * 2;

            // -- X Axis -- // index 0 - 5
            vertexList.Add(new MyPositionColor(new Vector3(m_lineOffset, 0, 0), xColor));
            vertexList.Add(new MyPositionColor(new Vector3(m_lineLength, 0, 0), xColor));

            vertexList.Add(new MyPositionColor(new Vector3(doubleLineOffset, 0, 0), xColor));
            vertexList.Add(new MyPositionColor(new Vector3(doubleLineOffset, doubleLineOffset, 0), xColor));

            vertexList.Add(new MyPositionColor(new Vector3(doubleLineOffset, 0, 0), xColor));
            vertexList.Add(new MyPositionColor(new Vector3(doubleLineOffset, 0, doubleLineOffset), xColor));

            // -- Y Axis -- // index 6 - 11
            vertexList.Add(new MyPositionColor(new Vector3(0, m_lineOffset, 0), yColor));
            vertexList.Add(new MyPositionColor(new Vector3(0, m_lineLength, 0), yColor));

            vertexList.Add(new MyPositionColor(new Vector3(0, doubleLineOffset, 0), yColor));
            vertexList.Add(new MyPositionColor(new Vector3(doubleLineOffset, doubleLineOffset, 0), yColor));

            vertexList.Add(new MyPositionColor(new Vector3(0, doubleLineOffset, 0), yColor));
            vertexList.Add(new MyPositionColor(new Vector3(0, doubleLineOffset, doubleLineOffset), yColor));

            // -- Z Axis -- // index 12 - 17
            vertexList.Add(new MyPositionColor(new Vector3(0, 0, m_lineOffset), zColor));
            vertexList.Add(new MyPositionColor(new Vector3(0, 0, m_lineLength), zColor));

            vertexList.Add(new MyPositionColor(new Vector3(0, 0, doubleLineOffset), zColor));
            vertexList.Add(new MyPositionColor(new Vector3(doubleLineOffset, 0, doubleLineOffset), zColor));

            vertexList.Add(new MyPositionColor(new Vector3(0, 0, doubleLineOffset), zColor));
            vertexList.Add(new MyPositionColor(new Vector3(0, doubleLineOffset, doubleLineOffset), zColor));
            #endregion

            // -- Convert to array -- //
            m_translationLineVertices = vertexList.ToArray();
        }
Exemple #55
0
 /// <summary>
 /// Performs a roll rotation
 /// </summary>
 /// <param name="angle">Angle of rotation</param>
 /// <param name="space">Space in which the operation is performed</param>
 public void Roll(float angle, TransformSpace space = TransformSpace.Local)
 {
     Vector3 zAxis = Vector3.UnitZ;
     Rotate(ref zAxis, angle, space);
 }
Exemple #56
0
 /// <summary>
 /// Performs a rotation around an axis
 /// </summary>
 /// <param name="axis">Axis to rotate around</param>
 /// <param name="angle">Angle of rotation</param>
 /// <param name="space">Space in which the operation is performed</param>
 public void Rotate(Vector3 axis, float angle, TransformSpace space = TransformSpace.Local)
 {
     Rotate(ref axis, angle, space);
 }
Exemple #57
0
		/// <summary>
		///		Sets the node's direction vector ie it's local -z.
		/// </summary>
		/// <remarks>
		///		Note that the 'up' vector for the orientation will automatically be
		///		recalculated based on the current 'up' vector (i.e. the roll will
		///		remain the same). If you need more control, use the <see name="Orientation"/>
		///		property.
		/// </remarks>
		/// <param name="x">The x component of the direction vector.</param>
		/// <param name="y">The y component of the direction vector.</param>
		/// <param name="z">The z component of the direction vector.</param>
		/// <param name="relativeTo">The space in which this direction vector is expressed.</param>
        /// <param name="localDirectionVector">The vector which normally describes the natural direction
		///		of the node, usually -Z.
		///	</param>
		public void SetDirection( Real x, Real y, Real z, TransformSpace relativeTo, Vector3 localDirectionVector )
		{
			Vector3 dir;
			dir.x = x;
			dir.y = y;
			dir.z = z;
			SetDirection( dir, relativeTo, localDirectionVector );
		}
Exemple #58
0
 /// <summary>
 /// Performs a rotation around an axis
 /// </summary>
 /// <param name="axis">Axis to rotate around</param>
 /// <param name="angle">Angle of rotation</param>
 /// <param name="space">Space in which the operation is performed</param>
 public void Rotate(ref Vector3 axis, float angle, TransformSpace space = TransformSpace.Local)
 {
     Quaternion rotation;
     Quaternion.CreateFromAxisAngle(ref axis, angle, out rotation);
     Rotate(ref rotation, space);
 }
Exemple #59
0
		/// <summary>
		/// Rotate the node around the Y-axis.
		/// </summary>
		public virtual void Yaw( float radians, TransformSpace relativeTo )
		{
			Rotate( Vector3.UnitY, radians, relativeTo );
		}