public TrackBallController(Vector2 screenCenter, double trackBallRadius) { rotationStart = new Vector3(); rotationCurrent = new Vector3(); this.screenCenter = screenCenter; this.rotationTrackingRadius = trackBallRadius; }
public void OnMouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { var mouseState = Mouse.GetState(); var keyboardState = Keyboard.GetState(); var currentMouseCoordinate = new Vector2(e.X, e.Y); if (keyboardState.IsKeyDown(Key.ShiftLeft) && (mouseState[MouseButton.Middle] || (mouseState[MouseButton.Left] && keyboardState[Key.ControlLeft]))) { var d = 5; var previousMouseWorldCoordinate = Maths.Project(ViewMatrix, Viewport.ProjectionMatrix, previousMouseCoordinate, (Rectangle)Viewport, Maths.ProjectionTarget.View); var mouseWorldCoordinate = Maths.Project(ViewMatrix, ProjectionMatrix, currentMouseCoordinate, (Rectangle)Viewport, Maths.ProjectionTarget.View); var delta = mouseWorldCoordinate - previousMouseWorldCoordinate; delta *= d; panTrack.Update(delta.X, delta.Y); } else if (keyboardState.IsKeyDown(Key.AltLeft) && (mouseState[MouseButton.Middle] || (mouseState[MouseButton.Left] && keyboardState[Key.ControlLeft]))) { var previousMouseWorldCoordinate = Maths.Project(ViewMatrix, Viewport.ProjectionMatrix, previousMouseCoordinate, (Rectangle)Viewport, Maths.ProjectionTarget.View); var mouseWorldCoordinate = Maths.Project(ViewMatrix, ProjectionMatrix, currentMouseCoordinate, (Rectangle)Viewport, Maths.ProjectionTarget.View); var delta = mouseWorldCoordinate - previousMouseWorldCoordinate; delta *= 10; zoomTrack.Update(delta.Y); } else if (mouseState[MouseButton.Middle] || (mouseState[MouseButton.Left] && keyboardState[Key.ControlLeft])) { var delta = currentMouseCoordinate - previousMouseCoordinate; //delta *= 10; orbitTrack.Update(delta.X, delta.Y); } if (this.MouseMove != null) this.MouseMove(this, new MouseEventArgs(this, new Vector2(e.X, e.Y), default(Vector3), e.Button)); previousMouseCoordinate = currentMouseCoordinate; }
private void SetNewState(VelocityComponentState state) { if (_lastState != null) _previousState = _lastState; _lastState = state; Velocity = new Vector2(state.VelocityX, state.VelocityY); }
public unsafe void Capture(Vector2 targetSize) { if (_previousTargetSize != targetSize) { SetupBuffers(targetSize); _previousTargetSize = targetSize; } _pboIndex = (_pboIndex + 1) % 2; _nextPboIndex = (_pboIndex + 1) % 2; var frame = _frameCache[_cachedFramesIndex++]; _cachedFramesIndex %= _numberOfCachedFrames; frame.FrameIndex = _frameIndex++; GL.ReadBuffer(ReadBufferMode.ColorAttachment0); GL.BindBuffer(BufferTarget.PixelPackBuffer, _pboIds[_pboIndex]); GL.ReadPixels(0, 0, (int)targetSize.X, (int)targetSize.Y, PixelFormat.Bgra, PixelType.UnsignedByte, (IntPtr)0); GL.BindBuffer(BufferTarget.PixelPackBuffer, _pboIds[_nextPboIndex]); var ptr = GL.MapBufferRange(BufferTarget.PixelPackBuffer, (IntPtr)0, (IntPtr)GetTargetSizeInBytes(targetSize), BufferAccessMask.MapReadBit); fixed (byte* data = frame.Bytes) { memcpy((IntPtr)data, ptr, GetTargetSizeInBytes(targetSize)); } GL.UnmapBuffer(BufferTarget.PixelPackBuffer); GL.BindBuffer(BufferTarget.PixelPackBuffer, 0); GL.ReadBuffer(ReadBufferMode.Back); _frames.TryAdd(frame); }
public ListBoxTextItem(string displayName, string itemValue) : base(displayName) { Padding = new BorderDouble(3); ItemValue = itemValue; MinimumSize = new Vector2(Width, Height); }
private static void OnDraw(EventArgs args) { if (Enabled) { foreach ( var unit in ObjectManager.Get<Obj_AI_Hero>().Where(u => u.IsValidTarget() && u.IsHPBarRendered)) { // Get damage to unit var damage = damageToUnit(unit); // Continue on 0 damage if (damage <= 0) { continue; } // Get remaining HP after damage applied in percent and the current percent of health var damagePercentage = ((unit.Health - damage) > 0 ? (unit.Health - damage) : 0) / unit.MaxHealth; var currentHealthPercentage = unit.Health / unit.MaxHealth; // Calculate start and end point of the bar indicator var startPoint = new Vector2( (int) (unit.HPBarPosition.X + BarOffset.X + damagePercentage * BarWidth), (int) (unit.HPBarPosition.Y + BarOffset.Y) - 5); var endPoint = new Vector2( (int) (unit.HPBarPosition.X + BarOffset.X + currentHealthPercentage * BarWidth) + 1, (int) (unit.HPBarPosition.Y + BarOffset.Y) - 5); // Draw the line Drawing.DrawLine(startPoint, endPoint, LineThickness, DrawingColor); } } }
public static void OrbwalkLRCLK_ValueChanged(object sender, OnValueChangeEventArgs e) { if (e.GetNewValue<KeyBind>().Active) { LastClickPoint = Game.CursorPos.To2D(); } }
private static void Game_OnWndProc(WndEventArgs args) { if (args.Msg == (uint)WindowsMessages.WM_RBUTTONDOWN) { LastClickPoint = Game.CursorPos.To2D(); } }
internal override float SignedDistance(ref Vector3 position, float lodVoxelSize, IMyModule macroModulator, IMyModule detailModulator) { Vector3 localPosition = position - m_translation; Vector3.Transform(ref localPosition, ref m_invRotation, out localPosition); var primaryDistance = new Vector2(localPosition.X, localPosition.Z).Length() - m_primaryRadius; var signedDistance = new Vector2(primaryDistance, localPosition.Y).Length() - m_secondaryRadius; var potentialHalfDeviation = m_potentialHalfDeviation + lodVoxelSize; if (signedDistance > potentialHalfDeviation) return 1f; else if (signedDistance < -potentialHalfDeviation) return -1f; if (m_enableModulation) { Debug.Assert(m_deviationFrequency != 0f); float normalizer = 0.5f * m_deviationFrequency; var tmp = localPosition * normalizer; float halfDeviationRatio = (float)macroModulator.GetValue(tmp.X, tmp.Y, tmp.Z); signedDistance -= halfDeviationRatio * m_secondaryHalfDeviation; } if (m_enableModulation && -m_detailSize < signedDistance && signedDistance < m_detailSize) { Debug.Assert(m_detailFrequency != 0f); float normalizer = 0.5f * m_detailFrequency; var tmp = localPosition * normalizer; signedDistance += m_detailSize * (float)detailModulator.GetValue(tmp.X, tmp.Y, tmp.Z); } return signedDistance / lodVoxelSize; }
/// <summary> /// Binds to specific events of the provided CoreWindow /// </summary> /// <param name="nativeWindow">A reference to <see cref="CoreWindow"/> or <see cref="UIElement"/> class.</param> /// <exception cref="ArgumentNullException">Is thrown when <paramref name="nativeWindow"/> is null.</exception> /// <exception cref="ArgumentException">Is thrown when <paramref name="nativeWindow"/> is not a <see cref="CoreWindow"/> and not an <see cref="UIElement"/></exception> protected override void BindWindow(object nativeWindow) { if (nativeWindow == null) throw new ArgumentNullException("nativeWindow"); var window = nativeWindow as CoreWindow; if (window != null) { windowSize = new Size2F((float)window.Bounds.Width, (float)window.Bounds.Height); var position = window.PointerPosition; pointerPosition = new Vector2((float)position.X/windowSize.Width, (float)position.Y / windowSize.Height); window.PointerPressed += HandleWindowPointerEvent; window.PointerReleased += HandleWindowPointerEvent; window.PointerWheelChanged += HandleWindowPointerEvent; window.PointerMoved += HandleWindowPointerEvent; window.SizeChanged += window_SizeChanged; return; } uiElement = nativeWindow as FrameworkElement; if (uiElement != null) { windowSize = new Size2F((float)uiElement.ActualWidth, (float)uiElement.ActualHeight); uiElement.Loaded += HandleLoadedEvent; uiElement.SizeChanged += HandleSizeChangedEvent; uiElement.PointerPressed += HandleUIElementPointerEvent; uiElement.PointerReleased += HandleUIElementPointerEvent; uiElement.PointerWheelChanged += HandleUIElementPointerEvent; uiElement.PointerMoved += HandleUIElementPointerEvent; uiElement.PointerEntered += HandleUIElementPointerEvent; return; } throw new ArgumentException("Should be an instance of either CoreWindow or UIElement", "nativeWindow"); }
public static bool IsOnScreen(this Vector2 start, Vector2 end) { if (start.X > 0 && start.X < Drawing.Width && start.Y > 0 && start.Y < Drawing.Height && end.X > 0 && end.X < Drawing.Width && end.Y > 0 && end.Y < Drawing.Height) { return true; } if (start.Intersection(end, new Vector2(0, 0), new Vector2(Drawing.Width, 0)).Intersects) { return true; } if (start.Intersection(end, new Vector2(0, 0), new Vector2(0, Drawing.Height)).Intersects) { return true; } if ( start.Intersection(end, new Vector2(0, Drawing.Height), new Vector2(Drawing.Width, Drawing.Height)) .Intersects) { return true; } return start.Intersection(end, new Vector2(Drawing.Width, 0), new Vector2(Drawing.Width, Drawing.Height)) .Intersects; }
public override void OnUpdate(long msec) { var g2d = Graphics2D.GetInstance (); var pos = g2d.GetMousePosition (); if (Input.GetKeyDown (KeyCode.Mouse0)) { var start = new Vector3 (pos.X, pos.Y, 1000); var end = new Vector3 (pos.X, pos.Y, -1000); var node = World.Pick (start, end); if (node != null) { this.picked = node; this.delta = pos - new Vector2 (node.Position.X, node.Position.Y); } } if (Input.GetKeyUp(KeyCode.Mouse0)) { this.picked = null; } if (picked != null) { var t = pos - delta; picked.Translation = new Vector3(t.X, t.Y, 0); } base.OnUpdate (msec); }
public LogoElement(InterfaceElement parent, Vector2 location) : base(parent, location) { Opacity = 1f; Size = Program.Logo.Size; }
public static bool IsLyingInCone(Vector2 position, Vector2 apexPoint, Vector2 circleCenter, double aperture) { // This is for our convenience var halfAperture = aperture / 2; // Vector pointing to X point from apex var apexToXVect = apexPoint - position; // Vector pointing from apex to circle-center point. var axisVect = apexPoint - circleCenter; // X is lying in cone only if it's lying in // infinite version of its cone -- that is, // not limited by "round basement". // We'll use dotProd() to // determine angle between apexToXVect and axis. var isInInfiniteCone = DotProd(apexToXVect, axisVect) / Magn(apexToXVect) / Magn(axisVect) > // We can safely compare cos() of angles // between vectors instead of bare angles. Math.Cos(halfAperture); if (!isInInfiniteCone) return false; // X is contained in cone only if projection of apexToXVect to axis // is shorter than axis. // We'll use dotProd() to figure projection length. var isUnderRoundCap = DotProd(apexToXVect, axisVect) / Magn(axisVect) < Magn(axisVect); return isUnderRoundCap; }
public static Vector2 FindNearestLineCircleIntersections(this Vector2 start, Vector2 end, Vector2 circlePos, float radius) { float t; var dx = end.X - start.X; var dy = end.Y - start.Y; var a = dx * dx + dy * dy; var b = 2 * (dx * (start.X - circlePos.X) + dy * (start.Y - circlePos.Y)); var c = (start.X - circlePos.X) * (start.X - circlePos.X) + (start.Y - circlePos.Y) * (start.Y - circlePos.Y) - radius * radius; var det = b * b - 4 * a * c; if ((a <= 0.0000001) || (det < 0)) { return Vector2.Zero; } if (det.Equals(0f)) { t = -b / (2 * a); return new Vector2(start.X + t * dx, start.Y + t * dy); } t = (float)((-b + Math.Sqrt(det)) / (2 * a)); var intersection1 = new Vector2(start.X + t * dx, start.Y + t * dy); t = (float)((-b - Math.Sqrt(det)) / (2 * a)); var intersection2 = new Vector2(start.X + t * dx, start.Y + t * dy); return Vector2.Distance(intersection1, ObjectManager.Player.Position.LSTo2D()) > Vector2.Distance(intersection2, ObjectManager.Player.Position.LSTo2D()) ? intersection2 : intersection1; }
public PartPreviewMainWindow(PrintItemWrapper printItem, View3DWidget.AutoRotate autoRotate3DView, View3DWidget.OpenMode openMode = View3DWidget.OpenMode.Viewing) : base(750, 550) { UseOpenGL = true; string partPreviewTitle = LocalizedString.Get("MatterControl"); Title = string.Format("{0}: ", partPreviewTitle) + Path.GetFileName(printItem.Name); this.Name = "Part Preview Window"; partPreviewWidget = new PartPreviewContent(printItem, View3DWidget.WindowMode.StandAlone, autoRotate3DView, openMode); partPreviewWidget.Closed += (sender, e) => { Close(); }; this.AddChild(partPreviewWidget); AddHandlers(); Width = 750; Height = 550; MinimumSize = new Vector2(400, 300); ShowAsSystemWindow(); }
public TrackBallController(TrackBallController trackBallToCopy) { this.screenCenter = trackBallToCopy.screenCenter; this.rotationTrackingRadius = trackBallToCopy.rotationTrackingRadius; this.currentRotationMatrix = trackBallToCopy.currentRotationMatrix; this.currentTranslationMatrix = trackBallToCopy.currentTranslationMatrix; }
public static PointF Rotate(this PointF c, float angle) { var cosAngle = Math.Cos(angle); var sinAngle = Math.Sin(angle); return(new PointF((float)(cosAngle * c.X - sinAngle * c.Y), (float)(sinAngle * c.X + cosAngle * c.Y))); }
public static float LengthSquare(this PointF c) { var x = c.X; var y = c.Y; return(x * x + y * y); }
/// <summary> /// Distance square to the point /// </summary> public static float DistanceSquareTo(this PointF point1, PointF point2) { var dx = point2.X - point1.X; var dy = point2.Y - point1.Y; return(dx * dx + dy * dy); }
public PCircle( Vector2 position, float radius, int sides, bool filled ) : base(filled) { this.position = position; this.radius = radius; this.sides = sides; }
public EquilateralTriangle(Vector2 v0, Vector2 v1, Vector2 v2) { corners[0] = v0; corners[1] = v1; corners[2] = v2; Recreate(); }
public IsoSphere(int s_steps, int t_steps, float x_scale, float y_scale, float z_scale) { int count = 4 * s_steps * t_steps ; Vertices = new Vector3[count]; Normals = new Vector3[count]; Texcoords = new Vector2[count]; Indices = new int[6 * count / 4]; int i = 0; for (double t = -System.Math.PI; (float)t < (float)System.Math.PI - Single.Epsilon; t += System.Math.PI / (double)t_steps) { for (double s = 0.0; (float)s < (float)DoublePI; s += System.Math.PI / (double)s_steps) { Vertices[i].X = x_scale * (float)(System.Math.Cos(s) * System.Math.Sin(t)); Vertices[i].Y = y_scale * (float)(System.Math.Sin(s) * System.Math.Sin(t)); Vertices[i].Z = z_scale * (float)System.Math.Cos(t); //vertices[i] = vertices[i].Scale(x_scale, y_scale, z_scale); Normals[i] = Vector3.Normalize(Vertices[i]); ++i; } } for (i = 0; i < 6*count/4; i+=6) { Indices[i] = i; Indices[i + 1] = i + 1; Indices[i + 2] = i + 2 * s_steps + 1; Indices[i + 3] = i + 2 * s_steps; Indices[i + 4] = i; Indices[i + 5] = i + 2 * s_steps + 1; } }
/// <summary> /// Determine which side of the line the 2D point is at /// </summary> /// <returns> /// 1 if on the right hand side; /// 0 if on the line; /// -1 if on the left hand side; /// </returns> public static float Side(this PointF c, PointF point) { var res = c.X * point.Y - point.X * c.Y; return(res > float.Epsilon ? 1 : res < -float.Epsilon ? -1 : 0); }
/// <summary> /// Distance to the point /// </summary> public static float DistanceTo(this PointF point1, PointF point2) { var dx = point2.X - point1.X; var dy = point2.Y - point1.Y; return((float)Math.Sqrt(dx * dx + dy * dy)); }
public override void RecreateControls(bool constructor) { base.RecreateControls(constructor); AddCaption(MySpaceTexts.ScreenCaptionWorkshopTags); Vector2 origin = new Vector2(0f, -0.025f * (m_activeTags.Count + 2)); Vector2 offset = new Vector2(0f, 0.05f); m_checkboxes.Clear(); foreach (var pair in m_activeTags) { AddLabeledCheckbox(origin += offset, pair.Key, pair.Value); if (m_typeTag == MySteamWorkshop.WORKSHOP_MOD_TAG) { var name = pair.Key.Replace(" ", string.Empty); var path = Path.Combine(MyFileSystem.ContentPath, "Textures", "GUI", "Icons", "buttons", name + ".dds"); if (File.Exists(path)) { AddIcon(origin + new Vector2(-0.05f, 0f), path, new Vector2(0.04f, 0.05f)); } } } origin += offset; Controls.Add(m_okButton = MakeButton(origin += offset, MySpaceTexts.Ok, MySpaceTexts.Ok, OnOkClick, MyGuiDrawAlignEnum.HORISONTAL_RIGHT_AND_VERTICAL_CENTER)); Controls.Add(m_cancelButton = MakeButton(origin, MySpaceTexts.Cancel, MySpaceTexts.Cancel, OnCancelClick, MyGuiDrawAlignEnum.HORISONTAL_LEFT_AND_VERTICAL_CENTER)); CloseButtonEnabled = true; }
// Get ready to start. private void ResetBoundingRect(Vector2[] vertices) { _numPoints = vertices.Count(); // Find the minimum and maximum points // in all four directions. double minx = vertices[0].X; double maxx = minx; double miny = vertices[0].Y; double maxy = miny; double minxi = 0; double maxxi = 0; double minyi = 0; double maxyi = 0; for (int i = 1; i < _numPoints; i++) { if (minx > vertices[i].X) { minx = vertices[i].X; minxi = i; } if (maxx < vertices[i].X) { maxx = vertices[i].X; maxxi = i; } if (miny > vertices[i].Y) { miny = vertices[i].Y; minyi = i; } if (maxy < vertices[i].Y) { maxy = vertices[i].Y; maxyi = i; } } _controlPoints[0] = (int)minxi; _controlPoints[1] = (int)maxyi; _controlPoints[2] = (int)maxxi; _controlPoints[3] = (int)minyi; _currentControlPoint = -1; // Reset the current and best bounding rectangle. _currentRectangle = new Vector2[] { new Vector2(minx, miny), new Vector2(maxx, miny), new Vector2(maxx, maxy), new Vector2(minx, maxy), }; var currentArea = (maxx - minx) * (maxy - miny); _bestRectangle = _currentRectangle; _bestArea = currentArea; // So far we have not checked any edges. _edgeChecked = new bool[_numPoints]; for (int i = 0; i < _numPoints; i++) { _edgeChecked[i] = false; } }
public override void Update(GameTime gameTime) { if (mouseDelta == Vector2.Zero) return; Vector3 cameraDirection = camera.Direction; float length = cameraDirection.Length(); cameraDirection.Normalize(); Vector3 cameraNormalDirection = Vector3.Cross(camera.UpVector, cameraDirection); Vector3 cameraTargetNormalDirectionUp = Vector3.Cross(cameraDirection, cameraNormalDirection); cameraTargetNormalDirectionUp.Normalize(); Vector3 newTargetRelative = cameraDirection; if (mouseDelta.X != 0) newTargetRelative -= cameraNormalDirection * mouseDelta.X * mouseSensivity * 1.0f / gameTime.ElapsedMiliseconds; if (mouseDelta.Y != 0) newTargetRelative -= cameraTargetNormalDirectionUp * mouseDelta.Y * mouseSensivity * mouseYInverted * 1.0f/gameTime.ElapsedMiliseconds; newTargetRelative = Vector3.Multiply(newTargetRelative, length); camera.Target = camera.Position + newTargetRelative; Cursor.Position = Master.I.form.PointToScreen(new Point(Master.I.form.ClientSize.Width / 2, Master.I.form.ClientSize.Height / 2)); Cursor.Hide(); mouseDelta = Vector2.Zero; }
public void AddWall(Vector2 p1, Vector2 p2) { double angle1, angle2; angle1 = Math.Atan2(p1.Y, p1.X); angle2 = Math.Atan2(p2.Y, p2.X); double adiff = angle2 - angle1; if (adiff < 0) adiff += Math.PI * 2.0; if (adiff > Math.PI) { Vector2 tmp = p2; p2 = p1; p1 = tmp; double tmp2 = angle1; angle1 = angle2; angle2 = tmp2; } if (angle1 < 0) angle1 += Math.PI * 2.0; if (angle2 < 0) angle2 += Math.PI * 2.0; if (angle2 < angle1) { float tmp = getinetersecty0(p1, p2); addit(tmp, 0.0f, p2.Length(), (float)angle2); addit(p1.Length(), (float)angle1, tmp, (float)Math.PI * 2.0f); } else { addit(p1.Length(), (float)angle1, p2.Length(), (float)angle2); } }
static int calcularDistancia() { Vector2 posicionBot = new Vector2(Program.bot.cliente.Self.SimPosition.X, Program.bot.cliente.Self.SimPosition.Y); Vector2 posicionCamarero = new Vector2(posCamarero.X, posCamarero.Y); return (int)(Math.Abs(Math.Sqrt(Math.Pow(posicionBot.X - posicionCamarero.X, 2) + Math.Pow(posicionBot.Y - posicionCamarero.Y, 2)))); }
protected override void TickCore(Entity host, RealmTime time, ref object state) { int cooldown; if (state == null) cooldown = 1000; else cooldown = (int)state; Status = CycleStatus.NotStarted; if (host.HasConditionEffect(ConditionEffects.Paralyzed)) return; var player = (Player)host.GetNearestEntity(distance, null); if (player != null) { Vector2 vect; vect = new Vector2(player.X - host.X, player.Y - host.Y); vect.Normalize(); float dist = host.GetSpeed(speed) * (time.thisTickTimes / 1000f); host.ValidateAndMove(host.X + (-vect.X) * dist, host.Y + (-vect.Y) * dist); host.UpdateCount++; if (cooldown <= 0) { Status = CycleStatus.Completed; cooldown = 1000; } else { Status = CycleStatus.InProgress; cooldown -= time.thisTickTimes; } } state = cooldown; }
public override void Initialize() { this.game = new MusicProject.Game(); this.game.Initialize(this); #region WAVE SOFTWARE LICENSE AGREEMENT this.backgroundSplashColor = new Color("#ebebeb"); this.spriteBatch = new SpriteBatch(WaveServices.GraphicsDevice); var resourceNames = Assembly.GetExecutingAssembly().GetManifestResourceNames(); string name = string.Empty; foreach (string item in resourceNames) { if (item.Contains("SplashScreen.wpk")) { name = item; break; } } if (string.IsNullOrWhiteSpace(name)) { throw new InvalidProgramException("License terms not agreed."); } using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name)) { this.splashScreen = WaveServices.Assets.Global.LoadAsset<Texture2D>(name, stream); } position = new Vector2(); #endregion }
/// <summary> /// Adds the enemy. /// </summary> /// <param name="position">The position.</param> public void AddEnemy(Vector2 position) { Enemy enemy = this.enemies[this.enemyIndex]; enemy.Position = position; this.enemyIndex = (this.enemyIndex + 1) % this.enemyMax; }
public static float Length(this PointF c) { var x = c.X; var y = c.Y; return((float)Math.Sqrt(x * x + y * y)); }
public TextWidget(string text, double x = 0, double y = 0, double pointSize = 12, Justification justification = Justification.Left, RGBA_Bytes textColor = new RGBA_Bytes(), bool ellipsisIfClipped = true, bool underline = false, RGBA_Bytes backgroundColor = new RGBA_Bytes()) { pointSize *= GlobalPointSizeScaleRatio; Selectable = false; DoubleBuffer = DoubleBufferDefault; AutoExpandBoundsToText = false; EllipsisIfClipped = ellipsisIfClipped; OriginRelativeParent = new Vector2(x, y); this.textColor = textColor; if (this.textColor.Alpha0To255 == 0) { // we assume it is the default if alpha 0. Also there is no reason to make a text color of this as it will draw nothing. this.textColor = RGBA_Bytes.Black; } if (backgroundColor.Alpha0To255 != 0) { BackgroundColor = backgroundColor; } base.Text = text; StyledTypeFace typeFaceStyle = new StyledTypeFace(LiberationSansFont.Instance, pointSize, underline); printer = new TypeFacePrinter(text, typeFaceStyle, justification: justification); LocalBounds = printer.LocalBounds; MinimumSize = new Vector2(LocalBounds.Width, LocalBounds.Height); }
internal Offset(Vector2 vec, int width, int height) { X = vec.X; Y = vec.Y; Width = width; Height = height; }
/// <summary> /// Normal from the line to the point /// </summary> public static PointF Normal(this PointF direction, PointF point) { var cosAngle = (point.X * direction.X + point.Y * direction.Y) / direction.LengthSquare(); var x = direction.X * cosAngle; var y = direction.Y * cosAngle; return(new PointF(point.X - x, point.Y - y)); }
/// <summary> /// Normal from the line to the point (the line is defined by normalized direction) /// </summary> public static PointF Normal2(this PointF normalizedDirection, PointF point) { var cosAngle = point.X * normalizedDirection.X + point.Y * normalizedDirection.Y; var x = normalizedDirection.X * cosAngle; var y = normalizedDirection.Y * cosAngle; return(new PointF(point.X - x, point.Y - y)); }
/// <summary> /// Minimal degree between vectors /// </summary> public static float Angle(this PointF c1, PointF c2) { var a = c1.Angle() - c2.Angle(); a += (float)((a > PI) ? -2 * PI : (a < -PI) ? 2 * PI : 0); return(a); }
public static PointF Rotate(this PointF c, float angle, PointF center) { var cosAngle = Math.Cos(angle); var sinAngle = Math.Sin(angle); var xx = c.X - center.X; var yy = c.Y - center.Y; return(new PointF((float)(cosAngle * xx - sinAngle * yy + center.X), (float)(sinAngle * xx + cosAngle * yy + center.Y))); }
/// <summary> /// This is essentially the same as Lerp but instead the function will ensure that the speed never exceeds maxDistanceDelta. /// Negative values of maxDistanceDelta pushes the vector away from target. /// </summary> public static PointF MoveTowards(this PointF current, PointF target, float maxDistanceDelta) { var dir = target.Sub(current); var magnitude = dir.Length(); if (magnitude <= maxDistanceDelta || magnitude <= float.Epsilon) { return(target); } return(current.Add(dir.Mul(maxDistanceDelta / magnitude))); }
/// <summary> /// Linear interpolation /// </summary> public static PointF LerpTrim(this PointF x1, PointF x2, float k) { if (k < 0) { k = 0f; } if (k > 1) { k = 1f; } return(Lerp(x1, x2, k)); }
public static PointF Intersection2(this PointF dir1, PointF point1, PointF dir2, PointF point2) { var x0 = point1.X; var p = dir1.X; var y0 = point1.Y; var q = dir1.Y; var x1 = point2.X; var p1 = dir2.X; var y1 = point2.Y; var q1 = dir2.Y; var x = (x0 * q * p1 - x1 * q1 * p - y0 * p * p1 + y1 * p * p1) / (q * p1 - q1 * p); var y = (y0 * p * q1 - y1 * p1 * q - x0 * q * q1 + x1 * q * q1) / (p * q1 - p1 * q); return(new PointF(x, y)); }
// Find the point of intersection between // the lines p1 --> p2 and p3 --> p4. // Находит пересечение отрезков, если точно известно, что они пересекаются public static PointF SegmentIntersection(PointF p1, PointF p2, PointF p3, PointF p4) { // Get the segments' parameters. float dx12 = p2.X - p1.X; float dy12 = p2.Y - p1.Y; float dx34 = p4.X - p3.X; float dy34 = p4.Y - p3.Y; // Solve for t1 and t2 float denominator = (dy12 * dx34 - dx12 * dy34); float t1 = ((p1.X - p3.X) * dy34 + (p3.Y - p1.Y) * dx34) / denominator; float t2 = ((p3.X - p1.X) * dy12 + (p1.Y - p3.Y) * dx12) / -denominator; // Find the point of intersection. return(new PointF(p1.X + dx12 * t1, p1.Y + dy12 * t1)); }
/// <summary> /// Точка пересечения между двумя примыми, заднными направляющей и точкой /// </summary> public static PointF Intersection(this PointF dir1, PointF point1, PointF dir2, PointF point2) { var x2 = point1.X; var y2 = point1.Y; var x1 = point1.X + dir1.X; var y1 = point1.Y + dir1.Y; var a2 = point2.X; var b2 = point2.Y; var a1 = point2.X + dir2.X; var b1 = point2.Y + dir2.Y; var c = (b2 - b1) / (a2 - a1 + 0.00001f); var z = (y2 - y1) / (x2 - x1 + 0.00001f); var x = (c * x2 - y2 - z * a2 + b2) / (c - z); var y = c * x - c * x2 + y2; return(new PointF(x, y)); }
/// <summary> /// Norma of cross product (норма векторного произведения, площадь натянутого паралелограмма) /// </summary> public static float DotVectorLength(this PointF x1, PointF x2) { return(Math.Abs(x1.X * x2.Y - x1.Y * x2.X)); }
/// <summary> /// Angle from (-PI ; PI] /// </summary> public static float Angle(this PointF c) { return((float)Math.Atan2(c.Y, c.X)); }
public static PointF InitFromAngle(this PointF c, float r, float angle) { var res = new PointF((float)(r * Math.Cos(angle)), (float)(r * Math.Sin(angle))); return(res); }
public static PointF Rotate90(this PointF c) { return(new PointF(-c.Y, c.X)); }
/// <summary> /// Projection on direction /// </summary> public static PointF Projection(this PointF x, PointF normalizedDirection) { var cosAngle = x.X * normalizedDirection.X + x.Y * normalizedDirection.Y; return(new PointF(normalizedDirection.X * cosAngle, normalizedDirection.Y * cosAngle)); }
public static PointF Inverse(this PointF c) { var res = new PointF(-c.X, -c.Y); return(res); }
/// <summary> /// Linear interpolation /// </summary> /// <param name="k">From 0 to 1</param> /// <returns></returns> public static PointF Lerp(this PointF x1, PointF x2, float k) { var m = 1.0f - k; return(new PointF(x1.X * m + x2.X * k, x1.Y * m + x2.Y * k)); }
/// <summary> /// Complex conjugate (комплексно-сопряженный вектор) /// </summary> public static PointF Conjugate(this PointF c) { var res = new PointF(c.X, -c.Y); return(res); }
public static float CosAngle(this PointF c) { return(c.X / c.Length()); }
public static System.Drawing.Point ToPoint(this PointF c) { return(new System.Drawing.Point((int)Math.Round(c.X), (int)Math.Round(c.Y))); }
public static PointF Rotate(this PointF c, float cosAngle, float sinAngle) { return(new PointF(cosAngle * c.X - sinAngle * c.Y, sinAngle * c.X + cosAngle * c.Y)); }
/// <summary> /// Cos of angle betwwen this and other vector /// </summary> public static float CosAngle(this PointF x1, PointF x2) { return((x1.X * x2.X + x1.Y * x2.Y) / x1.Length() / x2.Length()); }
/// <summary> /// Dot product for complex numbers (скалярное произведение комплексных чисел) /// </summary> public static PointF DotComplex(this PointF x1, PointF x2) { return(new PointF(x1.X * x2.X - x1.Y * x2.Y, x1.Y * x2.X + x1.X * x2.Y)); }
public static string ToString(this PointF c) { return(string.Format("{0:0.00};{1:0.00}", c.X, c.Y)); }
public static System.Drawing.PointF ToPointF(this PointF c) { return(new System.Drawing.PointF(c.X, c.Y)); }