void Start() { LockstepManager.Initialize (); GridManager.Generate (); const int count = 32; for (int i = -count; i < count; i++) { for (int j = -count; j < count; j++) { if (i * i + j * j < 16) continue; if (LSUtility.GetRandom (2) == 0) { Vector2d pos = new Vector2d(i,j); GridManager.GetNode(pos.x,pos.y).Unwalkable = true; Instantiate(TestWall).GetComponent<LSBody>().Initialize(pos); } } } /*LSBody wall = Instantiate (TestWall).GetComponent<LSBody> (); wall.Initialize (new Vector2d (-32 + 14, 0)); for (long i = wall.XMin; i <= wall.XMax; i+= FixedMath.One) { for (long j = wall.YMin; j <= wall.YMax; j+= FixedMath.One) { GridManager.GetNode (i, j).Unwalkable = true; } }*/ GridManager.Initialize (); controller = AgentController.Create (); for (int i = 0; i < 256; i++) { agent = controller.CreateAgent (AgentCode.Minion); } PlayerManager.AddAgentController (controller); }
public Box2d(Vector2d p, Vector2d q) { xmin = System.Math.Min(p.x,q.x); xmax = System.Math.Max(p.x,q.x); ymin = System.Math.Min(p.y,q.y); ymax = System.Math.Max(p.y,q.y); }
/// <summary> /// Initializes a new instance of the <c>LightWeightPolylineVertex</c> class. /// </summary> /// <param name="x">X coordinate.</param> /// <param name="y">Y coordinate.</param> public LightWeightPolylineVertex(double x, double y) { this.location = new Vector2d(x, y); this.bulge = 0.0; this.beginThickness = 0.0f; this.endThickness = 0.0f; }
public override double Calculate() { var result = projector.GetCoordinatesForScreenPoint(point.X, point.Y); switch (point.AxisType) { case AxisTypes.Alt: { var dist = (result.Y - point.Alt) * 100 * point.Weight; return dist; } case AxisTypes.Az: { var dist = (result.X - (-point.Az + 270)) * 100 * point.Weight; return dist; } case AxisTypes.Both: { var test = new Vector2d(-point.Az + 270, point.Alt); var dist = result.Distance3d(test) * 100 * point.Weight; return dist; } default: return 0; } }
public void Rotate(Vector2d startPoint, Vector2d endPoint) { var rotation = CalculateRotation(startPoint, endPoint); _tempCameraOrientation = rotation.GetRotationMatrix(); FireCameraChanged(); }
public void Update(DateTime st) { double t = (DateTime.Now - ShootTime).TotalMilliseconds; position = From + Vector2d.Multiply(dir, Bullet.Speed * t); if ((position - From).LengthSquared > (From - To).LengthSquared) HitEnd = true; }
/// <summary> /// Initializes a new instance of the <c>LightWeightPolylineVertex</c> class. /// </summary> /// <param name="location">Lightweight polyline <see cref="netDxf.Vector2d">vertex</see> coordinates.</param> public LightWeightPolylineVertex(Vector2d location) { this.location = location; this.bulge = 0.0; this.beginThickness = 0.0f; this.endThickness = 0.0f; }
public override void Initialize(LSAgent agent) { Body = agent.Body; timescaledTurnRate = TurnRate * LockstepManager.Timestep >> FixedMath.SHIFT_AMOUNT; TargetReached = true; TargetRotation = Vector2d.up; }
public Bullet(Vector2d From, Vector2d To, DateTime st) { ShootTime = DateTime.Now; this.From = From; this.To = To; this.dir = Vector2d.Normalize(To - From); }
public Vertex(double px, double py, double pz, /*double nx, double ny, double nz,*/ double tcx, double tcy, float r, float b, float g, float a) { Position = new Vector3d(px, py, pz); //Normal = new Vector3d(nx, ny, nz); TexCoord = new Vector2d(tcx, tcy); Color = new Vector4(r, g, b, a); }
public Vector2d TransformToRelative(Vector2d absoluteCoordinate) { var x = absoluteCoordinate.X / Control.Width * 2 - 1; var y = (Control.Height - absoluteCoordinate.Y) / Control.Height * 2 - 1; return new Vector2d(x, y); }
public Vertex(Vector3d p, /*Vector3d n,*/ Vector2d tc, Vector4 c) { Position = p; //Normal = n; TexCoord = tc; Color = c; }
public Vertex(double px, double py, double pz, /*double nx, double ny, double nz,*/ double tcx, double tcy) { Position = new Vector3d(px, py, pz); //Normal = new Vector3d(nx, ny, nz); TexCoord = new Vector2d(tcx, tcy); Color = Vector4.One; }
public static Vector2d Multiply(ref Matrix3x2d m, Vector2d v) { return new Vector2d( m.M00 * v.X + m.M10 * v.Y + m.M20, m.M01 * v.X + m.M11 * v.Y + m.M21 ); }
public void Rotate(Vector2d startPoint, Vector2d endPoint) { var rotation = CalculateRotation(startPoint, endPoint); var result = Vector3d.Transform(_camera.Position, rotation); _camera.Position = result; }
/// <see cref="PositionUpdater.UpdatePositions(List{Particle})"/> /// <summary> /// Initiates the particle moving behaviour and directions /// </summary> public void UpdatePositions(List<Particle> particles) { bool isFire = true; foreach (var particle in particles) { if (isFire) { Random rand = new Random (); double x = rand.NextDouble (); // To generate movings of the particles if (x > 0.5) { x = x - 1; } x = x / 5; Vector2d Translation = new Vector2d (x, DEFAULT_DELTA); particle.updatePosition (Translation); isFire = false; } else { Random rand = new Random (); double x = rand.NextDouble (); if (x > 0.5) { x = x - 1; } x = x / 5; Vector2d Translation = new Vector2d (x, -DEFAULT_DELTA); particle.updatePosition (Translation); isFire = true; } } }
public void Loop(TimeSpan loopTime) { var c = new Vector2d( (Settings.Max.X + Settings.Min.X) / 2, (Settings.Max.Y + Settings.Min.Y) / 2); foreach (var node in graph.Nodes) { if (node.Position.X < Settings.Min.X) { node.ForceN.X += Settings.Force; } if (node.Position.Y < Settings.Min.Y) { node.ForceN.Y += Settings.Force; } if (node.Position.X > Settings.Max.X) { node.ForceN.X -= Settings.Force; } if (node.Position.Y > Settings.Max.Y) { node.ForceN.Y -= Settings.Force; } node.ForceN.X -= (node.Position.X - c.X) / 100; node.ForceN.Y -= (node.Position.Y - c.Y) / 100; } }
/// <summary> /// Constructor with default velocity, i.e. 1.0. /// </summary> /// <param name="initialPosition">The particle's initial position</param> /// <param name="maxLifetime">The particle's maximum lifetime</param> /// <param name="agingVelocity">The particle's aging velocity</param> public AirParticle(Vector2d initialPosition, int maxLifetime, int agingVelocity) : base(initialPosition, maxLifetime, agingVelocity) { this.Position = initialPosition; this.RemainingLifetime = maxLifetime; SetAgingVelocity(agingVelocity); }
public override void Simulate() { if (IsMoving) { MovementDirection = Destination - Body.Position; long distance; MovementDirection.Normalize (out distance); if (distance > closingDistance) { Body.Velocity += (MovementDirection * timescaledSpeed - Body.Velocity) * SteeringWeight; } else { Body.Velocity += (MovementDirection * ((timescaledSpeed * distance) / (closingDistance)) - Body.Velocity) * SteeringWeight; if (distance < ((closingDistance * closingDistanceMultiplier) >> FixedMath.SHIFT_AMOUNT)) { StopMove (); } } Body.VelocityChanged = true; } else { if (TouchingObjects.Count > 0) Body.Velocity /= TouchingObjects.Count; Body.Velocity -= Body.Velocity * SteeringWeight; StopTime++; } TouchingObjects.FastClear (); }
public static void Circle(Vector2d origin, double radius, double currentZoom = 1, int sides = 0, bool loop = false) { if (sides < 3) { if (radius < 20) sides = 16; else if (radius < 50) sides = 24; else if (radius < 100) sides = 42; else if (radius < 300) sides = 64; else sides = 128; } radius /= currentZoom; var diff = (2 * Math.PI) / sides; var last = new Vector2d(0, 0); for (var i = 0; i < sides; i++) { var deg = diff * i; var point = new Vector2d(origin.X + Math.Cos(deg) * radius, origin.Y + Math.Sin(deg) * radius); if (i > 0 || loop) { if (!loop) GL.Vertex2(last); GL.Vertex2(point); } last = point; } if (loop) return; GL.Vertex2(last); GL.Vertex2(origin.X + radius, origin.Y); }
public RenderElement(Vector3d[] pos, Vector3d[] nor, Vector2d[] tex, int[] idx) { this.pos = pos; this.nor = nor; this.tex = tex; this.idx = idx; }
public void Loop(TimeSpan loopTime) { foreach (var connection in Graph.Connectivities) { var node1 = connection.Node1; var node2 = connection.Node2; var distance = Vector2d.GetDistance(node1.Position, node2.Position); if (distance < 0.1) { // Jitter distance = 0.1; } var forceS = Settings.DistanceToForceFct(distance); forceS *= Settings.ForceFactor; forceS *= connection.Connectivity; var dX = Math.Max(0.1, node1.Position.X - node2.Position.X); var dY = Math.Max(0.1, node1.Position.Y - node2.Position.Y); Vector2d force = new Vector2d(forceS * dX / distance, forceS * dY / distance); node1.ForceN.AddTo(force.Negate()); node2.ForceN.AddTo(force); } }
public static Vector2d Next(this Random random, Vector2d min, Vector2d max) { return new Vector2d( min.X + random.NextDouble() * (max.X - min.X), min.Y + random.NextDouble() * (max.Y - min.Y) ); }
public static bool IsReal(Vector2d v) { return !IsNaN(v) && !double.IsPositiveInfinity(v.X) && !double.IsNegativeInfinity(v.X) && !double.IsPositiveInfinity(v.Y) && !double.IsNegativeInfinity(v.Y); }
public void Update() { double elapsed = (DateTime.Now - st).TotalMilliseconds; //dir = Vector2d.Normalize(To - From); //position = From + ((elapsed * Speed) * dir); position = P.GetPosition(elapsed, Speed); }
public Vector2d TransformToRelative(Vector2d absoluteCoordinate) { var x = absoluteCoordinate.X / Interface.Width * 2 - 1; var y = (Interface.Height - absoluteCoordinate.Y) / Interface.Height * 2 - 1; return new Vector2d(x, y); }
public override void Simulate() { if (TargetReached == false) { sqrMag = TargetRotation.SqrMagnitude (); if (sqrMag != 0) { sideCheck1 = Body.Rotation.Cross (TargetRotation.x, TargetRotation.y); if (sideCheck1 != 0) { tempVec = Body.Rotation.rotatedRight (); if (sideCheck1 < 0) { Body.Rotation.Lerp (tempVec.x, tempVec.y, timescaledTurnRate); } else { Body.Rotation.Lerp (-tempVec.x, -tempVec.y, timescaledTurnRate); } tempVec = Body.Rotation.rotatedRight (); sideCheck2 = Body.Rotation.Cross (TargetRotation.x, TargetRotation.y); if (sideCheck2 != 0) { if (sideCheck2 > 0) { if (sideCheck1 < 0) { Body.Rotation = TargetRotation; TargetReached = true; Body.RotationChanged = true; return; } } else { if (sideCheck1 > 0) { Body.Rotation = TargetRotation; TargetReached = true; Body.RotationChanged = true; return; } } } Body.Rotation.Normalize (); Body.RotationChanged = true; } else { if (Body.Rotation.Dot (TargetRotation.x, TargetRotation.y) < 0) { tempVec = Body.Rotation.rotatedRight (); Body.Rotation.Lerp (tempVec.x, tempVec.y, TurnRate); Body.Rotation.Normalize (); Body.RotationChanged = true; } } } else { TargetReached = true; } } else { if ((TargetRotation.Cross (Body.Velocity.x, Body.Velocity.y)) != 0) { StartTurn (Body.Velocity); } } }
/* * Returns the square distance between the given point and the line * defined by this segment. * * @param p a point. */ public double LineDistSq(Vector2d p) { Vector2d ap = p - a; double dotprod = ab.Dot(ap); double projLenSq = dotprod * dotprod / ab.SqrMagnitude(); return ap.SqrMagnitude() - projLenSq; }
public Vector4d(Vector2d v, double z, double w) { x = v.x; y = v.y; this.z = z; this.w = w; }
/// <summary> /// Initializes a new instance of the <c>LightWeightPolylineVertex</c> class. /// </summary> public LightWeightPolylineVertex() { this.location = Vector2d.Zero; this.bulge = 0.0f; this.beginThickness = 0.0f; this.endThickness = 0.0f; }
internal double SmoothMesh() { double eps = 0; for (int n = 0; n < m_NumSmoothing; n++) //ripeto Num volte lo smoothing { eps = 0; for (int i = 0; i < m_ArrayVertexes.Count; i++) { // ciclo per tutti i punti interni al dominio AM_Vertex vertex = m_ArrayVertexes[i]; // Versione corretta (AC 16-01-03) // Algoritmo di Optimal Smoothing (Borouchaki-George IJNME vol.40) if (vertex.Flag == 0) // E' un punto smoothabile { Point2d p0 = vertex.Coord; Point2d center = Point2d.Unset; int degree = (int)vertex.Degree(true); if (degree < 2) { continue; } AM_Edge start = vertex.Edge; AM_Edge nextEdge = start; Point2d newCoord = Point2d.Unset; double oldQuality = double.MaxValue; // Valuta la qualità dei triangoli prima dello spostamento // e calcola il nuovo centro for (int j = 0; j < degree; j++) { Debug.Assert(nextEdge.CcwFace() != null); Point2d p1 = nextEdge.DestCoord(); Point2d p2 = nextEdge.Next.DestCoord(); // Punto del teorico triangolo equilatero di p1-p2 Vector2d v = p2 - p1; Point2d mp = 0.5 * (p1 + p2); Point2d np = mp + Math.Sqrt(3d) * v.Length * AM_Util.NormalVersor(v); newCoord += np; double inRadius = 0; double circumRadius = 0; AM_Util.CircumCircle(p0, p1, p2, ref center, ref circumRadius); AM_Util.InCircle(p0, p1, p2, ref center, ref inRadius); double sgnArea = AM_Util.TriArea(p0, p1, p2) > 0 ? 1 : -1; double quality = sgnArea * inRadius / circumRadius; oldQuality = Math.Min(oldQuality, quality); nextEdge = nextEdge.Next; } Debug.Assert(nextEdge == start); newCoord.X /= degree; newCoord.Y /= degree; // Controlla l'accettabilità del nuovo centro double newQuality = double.MaxValue; for (int j = 0; j < degree; j++) { Debug.Assert(nextEdge.CcwFace() != null); Point2d p1 = nextEdge.DestCoord(); Point2d p2 = nextEdge.Next.DestCoord(); double inRadius = 0; double circumRadius = 0; AM_Util.CircumCircle(newCoord, p1, p2, ref center, ref circumRadius); AM_Util.InCircle(newCoord, p1, p2, ref center, ref inRadius); double sgnArea = AM_Util.TriArea(newCoord, p1, p2) > 0? 1 : -1; double quality = sgnArea * inRadius / circumRadius; newQuality = Math.Min(quality, newQuality); nextEdge = nextEdge.Next; } Debug.Assert(nextEdge == start); if (newQuality > 0 && newQuality > oldQuality) { // La qualità viene migliorata, il vertice viene spostato eps += (newCoord - p0).Length; vertex.Coord = newCoord; } } } } return(eps); }
public static bool Intersects(Vector2d a1, Vector2d a2, Vector2d b1, Vector2d b2) { Vector2d p; return(Intersects(a1, a2, b1, b2, out p)); }
public virtual void SetCenterMercator(Vector2d centerMercator) { _centerMercator = centerMercator; }
/// <summary> /// Queries the real world elevation data in Unity units at a given latitude longitude. /// </summary> /// <returns>The height data.</returns> /// <param name="latlong">Latlong.</param> public virtual float QueryElevationInUnityUnitsAt(Vector2d latlong) { float tileScale = 1f; return(QueryElevationAtInternal(latlong, out tileScale)); }
public virtual bool offset(Vector2d vec, int segment) { bool ret = (SwigDerivedClassHasMethod("offset", swigMethodTypes32) ? touchvgPINVOKE.MgBaseShape_offsetSwigExplicitMgBaseShape(swigCPtr, Vector2d.getCPtr(vec), segment) : touchvgPINVOKE.MgBaseShape_offset(swigCPtr, Vector2d.getCPtr(vec), segment)); if (touchvgPINVOKE.SWIGPendingException.Pending) { throw touchvgPINVOKE.SWIGPendingException.Retrieve(); } return(ret); }
public static void DistanceSquared2D_Theory(Vector256 <double> left, Vector256 <double> right, Vector2d expected) { Vector256 <double> result = Vector.DistanceSquared2D(left, right); Assert.True(TestHelpers.AreEqual(expected, result), $"Expected {expected}, got {result}"); }
public override void Run(VectorFeatureUnity feature, MeshData md, UnityTile tile = null) { if (md.Vertices.Count == 0 || feature == null || feature.Points.Count < 1) { return; } _uv.Clear(); _mdVertexCount = md.Vertices.Count; _size = md.TileRect.Size; if (_options.texturingType != UvMapType.Atlas && _options.texturingType != UvMapType.AtlasWithColorPalette) { for (int i = 0; i < _mdVertexCount; i++) { _vert = md.Vertices[i]; if (_options.style == StyleTypes.Satellite) { var fromBottomLeft = new Vector2((float)(((_vert.x + md.PositionInTile.x) / tile.TileScale + _size.x / 2) / _size.x), (float)(((_vert.z + md.PositionInTile.z) / tile.TileScale + _size.x / 2) / _size.x)); _uv.Add(fromBottomLeft); } else if (_options.texturingType == UvMapType.Tiled) { _uv.Add(new Vector2(_vert.x, _vert.z)); } } } else if (_options.texturingType == UvMapType.Atlas || _options.texturingType == UvMapType.AtlasWithColorPalette) { _currentFacade = _options.atlasInfo.Roofs[UnityEngine.Random.Range(0, _options.atlasInfo.Roofs.Count)]; minx = float.MaxValue; miny = float.MaxValue; maxx = float.MinValue; maxy = float.MinValue; _textureUvCoordinates = new Vector2[_mdVertexCount]; _textureDirection = Quaternion.FromToRotation((md.Vertices[0] - md.Vertices[1]), Mapbox.Unity.Constants.Math.Vector3Right); _textureUvCoordinates[0] = new Vector2(0, 0); _firstVert = md.Vertices[0]; for (int i = 1; i < _mdVertexCount; i++) { _vert = md.Vertices[i]; _vertexRelativePos = _vert - _firstVert; _vertexRelativePos = _textureDirection * _vertexRelativePos; _textureUvCoordinates[i] = new Vector2(_vertexRelativePos.x, _vertexRelativePos.z); if (_vertexRelativePos.x < minx) { minx = _vertexRelativePos.x; } if (_vertexRelativePos.x > maxx) { maxx = _vertexRelativePos.x; } if (_vertexRelativePos.z < miny) { miny = _vertexRelativePos.z; } if (_vertexRelativePos.z > maxy) { maxy = _vertexRelativePos.z; } } var width = maxx - minx; var height = maxy - miny; for (int i = 0; i < _mdVertexCount; i++) { _uv.Add(new Vector2( (((_textureUvCoordinates[i].x - minx) / width) * _currentFacade.TextureRect.width) + _currentFacade.TextureRect.x, (((_textureUvCoordinates[i].y - miny) / height) * _currentFacade.TextureRect.height) + _currentFacade.TextureRect.y)); } } md.UV[0].AddRange(_uv); }
public static bool Intersects(Vector2d a1, Vector2d a2, Vector2d b1, Vector2d b2, out Vector2d intersection) { intersection = new Vector2d(0, 0); Vector2d b = a2 - a1; Vector2d d = b2 - b1; double bDotDPerp = b.X * d.Y - b.Y * d.X; // if b dot d == 0, it means the lines are parallel so have infinite intersection points if (Math.Abs(bDotDPerp) < double.Epsilon) { return(false); } Vector2d c = b1 - a1; double t = (c.X * d.Y - c.Y * d.X) / bDotDPerp; if (t < 0 || t > 1) { return(false); } double u = (c.X * b.Y - c.Y * b.X) / bDotDPerp; if (u < 0 || u > 1) { return(false); } intersection = a1 + t * b; return(true); }
public Vector2d getEndTangent() { Vector2d ret = new Vector2d(touchvgPINVOKE.MgPath_getEndTangent(swigCPtr), true); return(ret); }
public Line(Vector2d p1, Vector2d p2) { Position = p1; Position2 = p2; }
/// <summary> /// Computes the Euclidean distance between this vector and another vector /// </summary> /// <param name="a">This vector</param> /// <param name="b">The other vector</param> /// <returns>The Euclidean distance between the two vectors.</returns> public static double Distance(this Vector2d a, Vector2d b) { return((b - a).Length); }
/// <summary> /// Computes the cross product of the current vector with another vector. /// </summary> /// <param name="a">The current vector</param> /// <param name="b">The other vector</param> /// <returns>The result of the cross product</returns> public static double Cross(this Vector2d a, Vector2d b) { return(a.X * b.Y - a.Y * b.X); }
private void ScaleSelection(Vector2d pos) { if (_selection.Count > 0) { _movemade = true; var movediff = (pos - _clickstart); if (UI.InputUtils.CheckPressed(UI.Hotkey.ToolScaleAspectRatio)) { if (_nodeleft == _nodetop) { movediff.Y = movediff.X * (_boxstart.Height / _boxstart.Width); } else { movediff.Y = -(movediff.X * (_boxstart.Height / _boxstart.Width)); } } using (var trk = game.Track.CreateTrackWriter()) { trk.DisableUndo(); foreach (var selected in _selection) { var scalar1 = Vector2d.Divide( selected.clone.Position - _startselectionedges.Vector, _startselectionedges.Size); var scalar2 = Vector2d.Divide( selected.clone.Position2 - _startselectionedges.Vector, _startselectionedges.Size); if (_nodetop) { scalar1.Y = 1 - scalar1.Y; scalar2.Y = 1 - scalar2.Y; } if (_nodeleft) { scalar1.X = 1 - scalar1.X; scalar2.X = 1 - scalar2.X; } if (_startselectionedges.Size.X == 0) { scalar1.X = 0; scalar2.X = 0; } if (_startselectionedges.Size.Y == 0) { scalar1.Y = 0; scalar2.Y = 0; } var p1 = Vector2d.Multiply(scalar1, movediff); var p2 = Vector2d.Multiply(scalar2, movediff); trk.MoveLine( selected.line, selected.clone.Position + p1, selected.clone.Position2 + p2); } _selectionbox = GetBoxFromSelected(_selection); game.Track.NotifyTrackChanged(); } } game.Invalidate(); }
public override void OnMouseUp(Vector2d pos) { DropLine(); UpdateHoverline(ScreenToGameCoords(pos)); base.OnMouseUp(pos); }
/// <summary> /// /// </summary> /// <param name="tileLocation">x,y location</param> /// <param name="floor">Floor you go to when moved onto</param> /// <param name="nextFloorTile"></param> public StairTile(Vector2d tileLocation, int floor, ITileBase nextFloorTile) : base(tileLocation) { _nextFloorValue = floor; _nextFloorTile = nextFloorTile; }
private void StartAddSelection(Vector2d gamepos) { _movingselection = false; _drawbox = new DoubleRect(gamepos, Vector2d.Zero); _drawingbox = true; }
/// <summary> /// Дуга в плоскости (x, y). Точка начала дуги - a, точка конца дуги - b /// </summary> /// <param name="a">начало дуги</param> /// <param name="b">конец дуги</param> public Arc(Vector2d a, Vector2d b, Vector2d cp, bool direction) { //init _endPoint = new ArrayHelper <Vector2d>(2); _CP = new Vector2d(0, 0); _Direction = false; _R = 0; _Theta = 0; _ThetaZero = 0; _length = 0; _vDirect = new Vector2d(0, 0); _vDirectNorm = new Vector2d(0, 0); _IsClosed = false; _endPoint[true] = a; _endPoint[false] = b; _CP = cp; _Direction = direction; if (_Direction) { _DirectionInt = 1; } else { _DirectionInt = -1; } _R = (_endPoint[true] - _CP).Length();//?? точно ли до точки b будет тот же радиус?? if (_R == 0) { return; } _Theta = Angle_V1_v2(_endPoint[true] - _CP, _endPoint[false] - _CP); if (_DirectionInt * Sign(_Theta) < 0) { _Theta = 2 * PI - Abs(_Theta); } _Theta = _DirectionInt * Abs(_Theta); _ThetaZero = Angle_V1_v2(X2dAxes, _endPoint[true] - _CP); if (Equal_V1_V2(_endPoint[true], _endPoint[false])) { _Theta = 2 * PI * _DirectionInt; _IsClosed = true; } else { _IsClosed = false; } _length = _R * Abs(_Theta); _vDirect = _endPoint[false] - _endPoint[true]; _vDirectNorm = _vDirect; _vDirectNorm.Norm(); }
public void Print(string text, Vector2d position) { Print(text, position, Color.Transparent); }
public virtual bool ClickCheckScreenSpace(Vector2d cursor) { return(false); }
/// <summary> /// Получить центр дуги cp по двум точкам (a и b), знаковому радиусу R: R>0 дуга < PI, R<0 дуга > PI /// и направлению дуги direction: true - против ЧС /// </summary> public static bool GetCP_FromArc(Vector2d a, Vector2d b, double R, bool direction, out Vector2d cp) { bool res = false; cp = new Vector2d(0, 0); if (R == 0) { return(res); } int directionInt; if (direction) { directionInt = 1; } else { directionInt = -1; } Vector2d d = b - a; //хорда дуги if (d.isZero()) { d = 2 * Abs(R) * X2dAxes; //Полная окружность } Vector2d h; if (directionInt * R < 0) { h = d.NormR(); } else { h = d.NormL(); } h.Norm(); double H_LengthSqr = Pow(R, 2) - Pow((d.Length() / 2), 2); if (H_LengthSqr < 0) { return(res); } h = (Sqrt(H_LengthSqr)) * h;//выставляем длину вектора h cp = a + 0.5 * d + h; res = true; return(res); }
public static void test_uv_insert_segment() { DMesh3 mesh = TestUtil.LoadTestInputMesh("plane_250v.obj"); mesh.EnableVertexUVs(Vector2f.Zero); MeshTransforms.ConvertYUpToZUp(mesh); DMeshAABBTree3 spatial = new DMeshAABBTree3(mesh); spatial.Build(); int tid = spatial.FindNearestTriangle(Vector3d.Zero); //Polygon2d poly = Polygon2d.MakeRectangle(Vector2d.Zero, 5, 5); Polygon2d poly = Polygon2d.MakeCircle(5, 13); //PolyLine2d poly = new PolyLine2d( new Vector2d[] { -5 * Vector2d.One, 5 * Vector2d.One }); //int tri_edge0 = mesh.GetTriEdge(tid, 0); //Index2i edge0_tris = mesh.GetEdgeT(tri_edge0); //Index2i edge0_verts = mesh.GetEdgeV(tri_edge0); //Vector3d v0 = mesh.GetVertex(edge0_verts.a), v1 = mesh.GetVertex(edge0_verts.b); //Vector3d c = mesh.GetTriCentroid(tid); //Polygon2d poly = new Polygon2d(new Vector2d[] { // Vector2d.Lerp(v0.xy, v1.xy, -0.25), // Vector2d.Lerp(v0.xy, v1.xy, 1.5), // c.xy //}); MeshInsertUVPolyCurve insert = new MeshInsertUVPolyCurve(mesh, poly); insert.Apply(); Polygon2d test_poly = new Polygon2d(); List <double> distances = new List <double>(); List <int> nearests = new List <int>(); for (int i = 0; i < insert.Loops[0].VertexCount; ++i) { Vector2d v = mesh.GetVertex(insert.Loops[0].Vertices[i]).xy; test_poly.AppendVertex(v); int iNear; double fNear; distances.Add(poly.DistanceSquared(v, out iNear, out fNear)); nearests.Add(iNear); } System.Console.WriteLine("inserted loop poly has {0} edges", insert.Loops[0].EdgeCount); // find a triangle connected to loop that is inside the polygon // [TODO] maybe we could be a bit more robust about this? at least // check if triangle is too degenerate... int seed_tri = -1; for (int i = 0; i < insert.Loops[0].EdgeCount; ++i) { Index2i et = mesh.GetEdgeT(insert.Loops[0].Edges[i]); Vector3d ca = mesh.GetTriCentroid(et.a); bool in_a = poly.Contains(ca.xy); Vector3d cb = mesh.GetTriCentroid(et.b); bool in_b = poly.Contains(cb.xy); if (in_a && in_b == false) { seed_tri = et.a; break; } else if (in_b && in_a == false) { seed_tri = et.b; break; } } Util.gDevAssert(seed_tri != -1); // flood-fill inside loop HashSet <int> loopEdges = new HashSet <int>(insert.Loops[0].Edges); MeshFaceSelection sel = new MeshFaceSelection(mesh); sel.FloodFill(seed_tri, null, (eid) => { return(loopEdges.Contains(eid) == false); }); // delete inside loop MeshEditor editor = new MeshEditor(mesh); editor.RemoveTriangles(sel, true); MeshTransforms.ConvertZUpToYUp(mesh); TestUtil.WriteTestOutputMesh(mesh, "insert_uv_segment.obj"); //OBJWriter writer = new OBJWriter(); //var s = new System.IO.StreamWriter(Program.TEST_OUTPUT_PATH + "mesh_local_param.obj", false); //List<WriteMesh> wm = new List<WriteMesh>() { new WriteMesh(mesh) }; //WriteOptions opt = new WriteOptions() { // bCombineMeshes = false, bWriteGroups = false, bPerVertexColors = true, bPerVertexUVs = true, // AsciiHeaderFunc = () => { return "mttllib checkerboard.mtl\r\nusemtl checkerboard\r\n"; } //}; //writer.Write(s, wm, opt); //s.Close(); }
public static void test_uv_insert_string() { DMesh3 mesh = TestUtil.LoadTestInputMesh("plane_xy_25x25.obj"); mesh.EnableVertexUVs(Vector2f.Zero); DMeshAABBTree3 spatial = new DMeshAABBTree3(mesh); spatial.Build(); int tid = spatial.FindNearestTriangle(Vector3d.Zero); PolygonFont2d font = PolygonFont2d.ReadFont("c:\\scratch\\font.bin"); //List<GeneralPolygon2d> letter = new List<GeneralPolygon2d>(font.Characters.First().Value.Polygons); //double targetWidth = 20.0f; List <GeneralPolygon2d> letter = font.GetCharacter('a'); double targetWidth = 10.0f; AxisAlignedBox2d bounds = font.MaxBounds; Vector2d center = bounds.Center; Vector2d scale2d = (targetWidth / font.MaxBounds.Width) * new Vector2d(1, 1); for (int li = 0; li < letter.Count; ++li) { GeneralPolygon2d gp = new GeneralPolygon2d(letter[li]); gp.Scale(scale2d, center); gp.Translate(-center); letter[li] = gp; } List <MeshFaceSelection> letter_interiors = new List <MeshFaceSelection>(); bool bSimplify = true; for (int li = 0; li < letter.Count; ++li) { GeneralPolygon2d gp = letter[li]; MeshInsertUVPolyCurve outer = new MeshInsertUVPolyCurve(mesh, gp.Outer); Util.gDevAssert(outer.Validate() == ValidationStatus.Ok); outer.Apply(); if (bSimplify) { outer.Simplify(); } List <MeshInsertUVPolyCurve> holes = new List <MeshInsertUVPolyCurve>(gp.Holes.Count); for (int hi = 0; hi < gp.Holes.Count; ++hi) { MeshInsertUVPolyCurve insert = new MeshInsertUVPolyCurve(mesh, gp.Holes[hi]); Util.gDevAssert(insert.Validate() == ValidationStatus.Ok); insert.Apply(); if (bSimplify) { insert.Simplify(); } holes.Add(insert); } // find a triangle connected to loop that is inside the polygon // [TODO] maybe we could be a bit more robust about this? at least // check if triangle is too degenerate... int seed_tri = -1; EdgeLoop outer_loop = outer.Loops[0]; for (int i = 0; i < outer_loop.EdgeCount; ++i) { if (!mesh.IsEdge(outer_loop.Edges[i])) { continue; } Index2i et = mesh.GetEdgeT(outer_loop.Edges[i]); Vector3d ca = mesh.GetTriCentroid(et.a); bool in_a = gp.Outer.Contains(ca.xy); Vector3d cb = mesh.GetTriCentroid(et.b); bool in_b = gp.Outer.Contains(cb.xy); if (in_a && in_b == false) { seed_tri = et.a; break; } else if (in_b && in_a == false) { seed_tri = et.b; break; } } Util.gDevAssert(seed_tri != -1); // make list of all outer & hole edges HashSet <int> loopEdges = new HashSet <int>(outer_loop.Edges); foreach (var insertion in holes) { foreach (int eid in insertion.Loops[0].Edges) { loopEdges.Add(eid); } } // flood-fill inside loop from seed triangle MeshFaceSelection sel = new MeshFaceSelection(mesh); sel.FloodFill(seed_tri, null, (eid) => { return(loopEdges.Contains(eid) == false); }); letter_interiors.Add(sel); } // extrude regions Func <Vector3d, Vector3f, int, Vector3d> OffsetF = (v, n, i) => { return(v + Vector3d.AxisZ); }; foreach (var interior in letter_interiors) { MeshExtrudeFaces extrude = new MeshExtrudeFaces(mesh, interior); extrude.ExtrudedPositionF = OffsetF; extrude.Extrude(); } TestUtil.WriteTestOutputMesh(mesh, "insert_uv_string.obj"); }
void SetGPSFromSensor() { // textInfo.text = cntFramesFPS + " " + Input.location.lastData.latitude + ", " + Input.location.lastData.longitude; gps = new Vector2d(Input.location.lastData.latitude, Input.location.lastData.longitude); }
public string LatLonToString(Vector2d latLon) { string txt = latLon.x.ToString("F6") + ", " + latLon.y.ToString("F6"); return(txt); }
public virtual void SetCenterLatitudeLongitude(Vector2d centerLatitudeLongitude) { _options.locationOptions.latitudeLongitude = string.Format("{0}, {1}", centerLatitudeLongitude.x, centerLatitudeLongitude.y); _centerLatitudeLongitude = centerLatitudeLongitude; }
string latLonToString(Vector2d latLon) { return(latLon.x.ToString("F6") + ", " + latLon.y.ToString("F6")); }
public SceneryLine(Vector2d p1, Vector2d p2) { Position = p1; Position2 = p2; }
/// <summary> /// Initializes the map using the mapOptions. /// </summary> /// <param name="options">Options.</param> protected virtual void InitializeMap(MapOptions options) { Options = options; _worldHeightFixed = false; _fileSource = MapboxAccess.Instance; //_centerLatitudeLongitude = Conversions.StringToLatLon(options.locationOptions.latitudeLongitude); _centerLatitudeLongitude = Conversions.StringToLatLon(MapReader.bounds.BuildingCentre); _initialZoom = (int)options.locationOptions.zoom; options.scalingOptions.scalingStrategy.SetUpScaling(this); options.placementOptions.placementStrategy.SetUpPlacement(this); //Set up events for changes. _imagery.UpdateLayer += OnImageOrTerrainUpdateLayer; _terrain.UpdateLayer += OnImageOrTerrainUpdateLayer; _vectorData.SubLayerRemoved += OnVectorDataSubLayerRemoved; _vectorData.SubLayerAdded += OnVectorDataSubLayerAdded; _vectorData.UpdateLayer += OnVectorDataUpdateLayer; _options.locationOptions.PropertyHasChanged += (object sender, System.EventArgs eventArgs) => { UpdateMap(); }; _options.extentOptions.PropertyHasChanged += (object sender, System.EventArgs eventArgs) => { OnTileProviderChanged(); }; _options.extentOptions.defaultExtents.PropertyHasChanged += (object sender, System.EventArgs eventArgs) => { if (Application.isEditor && !Application.isPlaying && IsEditorPreviewEnabled == false) { Debug.Log("defaultExtents"); return; } if (TileProvider != null) { TileProvider.UpdateTileExtent(); } }; _options.placementOptions.PropertyHasChanged += (object sender, System.EventArgs eventArgs) => { SetPlacementStrategy(); UpdateMap(); }; _options.scalingOptions.PropertyHasChanged += (object sender, System.EventArgs eventArgs) => { SetScalingStrategy(); UpdateMap(); }; _mapVisualizer.Initialize(this, _fileSource); TileProvider.Initialize(this); SendInitialized(); TileProvider.UpdateTileExtent(); }
public virtual void UpdateMap(Vector2d latLon) { UpdateMap(latLon, Zoom); }
public Sceen(StarSystem a_oStarSystem, GLEffect a_oDefaultEffect, Pulsar4X.UI.Handlers.SystemMap ParentSM) { // set member vars: m_v3ViewOffset = Vector3.Zero; MeasureMode = false; ParentSystemMap = ParentSM; SceenDefaultEffect = a_oDefaultEffect; // Set Sceen Vars: m_oSceenEntity = a_oStarSystem; SceenID = a_oStarSystem.Id; // Create measurement element: m_oMeasurementElement = new MeasurementElement(); m_oMeasurementElement.PrimaryPrimitive = new GLLine(a_oDefaultEffect, Vector3.Zero, new Vector2(1.0f, 1.0f), Color.Yellow, UIConstants.Textures.DEFAULT_TEXTURE); m_oMeasurementElement.AddPrimitive(m_oMeasurementElement.PrimaryPrimitive); m_oMeasurementElement.Lable = new GLUtilities.GLFont(a_oDefaultEffect, Vector3.Zero, UIConstants.DEFAULT_TEXT_SIZE, Color.Yellow, UIConstants.Textures.DEFAULT_GLFONT2, ""); // Creat Working Vars: //double dKMperAUdevby10 = (Pulsar4X.Constants.Units.KM_PER_AU / 10); // we scale everthing down by 10 to avoid float buffer overflows. int iStarCounter = 0; // Keeps track of the number of stars. int iPlanetCounter = 0; // Keeps track of the number of planets around the current star int iMoonCounter = 0; // Keeps track of the number of moons around the current planet. double dMaxOrbitDist = 0; // used for fit to zoom. Vector3 v3StarPos = new Vector3(0, 0, 0); // used for storing the psoition of the current star in the system float fStarSize = 0.0f; // Size of a star double dPlanetOrbitRadius = 0; // used for holding the orbit in Km for a planet. Vector3 v3PlanetPos = new Vector3(0, 0, 0); // Used to store the planet Pos. float fPlanetSize = 0; // used to hold the planets size. double dMoonOrbitRadius = 0; // used for holding the orbit in Km for a Moon. float fMoonSize = 0; // used to hold the Moons size. Vector3 v3MoonPos = Vector3.Zero; // Used to store the Moons Position. // start creating star branches in the sceen graph: SceenElement oRootStar; SceenElement oCurrStar; foreach (Pulsar4X.Entities.Star oStar in a_oStarSystem.Stars) { if (iStarCounter <= 0) { // then we have a secondary, etc star give random position around its orbit! oRootStar = new StarElement(oStar, a_oDefaultEffect, Vector3.Zero, Pulsar4X.Constants.StarColor.LookupColor(oStar.Class), true); oCurrStar = oRootStar; } else { Random rnd = new Random(); //float fAngle = 0.0f; // rnd.Next(0, 360); //fAngle = MathHelper.DegreesToRadians(fAngle); // double x, y; Pulsar4X.Lib.OrbitTable.Instance.UpdatePosition(oStar, 0); v3StarPos.X = (float)(oStar.Position.X); //(float)(Math.Cos(fAngle) * oStar.SemiMajorAxis * dKMperAUdevby10); v3StarPos.Y = (float)(oStar.Position.Y); //(float)(Math.Sin(fAngle) * oStar.SemiMajorAxis * dKMperAUdevby10); MaxOrbitDistTest(ref dMaxOrbitDist, oStar.SemiMajorAxis); oCurrStar = new StarElement(oStar, a_oDefaultEffect, v3StarPos, Pulsar4X.Constants.StarColor.LookupColor(oStar.Class), false); // create orbit circle /*GLUtilities.GLCircle oStarOrbitCirc = new GLUtilities.GLCircle(a_oDefaultEffect, * Vector3.Zero, // base around parent star pos. * oStar, //(float)(oStar.SemiMajorAxis * dKMperAUdevby10) / 2, * Pulsar4X.Constants.StarColor.LookupColor(oStar.Class), * UIConstants.Textures.DEFAULT_TEXTURE); * oCurrStar.AddPrimitive(oStarOrbitCirc);*/ } fStarSize = (float)(oStar.Radius * 2.0 * (Constants.Units.SOLAR_RADIUS_IN_AU)); GLUtilities.GLQuad oStarQuad = new GLUtilities.GLQuad(a_oDefaultEffect, v3StarPos, new Vector2(fStarSize, fStarSize), Pulsar4X.Constants.StarColor.LookupColor(oStar.Class), UIConstants.Textures.DEFAULT_PLANET_ICON); // create name lable: GLUtilities.GLFont oNameLable = new GLUtilities.GLFont(a_oDefaultEffect, new Vector3((float)(v3StarPos.X), (float)(v3StarPos.Y - (oStar.Radius / Constants.Units.KM_PER_AU)), 0), UIConstants.DEFAULT_TEXT_SIZE, Color.White, UIConstants.Textures.DEFAULT_GLFONT2, oStar.Name); oCurrStar.AddPrimitive(oStarQuad); // Add star icon to the Sceen element. oCurrStar.Lable = oNameLable; oCurrStar.PrimaryPrimitive = oStarQuad; oCurrStar.RealSize = new Vector2(fStarSize, fStarSize); this.AddElement(oCurrStar); // now go though and add each planet to render list. foreach (Pulsar4X.Entities.Planet oPlanet in oStar.Planets) { SceenElement oPlanetElement = new PlanetElement(a_oDefaultEffect, v3StarPos, oPlanet, Color.FromArgb(255, 0, 205, 0)); oPlanetElement.EntityID = oPlanet.Id; if (iPlanetCounter == 0) { oCurrStar.SmallestOrbit = (float)(oPlanet.SemiMajorAxis * 2); } dPlanetOrbitRadius = oPlanet.SemiMajorAxis; Pulsar4X.Lib.OrbitTable.Instance.UpdatePosition(oPlanet, 0); v3PlanetPos = new Vector3((float)(oPlanet.Position.X), (float)(oPlanet.Position.Y), 0) + v3StarPos; // offset Pos by parent star pos oPlanet.Position.X = oPlanet.Position.X + v3StarPos.X; oPlanet.Position.Y = oPlanet.Position.Y + v3StarPos.Y; fPlanetSize = (float)((oPlanet.Radius * 2.0) / Constants.Units.KM_PER_AU); MaxOrbitDistTest(ref dMaxOrbitDist, dPlanetOrbitRadius); GLUtilities.GLQuad oPlanetQuad = new GLUtilities.GLQuad(a_oDefaultEffect, v3PlanetPos, new Vector2(fPlanetSize, fPlanetSize), Color.FromArgb(255, 0, 255, 0), // lime green UIConstants.Textures.DEFAULT_PLANET_ICON); /*GLUtilities.GLCircle oPlanetOrbitCirc = new GLUtilities.GLCircle(a_oDefaultEffect, * v3StarPos, // base around parent star pos. * oPlanet, //(float)dPlanetOrbitRadius / 2, * Color.FromArgb(255, 0, 205, 0), // lime green * UIConstants.Textures.DEFAULT_TEXTURE);*/ // create name lable: GLUtilities.GLFont oPlanetNameLable = new GLUtilities.GLFont(a_oDefaultEffect, new Vector3((float)(v3PlanetPos.X), (float)(v3PlanetPos.Y - (oPlanet.Radius / Constants.Units.KM_PER_AU)), 0), UIConstants.DEFAULT_TEXT_SIZE, Color.AntiqueWhite, UIConstants.Textures.DEFAULT_GLFONT2, oPlanet.Name); oPlanetElement.AddPrimitive(oPlanetQuad); //oPlanetElement.AddPrimitive(oPlanetOrbitCirc); oPlanetElement.Lable = oPlanetNameLable; oPlanetElement.PrimaryPrimitive = oPlanetQuad; oPlanetElement.RealSize = new Vector2(fPlanetSize, fPlanetSize); oCurrStar.AddChildElement(oPlanetElement); iPlanetCounter++; // now again for the moons: foreach (Pulsar4X.Entities.Planet oMoon in oPlanet.Moons) { SceenElement oMoonElement = new PlanetElement(a_oDefaultEffect, v3PlanetPos, oMoon, Color.FromArgb(255, 0, 205, 0)); oMoonElement.EntityID = oMoon.Id; if (iMoonCounter == 0) { oPlanetElement.SmallestOrbit = (float)(oMoon.SemiMajorAxis); } dMoonOrbitRadius = oMoon.SemiMajorAxis; Pulsar4X.Lib.OrbitTable.Instance.UpdatePosition(oMoon, 0); fMoonSize = (float)((oMoon.Radius * 2.0) / Constants.Units.KM_PER_AU); v3MoonPos = new Vector3((float)(oMoon.Position.X), (float)(oMoon.Position.Y), 0) + v3PlanetPos; oMoon.Position.X = oMoon.Position.X + v3PlanetPos.X; oMoon.Position.Y = oMoon.Position.Y + v3PlanetPos.Y; GLUtilities.GLQuad oMoonQuad = new GLUtilities.GLQuad(a_oDefaultEffect, v3MoonPos, // offset Pos by parent planet pos new Vector2(fMoonSize, fMoonSize), Color.FromArgb(255, 0, 205, 0), // lime green UIConstants.Textures.DEFAULT_PLANET_ICON); /*GLUtilities.GLCircle oMoonOrbitCirc = new GLUtilities.GLCircle(a_oDefaultEffect, * v3PlanetPos, // base around parent planet pos. * oMoon, //(float)dMoonOrbitRadius / 2, * Color.FromArgb(255, 0, 205, 0), // lime green * UIConstants.Textures.DEFAULT_TEXTURE);*/ GLUtilities.GLFont oMoonNameLable = new GLUtilities.GLFont(a_oDefaultEffect, new Vector3((float)(v3MoonPos.X), (float)(v3MoonPos.Y - (oMoon.Radius / Constants.Units.KM_PER_AU)), 0), UIConstants.DEFAULT_TEXT_SIZE, Color.AntiqueWhite, UIConstants.Textures.DEFAULT_GLFONT2, oMoon.Name); oMoonElement.AddPrimitive(oMoonQuad); //oMoonElement.AddPrimitive(oMoonOrbitCirc); oMoonElement.Lable = oMoonNameLable; oMoonElement.PrimaryPrimitive = oMoonQuad; oMoonElement.RealSize = new Vector2(fMoonSize, fMoonSize); oPlanetElement.AddChildElement(oMoonElement); iMoonCounter++; } iMoonCounter = 0; } iPlanetCounter = 0; foreach (Pulsar4X.Entities.JumpPoint oJumpPoint in a_oStarSystem.JumpPoints) { CreateJumpPoint(oCurrStar, oJumpPoint); } iStarCounter++; } foreach (Pulsar4X.Entities.SystemContact systemContact in a_oStarSystem.SystemContactList) { AddContactElement(SceenDefaultEffect, systemContact); } a_oStarSystem.JumpPoints.ListChanged += JumpPoints_ListChanged; a_oStarSystem.SystemContactList.ListChanging += SystemContactList_ListChanging; // Set Sceen Size basd on Max Orbit: m_v2SceenSize = new Vector2d(dMaxOrbitDist * 2, dMaxOrbitDist * 2); }