public AnimatedModelLayer(Game engine, DVector2 lonLat, string fileName, int maxInstanceCount = 0) : base(engine, lonLat, fileName, maxInstanceCount) { localMatrices = new Matrix[model.Nodes.Count]; firstFrame = model.FirstFrame; lastFrame = model.LastFrame; }
void AddBuildingContour(DVector2[] contourPoints, Color color) { if (contourPoints.Length < 3) return; var firstInd = contourBuildingsList.Count; //write first two contourBuildingsList.Add(new GeoVert { Lon = DMathUtil.DegreesToRadians(contourPoints[0].X), Lat = DMathUtil.DegreesToRadians(contourPoints[0].Y), Color = color }); contourBuildingsList.Add(new GeoVert { Lon = DMathUtil.DegreesToRadians(contourPoints[1].X), Lat = DMathUtil.DegreesToRadians(contourPoints[1].Y), Color = color }); for (int i = 1; i < contourPoints.Length-1; i++) { var prevInd = contourBuildingsList.Count-1; contourBuildingsList.Add(contourBuildingsList[prevInd]); contourBuildingsList.Add(new GeoVert { Lon = DMathUtil.DegreesToRadians(contourPoints[i+1].X), Lat = DMathUtil.DegreesToRadians(contourPoints[i+1].Y), Color = color }); } contourBuildingsList.Add(contourBuildingsList[contourBuildingsList.Count-1]); contourBuildingsList.Add(contourBuildingsList[firstInd]); }
public override DVector2 WorldToTilePos(double lon, double lat, int zoom) { DVector2 p = new DVector2(); p.X = (lon + 180.0) / 360.0 * (1 << zoom); p.Y = (1.0 - Math.Log(Math.Tan(lat * Math.PI / 180.0) + 1.0 / Math.Cos(lat * Math.PI / 180.0)) / Math.PI) / 2.0 * (1 << zoom); //p.Y = (1.0 - Math.Log((Math.Sin(lat * Math.PI / 180.0) + 1.0) / Math.Cos(lat * Math.PI / 180.0)) / Math.PI) / 2.0 * (1 << zoom); return p; }
/// <summary>Creates the circle texture.</summary> /// <param name="radius">The radius.</param> /// <param name="borderWidth">Width of the border.</param> /// <param name="borderInnerTransitionWidth">Width of the border inner transition.</param> /// <param name="borderOuterTransitionWidth">Width of the border outer transition.</param> /// <param name="color">The color.</param> /// <param name="borderColor">Color of the border.</param> /// <returns>A array with a representation of a circle inside.</returns> public static GUIColor[] CreateCircleTexture(int radius, int borderWidth, int borderInnerTransitionWidth, int borderOuterTransitionWidth, GUIColor color, GUIColor borderColor) { int x; var y = -1; var diameter = (radius + 2) * 2; // DVector2 center = new DVector2(0, 0); var center = new DVector2((diameter - 1) / 2f, (diameter - 1) / 2f); var colors = new GUIColor[diameter * diameter]; for (var i = 0; i < colors.Length; i++) { if (i % diameter == 0) { y += 1; } x = i % diameter; // var distance = new DVector2(Math.Abs(center.X - x), Math.Abs(center.Y - y)); var diff = new DVector2(x, y) - center; var length = diff.Length; // distance.Length(); if (length > radius) { colors[i] = GUIColor.Transparent(); } else if (length >= radius - borderOuterTransitionWidth) { var transitionAmount = (length - (radius - borderOuterTransitionWidth)) / borderOuterTransitionWidth; transitionAmount = 255 * (1 - transitionAmount); colors[i] = new GUIColor(borderColor.R, borderColor.G, borderColor.B, (byte)transitionAmount); } else if (length > radius - (borderWidth + borderOuterTransitionWidth)) { colors[i] = borderColor; } else if (length >= radius - (borderWidth + borderOuterTransitionWidth + borderInnerTransitionWidth)) { var transitionAmount = (length - (radius - (borderWidth + borderOuterTransitionWidth + borderInnerTransitionWidth))) / (borderInnerTransitionWidth + 1); colors[i] = new GUIColor( (byte)Lerp(color.R, borderColor.R, transitionAmount), (byte)Lerp(color.G, borderColor.G, transitionAmount), (byte)Lerp(color.B, borderColor.B, transitionAmount)); } else { colors[i] = color; } } return colors; }
public void DotsAddGeoObject(int objectClass, DVector2 lonLat, Color color, float size) { if (geoObjectOffset >= Dots.Length) return; Dots[geoObjectOffset++] = new GeoVert { Color = color, Lon = DMathUtil.DegreesToRadians(lonLat.X), Lat = DMathUtil.DegreesToRadians(lonLat.Y), Position = Vector3.Zero, Tex = new Vector4(objectClass, 0, size, 0) }; }
/// <summary> /// Called when graphics resources need to be loaded. /// Use this for the usage of : /// - creation of the internal embedded controls. /// - setting of the variables and resources in this control /// - to load any game-specific graphics resources /// - take over the config width and height and use it into State /// - overriding how this item looks like , by settings its texture or theme /// Call base.LoadContent before you do your override code, this will cause : /// - State.SourceRectangle to be reset to the Config.Size /// </summary> public override void LoadContent() { this.CurrentTextureName = this.Manager.ImageCompositor.CreateImageTexture(this.Name + "-Sizer", "Textures\\resizeicon"); this.textureSize = this.Manager.ImageCompositor.ReadSizeTexture(this.CurrentTextureName); this.Config.Width = this.textureSize.X; this.Config.Height = this.textureSize.Y; // do the basic stuff base.LoadContent(); this.UpdateDrawPositionByConfigAndParent(); this.UpdateDrawSizeByConfig(); }
/// <summary> /// Determines whether given location is inside the control. /// </summary> /// <param name="control">The control.</param> /// <param name="positionX">The positionX of the location.</param> /// <param name="positionY">The positionY of the location.</param> /// <returns>Whether the given location is inside.</returns> public static bool IsPointInside(this Control control, int positionX, int positionY) { #if DEBUG if (control == null) { throw new ArgumentNullException("control"); } #endif var absPos = new DVector2(control.State.DrawPosition.X, control.State.DrawPosition.Y); return absPos.X < positionX && positionX < (absPos.X + control.State.Width) && absPos.Y < positionY && positionY < (absPos.Y + control.State.Height); }
public static bool IsPointInPolygon(List<DVector2> boundaries, DVector2 pos) { int i = 0; int j = boundaries.Count - 1; bool oddNodes = false; for (i = 0; i < boundaries.Count; i++) { if ((boundaries[i].Y < pos.Y && boundaries[j].Y >= pos.Y || boundaries[j].Y < pos.Y && boundaries[i].Y >= pos.Y) && (boundaries[i].X <= pos.X || boundaries[j].X <= pos.X)) { oddNodes ^= (boundaries[i].X + (pos.Y - boundaries[i].Y) / (boundaries[j].Y - boundaries[i].Y) * (boundaries[j].X - boundaries[i].X) < pos.X); } j = i; } return oddNodes; }
/// <summary> /// Called when graphics resources need to be loaded. /// Use this for the usage of : /// - creation of the internal embedded controls. /// - setting of the variables and resources in this control /// - to load any game-specific graphics resources /// - take over the config width and height and use it into State /// - overriding how this item looks like , by settings its texture or theme /// Call base.LoadContent before you do your override code, this will cause : /// - State.SourceRectangle to be reset to the Config.Size /// </summary> public override void LoadContent() { // make the background this.CurrentTextureName = Manager.ImageCompositor.CreateImageTexture(this.Name + "-mouse cursor", "Textures\\Kcng6e9cq"); // CurrentTextureName = Manager.ImageCompositor.CreateRectangleColorMap(this.Name, (int)this.Config.Width, (int)this.Config.Height, 1,GUIColor.Gainsboro(), GUIColor.Wheat()); this.mouseCursorImageSize = Manager.ImageCompositor.ReadSizeTexture(this.CurrentTextureName); Config.Width = this.mouseCursorImageSize.X; Config.Height = this.mouseCursorImageSize.Y; // do the basic stuff base.LoadContent(); this.UpdateDrawPositionByConfigAndParent(); this.UpdateDrawSizeByConfig(); }
public void LinesPolyAdd(DVector2 lonLatPoint0, DVector2 lonLatPoint1, Color color, float width) { linesPolyBatchVertices.Add(new GeoVert { Lon = DMathUtil.DegreesToRadians(lonLatPoint0.X), Lat = DMathUtil.DegreesToRadians(lonLatPoint0.Y), Color = color, Position = new Vector3(), Tex = new Vector4(width, 0, 0, 0) }); linesPolyBatchVertices.Add(new GeoVert { Lon = DMathUtil.DegreesToRadians(lonLatPoint1.X), Lat = DMathUtil.DegreesToRadians(lonLatPoint1.Y), Color = color, Position = new Vector3(), Tex = new Vector4(width, 0, 0, 0) }); }
public void AddPoint(int index, DVector2 lonLat, int typeInd, float size = 0.01f) { var basis = GeoHelper.CalculateBasisOnSurface(lonLat, true); var trans = basis.TranslationVector; var len = trans.Length(); var topLeft = trans + basis.Forward*size - basis.Right*size; var topRight = trans + basis.Forward*size + basis.Right*size; var botLeft = trans - basis.Forward*size - basis.Right*size; var botRight = trans - basis.Forward*size + basis.Right*size; PointsCpu[index * 4 + 0] = new Gis.CartPoint { X = topLeft.X, Y = topLeft.Y, Z = topLeft.Z, Color = Color.White, Tex0 = new Vector4(1, 1, 0, 0) }; PointsCpu[index * 4 + 1] = new Gis.CartPoint { X = topRight.X, Y = topRight.Y, Z = topRight.Z, Color = Color.White, Tex0 = new Vector4(0, 1, 0, 0) }; PointsCpu[index * 4 + 2] = new Gis.CartPoint { X = botLeft.X, Y = botLeft.Y, Z = botLeft.Z, Color = Color.White, Tex0 = new Vector4(1, 0, 0, 0) }; PointsCpu[index * 4 + 3] = new Gis.CartPoint { X = botRight.X, Y = botRight.Y, Z = botRight.Z, Color = Color.White, Tex0 = new Vector4(0, 0, 0, 0) }; }
private void Zoom() { if (Event.current.type == EventType.ScrollWheel) { // Berechne Geoposition der Maus Vector2 mouse = Event.current.mousePosition; Vector2 center = GUIToCoordinateSystemPosition(mouse); DVector2 geoMouse = CalculateGeoCoords(center); if (Event.current.delta.y < 0) { if (ZoomLevel < MAXZOOMLEVEL) { ZoomLevel++; } } else { if (mapRect.width < TileSizePixels * (int)Mathf.Pow(2, ZoomLevel - 1)) { ZoomLevel--; } } // Berechne TileIndex im neuen Zoomlevel Vector2 tileIndex = CalculateGridIndex((Vector2)geoMouse); Vector2 pixelPositionAfterZoom = WorldToPixelPosition(geoMouse.x, geoMouse.y, ZoomLevel); pixelOrigin = pixelPositionAfterZoom - mouse; PerformMove(Vector2.zero); Event.current.Use(); SetDirty(); } FitZoomLevel(); }
private static List <Tuple <double, int> > GetSortedBodyDistances(int currentIndex, IList <IGravitationalBody> bodies) { DVector2 targetCenter = bodies[currentIndex].Position; var bodiesByDistance = new List <Tuple <double, int> >(); for (int i = 0; i < bodies.Count; i++) { if (i == currentIndex) { continue; } DVector2 difference = targetCenter - bodies[i].Position; double distance = difference.LengthSquared(); bodiesByDistance.Add(new Tuple <double, int>(distance, i)); } bodiesByDistance.Sort(Compare); return(bodiesByDistance); }
void TickUpdate() { ComSat.Trace(this, "TickUpdate"); if (ComSat.EntityExists(target)) { moving = true; destination = target.position; if ((destination - entity.position).sqrMagnitude < detonateRange * detonateRange) { Detonate(); return; } } else if (targets != null && targets.Any()) { PickNewTarget(); } if (moving) { if ((ComSat.RandomValue() % 500) == 0) { Detonate(); return; } if ((destination - entity.position).sqrMagnitude < sqrPositioningAccuracy) { // Close enough. moving = false; motor.Stop(); } else { motor.MoveTowards(destination); } } }
/// <summary> /// Gets the relative velocity of the spacecraft. If the space craft is within the parent's /// atmosphere than the rotation of the planet is taken in account. Otherwise its a simple difference of velocities. /// </summary> public override DVector2 GetRelativeVelocity() { double altitude = GetRelativeAltitude(); if (altitude > GravitationalParent.AtmosphereHeight) { return(Velocity - GravitationalParent.Velocity); } DVector2 difference = GravitationalParent.Position - Position; difference.Normalize(); var surfaceNormal = new DVector2(-difference.Y, difference.X); double altitudeFromCenter = altitude + GravitationalParent.SurfaceRadius; // Distance of circumference at this altitude ( c= 2r * pi ) double pathCirumference = 2 * Math.PI * altitudeFromCenter; double rotationalSpeed = pathCirumference / GravitationalParent.RotationPeriod; return(Velocity - (GravitationalParent.Velocity + surfaceNormal * rotationalSpeed)); }
void TryToPlaceThing() { if (Input.GetMouseButtonUp(0)) { var position = new DVector2((DReal)activeGhost.transform.position.z, (DReal)activeGhost.transform.position.x); if (placementValidCallback(position)) { placeCallback(position); Destroy(activeGhost); placementValidCallback = null; placeCallback = null; return; } } else if (Input.GetMouseButtonUp(1)) { Destroy(activeGhost); placementValidCallback = null; placeCallback = null; return; } Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, Mathf.Infinity, 1 << terrainLayer)) { activeGhost.transform.position = hit.point; var position = new DVector2((DReal)activeGhost.transform.position.z, (DReal)activeGhost.transform.position.x); var colour = placementValidCallback(position) ? Color.green : Color.red; foreach (var r in activeGhost.GetComponentsInChildren <Renderer>()) { r.material.color = colour; } } }
/// <summary> /// Stages the spacecraft according to its mounted angle by applying a normal force. /// </summary> public void Stage() { if (Children.Count > 0) { ISpaceCraft[] children = Children.ToArray(); foreach (ISpaceCraft child in children) { child.Stage(); } } else if (Parent != null) { Parent.RemoveChild(this); Parent = null; // Simulate simple staging mechanism double sAngle = StageOffset.Angle(); DVector2 stagingVector = DVector2.FromAngle(Rotation + sAngle + Math.PI * 0.5); AccelerationN += stagingVector * 1000; } }
public ITSShip(string craftDirectory, DVector2 position, DVector2 velocity, double payloadMass, double propellantMass = 1769010) : base(craftDirectory, position, velocity, payloadMass, propellantMass, null) { Engines = new IEngine[9]; // Raptor Vac engines for (int i = 0; i < 6; i++) { double engineOffsetX = (i - 2.5) / 2.5; var offset = new DVector2(engineOffsetX * Width * 0.25, Height * 0.48); Engines[i] = new RaptorVac2016(i, this, offset); } // Raptor SL 50 engines Engines[6] = new Raptor50(6, this, new DVector2(-2, Height * 0.48)); Engines[7] = new Raptor50(7, this, new DVector2(0, Height * 0.48)); Engines[8] = new Raptor50(8, this, new DVector2(2, Height * 0.48)); _spriteSheet = new SpriteSheet("Textures/Spacecrafts/Its/ship.png", 12, 12); this.payloadMass = payloadMass; }
public void ResolveGravitionalParents(List <IMassiveBody> massiveBodies) { foreach (ISpaceCraft spaceCraft in _spaceCrafts) { double bestMassDistanceRatio = double.MaxValue; foreach (IMassiveBody bodyB in massiveBodies) { double massRatio = Math.Pow(spaceCraft.Mass / bodyB.Mass, 0.4); DVector2 difference = spaceCraft.Position - bodyB.Position; double massDistanceRatio = massRatio * difference.Length(); // New parent if (massDistanceRatio < bestMassDistanceRatio) { spaceCraft.SetGravitationalParent(bodyB); bestMassDistanceRatio = massDistanceRatio; } } } }
/// <summary> /// Gets the down range distance along the equator of the parent planet. /// </summary> public double GetDownrangeDistance(DVector2 pointOfReference) { DVector2 pofOffset = GravitationalParent.Position - pointOfReference; pofOffset.Normalize(); DVector2 spaceCraftOffset = GravitationalParent.Position - Position; spaceCraftOffset.Normalize(); // Find angle between normal vectors double angle = Math.Acos(pofOffset.X * spaceCraftOffset.X + pofOffset.Y * spaceCraftOffset.Y); // Fixing wrapping around a circle if (angle > Math.PI) { angle -= Math.PI; } // Take the ratio of the angle to the full circumference double arcRatio = angle / (Math.PI * 2); return(arcRatio * (2.0 * GravitationalParent.SurfaceRadius * Math.PI)); }
public RaptorSL300(int id, ISpaceCraft parent, DVector2 offset) : base(parent, offset, new EngineFlame(id, Color.FromArgb(15, 209, 173, 199), 50, 2, 0.2, 0.6, 0.1)) { }
public void Accept(DVector2 type, StringBuilder x) { var v = type.Value; x.Append($"vector2(x={v.X},y={v.Y})"); }
public Merlin1DVac(ISpaceCraft parent, DVector2 offset) : base(parent, offset, new EngineFlame(0, 500, 3, 0.5, 0.5)) { }
public static LinesGisLayer GenerateGrid(Game Game, DVector2 leftTop, DVector2 rightBottom, int dimX, int dimY, Color color, MapProjection projection, bool keepQuad = false) { var lt = projection.WorldToTilePos(leftTop.X, leftTop.Y, 0); var rb = projection.WorldToTilePos(rightBottom.X, rightBottom.Y, 0); if (keepQuad) { rb.Y = lt.Y + (rb.X - lt.X); } double stepX = Math.Abs(rb.X - lt.X) / (dimX - 1); double stepY = Math.Abs(rb.Y - lt.Y) / (dimY - 1); List<Gis.GeoPoint> points = new List<Gis.GeoPoint>(); // Too lazy for (int row = 1; row < dimY-1; row++) { for (int col = 0; col < dimX-1; col++) { var coords0 = projection.TileToWorldPos(lt.X + stepX * col, lt.Y + stepY * row, 0); var coords1 = projection.TileToWorldPos(lt.X + stepX * (col+1), lt.Y + stepY * row, 0); points.Add(new Gis.GeoPoint { Lon = DMathUtil.DegreesToRadians(coords0.X), Lat = DMathUtil.DegreesToRadians(coords0.Y), Color = color }); points.Add(new Gis.GeoPoint { Lon = DMathUtil.DegreesToRadians(coords1.X), Lat = DMathUtil.DegreesToRadians(coords1.Y), Color = color }); } } for (int col = 1; col < dimX-1; col++) { for (int row = 0; row < dimY-1; row++) { var coords0 = projection.TileToWorldPos(lt.X + stepX * col, lt.Y + stepY * row, 0); var coords1 = projection.TileToWorldPos(lt.X + stepX * col, lt.Y + stepY * (row+1), 0); points.Add(new Gis.GeoPoint { Lon = DMathUtil.DegreesToRadians(coords0.X), Lat = DMathUtil.DegreesToRadians(coords0.Y), Color = color }); points.Add(new Gis.GeoPoint { Lon = DMathUtil.DegreesToRadians(coords1.X), Lat = DMathUtil.DegreesToRadians(coords1.Y), Color = color }); } } var linesLayer = new LinesGisLayer(Game, points.Count); Array.Copy(points.ToArray(), linesLayer.PointsCpu, points.Count); linesLayer.UpdatePointsBuffer(); linesLayer.Flags = (int)(LineFlags.THIN_LINE); return linesLayer; }
public DisplayNumericPropertyAttribute(DVector2 Default, double Increment, int Decimals, string Name, double Minimum = (double)long.MinValue, double Maximum = (double)long.MaxValue) : this(Default, Name, Increment, Minimum, Maximum, Decimals) { }
/// <summary> /// Takes the value that came from the relative position of the mouse , to update color. /// </summary> /// <param name="newValue">The new value.</param> private void TakeValue(DVector2 newValue) { switch (this.drawStyle) { case DrawStyle.Hue: HSL.S = newValue.X; HSL.L = 1 - newValue.Y; this.RGBA = AdobeColors.HSLToRGB(HSL); break; case DrawStyle.Saturation: HSL.H = newValue.X; HSL.L = 1 - newValue.Y; this.RGBA = AdobeColors.HSLToRGB(HSL); break; case DrawStyle.Brightness: HSL.H = newValue.X; HSL.S = 1 - newValue.Y; this.RGBA = AdobeColors.HSLToRGB(HSL); break; case DrawStyle.Red: this.RGBA.UpdateG((byte)(1 - newValue.Y)); this.RGBA.UpdateB((byte)newValue.X); HSL = AdobeColors.RGBToHSL(this.RGBA); break; case DrawStyle.Green: this.RGBA.UpdateB((byte)newValue.X); this.RGBA.UpdateR((byte)(1 - newValue.Y)); HSL = AdobeColors.RGBToHSL(this.RGBA); break; case DrawStyle.Blue: this.RGBA.UpdateR((byte)newValue.X); this.RGBA.UpdateG((byte)(1 - newValue.Y)); HSL = AdobeColors.RGBToHSL(this.RGBA); break; } }
public Merlin1DVac(ISpaceCraft parent, DVector2 offset) : base(parent, offset, new EngineFlame(0, Color.FromArgb(200, 255, 255, 0), 500, 3, 0.5, 0.5, 0.1)) { }
public override List<Gis.SelectedItem> Select(DVector3 nearPoint, DVector3 farPoint) { DVector3[] rayHitPoints; var ret = new List<Gis.SelectedItem>(); if (!GeoHelper.LineIntersection(nearPoint, farPoint, GeoHelper.EarthRadius, out rayHitPoints)) return ret; var rayLonLatRad = GeoHelper.CartesianToSpherical(rayHitPoints[0]); //var OneGradusLengthKmInv = 1.0 / (Math.Cos(rayLonLatRad.Y)*GeoHelper.EarthOneDegreeLengthOnEquatorMeters/1000.0); for (int i = 0; i < PointsCountToDraw; i++) { int ind = PointsDrawOffset + i; var point = PointsCpu[ind]; var size = point.Tex0.Z * 0.5; var pointLonLat = new DVector2(point.Lon, point.Lat); var dist = GeoHelper.DistanceBetweenTwoPoints(pointLonLat, rayLonLatRad); if (dist <= size) { ret.Add(new SelectedItem { Distance = dist, PointIndex = ind }); } } return ret; }
public static DVector2 WorldToTilePos(DVector2 lonLat) { DVector2 p = new DVector2(); p.X = (lonLat.X + 180.0) / 360.0 * (1 << 0); p.Y = (1.0 - Math.Log(Math.Tan(lonLat.Y * Math.PI / 180.0) + 1.0 / Math.Cos(lonLat.Y * Math.PI / 180.0)) / Math.PI) / 2.0 * (1 << 0); return p; }
public static DVector2 WorldToTilePos(double lon, double lat, int zoom) { DVector2 p = new DVector2(); p.X = (float)((lon + 180.0) / 360.0 * (1 << zoom)); p.Y = (float)((1.0 - Math.Log(Math.Tan(lat * Math.PI / 180.0) + 1.0 / Math.Cos(lat * Math.PI / 180.0)) / Math.PI) / 2.0 * (1 << zoom)); return p; }
public static DVector2 DegreesToRadians(DVector2 degree) { return new DVector2(degree.X * (Pi / 180.0), degree.Y * (Pi / 180.0)); }
public static LinesGisLayer GenerateDistanceGrid(Game Game, DVector2 lonLatLeftBottomCorner, double step, int xStepsCount, int yStepsCount, Color color) { List<Gis.GeoPoint> points = new List<Gis.GeoPoint>(); // Too lazy //var yPoint = lonLatLeftBottomCorner; //for (int row = 0; row < yStepsCount; row++) { // // yPoint = GeoHelper.RhumbDestinationPoint(yPoint, 0, step); // // for (int col = 0; col < xStepsCount; col++) // { // var coords0 = GeoHelper.RhumbDestinationPoint(yPoint, 90, step * col); // //var coords1 = GeoHelper.RhumbDestinationPoint(coords0, 90, step); // // points.Add(new Gis.GeoPoint { // Lon = DMathUtil.DegreesToRadians(coords0.X), // Lat = DMathUtil.DegreesToRadians(coords0.Y), // Color = color // }); // //points.Add(new Gis.GeoPoint { // // Lon = DMathUtil.DegreesToRadians(coords1.X), // // Lat = DMathUtil.DegreesToRadians(coords1.Y), // // Color = color // //}); // } //} for (int col = 0; col < xStepsCount; col++) { var xPoint = GeoHelper.RhumbDestinationPoint(lonLatLeftBottomCorner, 90, step * col); for (int row = 0; row < yStepsCount; row++) { var coords0 = GeoHelper.RhumbDestinationPoint(xPoint, 0, step * row); //var coords1 = GeoHelper.RhumbDestinationPoint(xPoint, 0, step * (row + 1)); points.Add(new Gis.GeoPoint { Lon = DMathUtil.DegreesToRadians(coords0.X), Lat = DMathUtil.DegreesToRadians(coords0.Y), Color = color }); //points.Add(new Gis.GeoPoint //{ // Lon = DMathUtil.DegreesToRadians(coords1.X), // Lat = DMathUtil.DegreesToRadians(coords1.Y), // Color = color //}); } } var indeces = new List<int>(); for (int col = 0; col < xStepsCount-1; col++) { for (int row = 0; row < yStepsCount; row++) { indeces.Add(row + (col+1) * yStepsCount); indeces.Add(row + col*yStepsCount); } } for (int row = 0; row < yStepsCount-1; row++) { for (int col = 0; col < xStepsCount; col++) { indeces.Add(col * yStepsCount + row); indeces.Add((col) * yStepsCount + row + 1); } } var newPoints = new List<Gis.GeoPoint>(); foreach (var ind in indeces) { newPoints.Add(points[ind]); } var linesLayer = new LinesGisLayer(Game, newPoints.Count); Array.Copy(newPoints.ToArray(), linesLayer.PointsCpu, newPoints.Count); linesLayer.UpdatePointsBuffer(); linesLayer.Flags = (int)(LineFlags.THIN_LINE); return linesLayer; }
// Перегружаем главный метод. По назначению он анологичен методу OnPaint() и предназначен // для формирования изображения. Однако в отличии от оного он выполняется паралелльно в // другом потоке и вызывается непрерывно. О текущей частоте вызовов можно судить по // счетчику числа кадров в заголовке окна (конечно в режиме отладки скорость падает). // Помимо прочего он обеспечивает более высокую скорость рисования и не мерцает. void DrawStripes(Graphics gr, DVector2 center, double x1, double y1, double x2, double y2, double angle, double scale, double WindowScale, bool inverted, double invertAngle) { double startDx = x1 - center.X; double startDy = y1 - center.Y; double startDist = Math.Sqrt(startDx * startDx + startDy * startDy); double endDx = x2 - center.X; double endDy = y2 - center.Y; double endDist = Math.Sqrt(endDx * endDx + endDy * endDy); double step = 10.0; double scaledStep = step * scale * WindowScale; if (scale > 0.0) { int start = (int)(startDist / scaledStep) + 1; int end = (int)(endDist / scaledStep) + 1; double stripeWidth = 10.0 * WindowScale; for (int i = -start; i <= end; ++i) { if (i == 0) { continue; } double leftX, rightX; rightX = stripeWidth / 2 * WindowScale; leftX = -stripeWidth / 2 * WindowScale; double Y = i * scaledStep; if (angle > Math.PI) { angle -= Math.PI; } double lx, ly, rx, ry, lbx, lby; if (i % 5 == 0) { double labelX = rightX + stripeWidth * WindowScale; double fontSize = 10.0 * WindowScale; rightX *= 2; leftX *= 2; (lbx, lby) = VecRotate(labelX, Y - fontSize / 2, angle + 3.0 * Math.PI / 2.0); double label; label = i * step; if (inverted) { label = -label; } if (RotationAngle >= invertAngle && RotationAngle <= 180.0 + invertAngle) { label = -label; } gr.DrawString(label.ToString(), new Font("Arial", (float)fontSize), Brushes.Black, lbx + center.X, lby + center.Y); } (lx, ly) = VecRotate(leftX, Y, angle + 3.0 * Math.PI / 2.0); (rx, ry) = VecRotate(rightX, Y, angle + 3.0 * Math.PI / 2.0); gr.DrawLine(Pens.Black, lx + center.X, ly + center.Y, rx + center.X, ry + center.Y); } } }
public virtual double GetRelativeAltitude() { DVector2 difference = Position - GravitationalParent.Position; return(difference.Length()); }
/// <summary>Adds the control to my grid.</summary> /// <param name="gridIndexX">The grid index position x.</param> /// <param name="gridIndexY">The grid index position y.</param> /// <param name="control">The control to add to given location.</param> /// <exception cref="System.ArgumentNullException">Control that was null.</exception> public void AddGridControl(int gridIndexX, int gridIndexY, Control control) { #if DEBUG if (control == null) { throw new ArgumentNullException("control"); } #endif if (gridIndexX >= 0 && gridIndexX < this.ConfigColumnCount && gridIndexY >= 0 && gridIndexY < this.ConfigRowCount && this.controlArray[gridIndexX][gridIndexY] == null) { this.controlArray[gridIndexX][gridIndexY] = control; var position = this.GridPosition(gridIndexX, gridIndexY); control.Config.PositionX = position.X; control.Config.PositionY = position.Y; control.Config.Width = this.cellWidth; control.Config.Height = this.cellHeight; if (control is Label) { var pos = new DVector2(control.Config.PositionX, control.Config.PositionY); pos += new DVector2(this.cellWidth / 2.0f, this.cellHeight / 2.0f); control.State.DrawPosition = pos; } this.AddControl(control); control.LoadContent(); } }
public SpaceCraftProxy(DVector2 position, DVector2 velocity, SpaceCraftBase spaceCraft) : base(position, velocity, 0) { _proxy = spaceCraft; }
public SuperDraco(int id, ISpaceCraft parent, DVector2 offset) : base(parent, offset, new EngineFlame(id, 50, 1, 0.1, 0.15)) { }
public static List <Entity> FindAllEntitiesWithinRadius(DVector2 origin, DReal radius, int ignoreTeam = -1, Func <Entity, DReal> getRadius = null) { return(FindAllEntitiesWithinRadius <Entity>(origin, radius, ignoreTeam, getRadius)); }
public static void DrawLine(this BitmapSurface surface, int color, DVector2 p1, DVector2 p2) { unchecked { DrawLine(surface, color, p1.X, p1.Y, p2.X, p2.Y); } }
public bool Contains(DVector2 other) { return(other.X > Left && other.X < Right && other.Y > Top && other.Y < Bottom); }
/// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { base.Update(gameTime); this.UpdateDrawPositionByConfigAndParent(); this.UpdateDrawSizeByConfig(); this.UpdateDrawSourceRectangleByConfig(); var leftMousePressed = Manager.InputManager.ReadLeftMousePressed(); var mouseLocation = Manager.InputManager.ReadMouseLocation(); // check the redraw FLAG ! if (this.redrawControlFlag == true) { this.RedrawControl(); this.redrawControlFlag = false; } if (this.CheckIsFocused() && leftMousePressed) { this.dragging = true; } if (this.dragging && leftMousePressed) { var relativeLocation = PointRelative(mouseLocation); this.gradientValue = new DVector2(relativeLocation.X / Config.Width, relativeLocation.Y / Config.Height); this.redrawControlFlag = true; this.TakeValue(this.gradientValue); Debug.WriteLine("Rel " + relativeLocation + " val " + this.gradientValue); } if (this.dragging && leftMousePressed == false) { this.dragging = false; } }
protected MassiveBodyBase(DVector2 position, DVector2 velocity, IMassiveKernel kernel) : base(position, velocity, 0) { Kernel = kernel; }
/// <summary> /// Reads if we are dragging, and react to it if we are. /// </summary> public void ReadIfDragging() { if (this.TitleBar == null || !this.TitleBar.StateIsPressed || this.Dragging != false) { return; } if (this.Parent != null) { // remember the mouse location , relative to this control where we start dragging this.DragStartLocation = this.Parent.PointRelative(this.Manager.InputManager.ReadMouseLocation()); // check where the indicator is, relative to this control where we start dragging this.WindowDragStartLocation = this.Parent.PointRelative(this.TitleBar.State.DrawPosition); } else { this.DragStartLocation = this.Manager.InputManager.ReadMouseLocation(); this.WindowDragStartLocation = this.TitleBar.State.DrawPosition; } this.Dragging = true; Debug.WriteLine("Dragging started at location " + this.DragStartLocation + " and form starts at location " + this.WindowDragStartLocation); }
public static void DrawTriangle(this BitmapSurface surface, int color, DVector2 p1, DVector2 p2, DVector2 p3) { unchecked { DrawTriangle(surface, color, p1.X, p1.Y, p2.X, p2.Y, p3.X, p3.Y); } }
public static DVector3 SphericalToCartesian(DVector2 lonLat, double radius) { double x, y, z; SphericalToCartesian(lonLat.X, lonLat.Y, radius, out x, out y, out z); return new DVector3(x, y, z); }
private void PredictTargetThrottle(SpaceCraftBase spaceCraft) { double optimalThrust = _currentThrust; double optimalLandingSpeed = double.PositiveInfinity; for (int i = -1; i <= 1; i++) { double thrust = _currentThrust; thrust += i; if (thrust < 40 || thrust > 100) { continue; } IMassiveBody parent = spaceCraft.GravitationalParent; DVector2 initialPosition = spaceCraft.Position - parent.Position; var proxyParent = new MassiveBodyProxy(DVector2.Zero, DVector2.Zero, parent); var proxySatellite = new SpaceCraftProxy(initialPosition, spaceCraft.Velocity - parent.Velocity, spaceCraft); foreach (int id in _engineIds) { proxySatellite.Engines[id].Startup(); proxySatellite.Engines[id].AdjustThrottle(thrust); } proxySatellite.SetGravitationalParent(proxyParent); // Simulate until the rocket runs out of fuel or touches down for (int step = 0; step < 1000; step++) { proxySatellite.ResetAccelerations(); proxySatellite.ResolveGravitation(proxyParent); proxySatellite.ResolveAtmopsherics(proxyParent); if (proxySatellite.PropellantMass <= 0) { break; } if (proxySatellite.OnGround) { double landingSpeed = proxySatellite.RelativeVelocity.Length(); if (landingSpeed < optimalLandingSpeed) { optimalLandingSpeed = landingSpeed; optimalThrust = thrust; } break; } proxySatellite.Update(0.05); } } // Set the target engines to the optimal computed thrust if (_engineIds != null) { // Startup the required landing engines foreach (int id in _engineIds) { IEngine engine = spaceCraft.Engines[id]; engine.AdjustThrottle(optimalThrust); } _currentThrust = optimalThrust; } }
public static double DistanceBetweenTwoPoints(DVector2 lonLatP0, DVector2 lonLatP1, double earthRadius = 6378.137) { var phi0 = lonLatP0.Y; var phi1 = lonLatP1.Y; var deltaPhi = phi1 - phi0; var deltaLam = lonLatP1.X - lonLatP0.X; var a = Math.Sin(deltaPhi / 2) * Math.Sin(deltaPhi / 2) + Math.Cos(phi0) * Math.Cos(phi1) * Math.Sin(deltaLam / 2) * Math.Sin(deltaLam / 2); var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a)); var d = earthRadius * c; return d; }
public static double Dot(DVector2 v1, DVector2 v2) { return(v1.x * v2.x + v1.y * v2.y); }
public static DVector2 RhumbDestinationPoint(DVector2 startPoint, double bearing, double distance, double radius = 6378.137) { var δ = distance / radius; // angular distance in radians var φ1 = DMathUtil.DegreesToRadians(startPoint.Y); var λ1 = DMathUtil.DegreesToRadians(startPoint.X); var θ = DMathUtil.DegreesToRadians(bearing); var Δφ = δ * Math.Cos(θ); var φ2 = φ1 + Δφ; // check for some daft bugger going past the pole, normalise latitude if so if (Math.Abs(φ2) > Math.PI / 2) φ2 = φ2 > 0 ? Math.PI - φ2 : -Math.PI - φ2; var Δψ = Math.Log(Math.Tan(φ2 / 2 + Math.PI / 4) / Math.Tan(φ1 / 2 + Math.PI / 4)); var q = Math.Abs(Δψ) > 10e-12 ? Δφ / Δψ : Math.Cos(φ1); // E-W course becomes ill-conditioned with 0/0 var Δλ = δ * Math.Sin(θ) / q; var λ2 = λ1 + Δλ; return new DVector2((DMathUtil.RadiansToDegrees(λ2) + 540) % 360 - 180, DMathUtil.RadiansToDegrees(φ2)); // normalise to −180…+180° }
public RedDragon(string craftDirectory, DVector2 position, DVector2 velocity, double payloadMass) : base(craftDirectory, position, velocity, payloadMass, 1388) { }
public static DMatrix CalculateBasisOnSurface(DVector2 lonLatRad, bool includeTranslation = false) { var translation = SphericalToCartesian(lonLatRad, EarthRadius); DVector3 up = translation; up.Normalize(); var xAxis = DVector3.TransformNormal(DVector3.UnitX, DMatrix.RotationAxis(DVector3.UnitY, lonLatRad.X)); xAxis.Normalize(); var mat = DMatrix.Identity; mat.Up = up; mat.Right = xAxis; mat.Forward = DVector3.Cross(xAxis, up); mat.Forward.Normalize(); if (includeTranslation) mat.TranslationVector = translation; return mat; }
protected override void OnDeviceUpdate(object s, GDIDeviceUpdateArgs e) { Width = (int)e.Width; Height = (int)e.Heigh; double WindowScale; if (Height < Width) { WindowScale = (double)Height / InitialHeight; } else { WindowScale = (double)Width / InitialWidth; } DVector2 pivot = new DVector2(Width / 2, Height / 2); Pen graphPen = new Pen(Brushes.DarkBlue, 2.0f); Pen xAxisPen = new Pen(Brushes.Red, 2.0f); Pen yAxisPen = new Pen(Brushes.Green, 2.0f); if (points == null || PrevApproxLevel != ApproxLevel || PrevAmplitude != Amplitude) { points = ComputePoints(); PrevApproxLevel = ApproxLevel; PrevAmplitude = Amplitude; Console.WriteLine("Recomputed!"); } // ----- double RotationAngleRad = RotationAngle / 180.0 * Math.PI; DVector2 center = new DVector2(pivot.X + Offset.X + ShiftX, pivot.Y - Offset.Y - ShiftY); DrawAxis(e.Graphics, xAxisPen, RotationAngleRad, center, Math.Abs(Scale.X), WindowScale, false, 180.0); DrawAxis(e.Graphics, yAxisPen, RotationAngleRad + Math.PI / 2.0, center, Math.Abs(Scale.Y), WindowScale, true, 90.0); e.Graphics.FillEllipse(Brushes.Black, new Rectangle((int)(center.X - centerCircleSize), (int)(center.Y - centerCircleSize), centerCircleSize * 2, centerCircleSize * 2)); DVector2 prevP = new DVector2(pivot); bool firstPointComputed = false; foreach (var p in points) { DVector2 scaledP = (new DVector2(p.X, -p.Y)).Multiply(Scale * WindowScale); double sin = Math.Sin(RotationAngleRad); double cos = Math.Cos(RotationAngleRad); DVector2 rotatedP = VecRotate(scaledP, RotationAngleRad); DVector2 transformedP = new DVector2(rotatedP.X + Offset.X + ShiftX + pivot.X, rotatedP.Y + -Offset.Y - ShiftY + pivot.Y); if (firstPointComputed) { e.Graphics.DrawLine(graphPen, prevP.X, prevP.Y, transformedP.X, transformedP.Y); } prevP = transformedP; firstPointComputed = true; } e.Graphics.DrawString(LabelTxt, new Font("Arial", 15f), Brushes.Black, 10f, 10f); }
public bool ScreenToSpherical(float x, float y, out DVector2 lonLat) { DVector3 near, far; GetRayFromScreenPoint(x, y, out near, out far); lonLat = DVector2.Zero; DVector3[] res; if (GeoHelper.LineIntersection(near, far, EarthRadius, out res)) { GeoHelper.CartesianToSpherical(res[0], out lonLat.X, out lonLat.Y); return true; } return false; }
public OrionAbortMotor(int id, ISpaceCraft parent, DVector2 offset, double angle) : base(parent, offset, new EngineFlame(id, Color.FromArgb(63, 255, 255, 159), 50, 2, 0.1, 0.15, 0.003, angle)) { _angle = angle; }
/// <summary> /// Updates the draw position by using my current configuration and the position of my parent control. /// </summary> protected void UpdateDrawPositionByConfigAndParent() { var parentPosition = new DVector2(); if (this.Parent != null) { parentPosition = Parent.State.DrawPosition; } var newPosition = parentPosition + new DVector2(this.Config.PositionX, this.Config.PositionY); // System.Diagnostics.Debug.WriteLine(string.Format("Setting control {0} draw-position to {1}", Name, newPosition)); this.State.DrawPosition = newPosition; }
/// <summary>Draws the string using specified location font and color.</summary> /// <param name="fontName">Name of the font.</param> /// <param name="text">The text to draw.</param> /// <param name="position">The position of the text.</param> /// <param name="fontColor">Color of the font.</param> public abstract void DrawString(string fontName, string text, DVector2 position, GUIColor fontColor);
/// <summary> /// Check where given location is relative to me. /// </summary> /// <param name="location">The location.</param> /// <returns>The given point in relation to this control.</returns> public DVector2 PointRelative(DVector2 location) { return location - this.State.DrawPosition; }
public void ApplyFrameOffset(DVector2 offset) { Position -= offset; }
/// <summary> /// Sets the indicator position. /// </summary> /// <param name="newValue">The new value.</param> private void SetIndicatorPosition(DVector2 newValue) { var x = Config.Width * newValue.X; if (x < 0) { x = 0; } if (x > Config.Width) { x = Config.Width; } var y = Config.Height * newValue.Y; if (y < 0) { y = 0; } if (y > Config.Height) { y = Config.Height; } this.Indicator.Config.PositionX = x; this.Indicator.Config.PositionY = y; }