public override void Render(DrawArgs drawArgs) { if (!m_widget.Visible) { SetPushed(false); } }
/// <summary> /// Plugin entry point /// </summary> public override void Load() { drawArgs = ParentApplication.WorldWindow.DrawArgs; DeviceList dl = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly); dl.MoveNext(); if(dl.Current==null) { throw new ApplicationException("No joystick detected. Please check your connections and verify your device appears in Control panel -> Game Controllers."); } DeviceInstance di = (DeviceInstance) dl.Current; joystick = new Device( di.InstanceGuid ); joystick.SetDataFormat(DeviceDataFormat.Joystick); joystick.SetCooperativeLevel(ParentApplication, CooperativeLevelFlags.NonExclusive | CooperativeLevelFlags.Background); foreach(DeviceObjectInstance d in joystick.Objects) { // For axes that are returned, set the DIPROP_RANGE property for the // enumerated axis in order to scale min/max values. if((d.ObjectId & (int)DeviceObjectTypeFlags.Axis)!=0) { // Set the AxisRange for the axis. joystick.Properties.SetRange(ParameterHow.ById, d.ObjectId, new InputRange(-AxisRange, AxisRange)); joystick.Properties.SetDeadZone(ParameterHow.ById, d.ObjectId, 1000); // 10% } } joystick.Acquire(); // Start a new thread to poll the joystick // TODO: The Device supports events, use them joyThread = new Thread( new ThreadStart(JoystickLoop) ); joyThread.IsBackground = true; joyThread.Start(); }
/// <summary> /// Draws the progress bar /// </summary> /// <param name="x">Center X position of progress.</param> /// <param name="y">Center Y position of progress.</param> /// <param name="progress">Progress vale, in the range 0..1</param> public void Draw(DrawArgs drawArgs, float x, float y, float progress, int color) { if(x!=this.x || y!=this.y) Initalize(x,y); int barlength = (int)(progress * 2 * halfWidth); progressBar[0].X = x - halfWidth; progressBar[0].Y = y - halfHeight; progressBar[0].Color = color; progressBar[1].X = x - halfWidth; progressBar[1].Y = y + halfHeight; progressBar[1].Color = color; progressBar[2].X = x - halfWidth + barlength; progressBar[2].Y = y - halfHeight; progressBar[2].Color = color; progressBar[3].Y = y + halfHeight; progressBar[3].X = x - halfWidth + barlength; progressBar[3].Color = color; progressRight[0].X = x - halfWidth +barlength; progressRight[0].Y = y - halfHeight; progressRight[1].X = x - halfWidth + barlength; progressRight[1].Y = y + halfHeight; progressRight[2].X = x + halfWidth; progressRight[2].Y = y - halfHeight; progressRight[3].X = x + halfWidth; progressRight[3].Y = y + halfHeight; drawArgs.device.VertexFormat = CustomVertex.TransformedColored.Format; drawArgs.device.TextureState[0].ColorOperation = TextureOperation.Disable; drawArgs.device.DrawUserPrimitives(PrimitiveType.TriangleStrip, 2, progressBar); drawArgs.device.DrawUserPrimitives(PrimitiveType.TriangleStrip, 2, progressRight); drawArgs.device.DrawUserPrimitives(PrimitiveType.LineStrip, 4, progressBarOutline); }
public void Render(DrawArgs drawArgs) { // Render from bottom and up const int screenMargin = 10; m_renderPosition = new Vector2(drawArgs.screenWidth - HalfWidth - screenMargin, drawArgs.screenHeight - screenMargin); ImageAccessor logoAccessor = null; // Render download progress and rectangles for(int i=0; i < DrawArgs.DownloadQueue.ActiveDownloads.Count; i++) { DownloadRequest request = (DownloadRequest)DrawArgs.DownloadQueue.ActiveDownloads[i]; GeoSpatialDownloadRequest geoRequest = request as GeoSpatialDownloadRequest; if(geoRequest == null) continue; RenderProgress(drawArgs, geoRequest); RenderRectangle(drawArgs, geoRequest); ImageTileRequest imageRequest = geoRequest as ImageTileRequest; if(imageRequest == null) continue; QuadTile qt = imageRequest.QuadTile; if(qt.QuadTileArgs.ImageAccessor.ServerLogoPath != null) logoAccessor = qt.QuadTileArgs.ImageAccessor; } if(logoAccessor != null) RenderLogo( drawArgs, logoAccessor ); }
public override void Render(DrawArgs drawArgs) { if(!this._control.Visible) { this.SetPushed(false); } }
public override void Initialize(DrawArgs drawArgs) { FileInfo boundaryFileInfo = new FileInfo(this._boundaryFilePath); if(!boundaryFileInfo.Exists) { this.isInitialized = true; return; } using( FileStream boundaryFileStream = boundaryFileInfo.OpenRead() ) using( BinaryReader boundaryFileReader = new BinaryReader(boundaryFileStream, System.Text.Encoding.ASCII) ) { int numBoundaries = boundaryFileReader.ReadInt32(); int count = boundaryFileReader.ReadInt32(); this.vertices = new CustomVertex.PositionColored[count]; for(int i = 0; i < count; i++) { double lat = boundaryFileReader.ReadDouble(); double lon = boundaryFileReader.ReadDouble(); Vector3 v = MathEngine.SphericalToCartesian((float)lat, (float)lon, (float)(this._parentWorld.EquatorialRadius + this._distanceAboveSurface)); this.vertices[i].X = v.X; this.vertices[i].Y = v.Y; this.vertices[i].Z = v.Z; this.vertices[i].Color = this._color; } } this.isInitialized = true; }
public override void Initialize(WorldWind.DrawArgs drawArgs) { lock (this) { m_oLastAoI = drawArgs.CurrentRoI; m_oLastAoIChangeTime = DateTime.Now; if (m_oGroundOverlay.Icon.ViewRefreshMode == KMLViewRefreshMode.onStop) { GeographicBoundingBox oRenderBox = GetNewBox(drawArgs.CurrentRoI, m_oGroundOverlay.Icon.ViewBoundScale); m_oLayer = new ImageLayer( m_oGroundOverlay.Name, drawArgs.CurrentWorld, m_oGroundOverlay.Altitude, m_strImageFilename, oRenderBox.South, oRenderBox.North, oRenderBox.West, oRenderBox.East, (byte)(m_oGroundOverlay.Color.A * ((double)m_opacity / (double)(byte.MaxValue))), drawArgs.CurrentWorld.TerrainAccessor); if (m_oGroundOverlay.Icon.IsLocalFile) { m_oLayer.ImagePath = Path.Combine(m_strKMLDirectory, m_oGroundOverlay.Icon.HRef); } else { m_oLayer.ImageUrl = m_oGroundOverlay.Icon.GetUri(oRenderBox.West, oRenderBox.South, oRenderBox.East, oRenderBox.North); } m_oLayerAoI = drawArgs.CurrentRoI.Clone() as GeographicBoundingBox; } else { m_oLayer = new ImageLayer( m_oGroundOverlay.Name, drawArgs.CurrentWorld, m_oGroundOverlay.Altitude, m_strImageFilename, m_oGroundOverlay.LatLonBox.South, m_oGroundOverlay.LatLonBox.North, m_oGroundOverlay.LatLonBox.West, m_oGroundOverlay.LatLonBox.East, (byte)(m_oGroundOverlay.Color.A * ((double)m_opacity / (double)(byte.MaxValue))), drawArgs.CurrentWorld.TerrainAccessor); if (m_oGroundOverlay.Icon.IsLocalFile) { m_oLayer.ImagePath = Path.Combine(m_strKMLDirectory, m_oGroundOverlay.Icon.HRef); } else { m_oLayer.ImageUrl = m_oGroundOverlay.GetUri(); } } m_oLayer.Initialize(drawArgs); } }
/// <summary> /// Initialize graphics objects /// </summary> /// <param name="drawArgs"></param> public override void Initialize(WorldWind.DrawArgs drawArgs) { base.Initialize(drawArgs); lastUpdatelat = lastUpdatelon = WorldWind.Angle.Zero; lastUpdatealt = 0.0; m_needsupdate = true; Image = new System.Drawing.Bitmap(Directory.GetParent(Application.ExecutablePath) + "\\Plugins\\Flickr\\flickr.ico"); }
public override void Update(WorldWind.DrawArgs drawArgs) { lock (this) { if (m_oLayer != null) { if (m_oGroundOverlay.Icon.ViewRefreshMode == KMLViewRefreshMode.onStop) { double dTimeStopped; if (drawArgs.CurrentRoI.Equals(m_oLastAoI)) { dTimeStopped = (DateTime.Now - m_oLastAoIChangeTime).Seconds; } else { dTimeStopped = 0.0; m_oLastAoI = drawArgs.CurrentRoI; m_oLastAoIChangeTime = DateTime.Now; } if (dTimeStopped > m_oGroundOverlay.Icon.ViewRefreshTime && !m_oLayerAoI.Equivalent(drawArgs.CurrentRoI, 1e-6)) { try { File.Delete(m_strImageFilename); } catch (IOException) { return; } GeographicBoundingBox oRenderBox = GetNewBox(drawArgs.CurrentRoI, m_oGroundOverlay.Icon.ViewBoundScale); m_oLayer = new ImageLayer( m_oGroundOverlay.Name, drawArgs.CurrentWorld, m_oGroundOverlay.Altitude, m_strImageFilename, oRenderBox.South, oRenderBox.North, oRenderBox.West, oRenderBox.East, (byte)(m_oGroundOverlay.Color.A * ((double)m_opacity / (double)(byte.MaxValue))), drawArgs.CurrentWorld.TerrainAccessor); if (m_oGroundOverlay.Icon.IsLocalFile) { m_oLayer.ImagePath = Path.Combine(m_strKMLDirectory, m_oGroundOverlay.Icon.HRef); } else { m_oLayer.ImageUrl = m_oGroundOverlay.Icon.GetUri(oRenderBox.West, oRenderBox.South, oRenderBox.East, oRenderBox.North); } m_oLayer.Initialize(drawArgs); m_oLayerAoI = drawArgs.CurrentRoI.Clone() as GeographicBoundingBox; } } m_oLayer.Update(drawArgs); } } }
/// <summary> /// This is where we do our rendering /// Called from UI thread = UI code safe in this function /// </summary> public override void Render(DrawArgs drawArgs) { // Draw the current time using default font in lower right corner string text = DateTime.Now.ToString(); Rectangle bounds = drawArgs.defaultDrawingFont.MeasureString(null, text, DrawTextFormat.None, 0); drawArgs.defaultDrawingFont.DrawText(null, text, drawArgs.screenWidth-bounds.Width-distanceFromCorner, drawArgs.screenHeight-bounds.Height-distanceFromCorner, color ); }
public override void Render(WorldWind.DrawArgs drawArgs) { lock (this) { if (m_oLayer != null) { m_oLayer.Render(drawArgs); } } }
public void Render(DrawArgs drawArgs) { // if we aren't active do nothing. if ((!m_visible) || (!m_enabled)) return; for(int index = m_ChildWidgets.Count - 1; index >= 0; index--) { WorldWind.NewWidgets.IWidget currentWidget = m_ChildWidgets[index] as WorldWind.NewWidgets.IWidget; if(currentWidget != null) { if(currentWidget.ParentWidget == null || currentWidget.ParentWidget != this) currentWidget.ParentWidget = this; currentWidget.Render(drawArgs); } } }
/// <summary> /// Renders the server logo /// </summary> /// <param name="logoAccessor"></param> protected void RenderLogo( DrawArgs drawArgs, ImageAccessor logoAccessor ) { if(logoAccessor.ServerLogoPath == null) return; if(logoAccessor.ServerLogo == null) { if(!File.Exists(logoAccessor.ServerLogoPath)) return; logoAccessor.ServerLogo = ImageHelper.LoadTexture(drawArgs.device, logoAccessor.ServerLogoPath); using(Surface s = logoAccessor.ServerLogo.GetSurfaceLevel(0)) { SurfaceDescription desc = s.Description; logoAccessor.ServerLogoSize = new Rectangle(0, 0, desc.Width, desc.Height); } } if(m_sprite == null) m_sprite = new Sprite(drawArgs.device); float xScale = 2f * HalfWidth / logoAccessor.ServerLogoSize.Width; float yScale = 2f * HalfWidth / logoAccessor.ServerLogoSize.Height; m_renderPosition.Y -= HalfWidth; m_sprite.Begin(SpriteFlags.AlphaBlend); m_sprite.Transform = Matrix.Scaling(xScale,yScale,0); m_sprite.Transform *= Matrix.Translation(m_renderPosition.X, m_renderPosition.Y, 0); m_sprite.Draw( logoAccessor.ServerLogo, new Vector3(logoAccessor.ServerLogoSize.Width>>1, logoAccessor.ServerLogoSize.Height>>1, 0), Vector3.Empty, World.Settings.downloadLogoColor ); m_sprite.End(); }
/*public byte Opacity * { * get * { * return m_parentProjectedLayer.Opacity; * } * set * { * if(m_NwImageLayer != null) * { * m_NwImageLayer.Opacity = value; * } * if(m_NeImageLayer != null) * { * m_NeImageLayer.Opacity = value; * } * if(m_SwImageLayer != null) * { * m_SwImageLayer.Opacity = value; * } * if(m_SeImageLayer != null) * { * m_SeImageLayer.Opacity = value; * } * * if(m_NorthWestChild != null) * { * m_NorthWestChild.Opacity = value; * } * if(m_NorthEastChild != null) * { * m_NorthEastChild.Opacity = value; * } * if(m_SouthWestChild != null) * { * m_SouthWestChild.Opacity = value; * } * if(m_SouthEastChild != null) * { * m_SouthEastChild.Opacity = value; * } * } * }*/ private Renderable.ImageLayer CreateImageLayer(double north, double south, double west, double east, DrawArgs drawArgs, string imagePath) { Bitmap b = null; Graphics g = null; Renderable.ImageLayer imageLayer = null; GeographicBoundingBox geoBB = new GeographicBoundingBox(north, south, west, east); int numberPolygonsInTile = 0; FileInfo imageFile = new FileInfo(imagePath); if (!m_parentProjectedLayer.EnableCaching || !imageFile.Exists ) { if (m_parentProjectedLayer.LineStrings != null) { for (int i = 0; i < m_parentProjectedLayer.LineStrings.Length; i++) { if (!m_parentProjectedLayer.LineStrings[i].Visible) { continue; } GeographicBoundingBox currentBoundingBox = m_parentProjectedLayer.LineStrings[i].GetGeographicBoundingBox(); if (currentBoundingBox != null && !currentBoundingBox.Intersects(geoBB)) { continue; } else { if (b == null) { b = new Bitmap( m_parentProjectedLayer.TileSize.Width, m_parentProjectedLayer.TileSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); } if (g == null) { g = Graphics.FromImage(b); } drawLineString( m_parentProjectedLayer.LineStrings[i], g, geoBB, b.Size ); numberPolygonsInTile++; } } } if (m_parentProjectedLayer.Polygons != null) { for (int i = 0; i < m_parentProjectedLayer.Polygons.Length; i++) { if (!m_parentProjectedLayer.Polygons[i].Visible) { continue; } GeographicBoundingBox currentBoundingBox = m_parentProjectedLayer.Polygons[i].GetGeographicBoundingBox(); if (currentBoundingBox != null && !currentBoundingBox.Intersects(geoBB)) { continue; } else { if (b == null) { b = new Bitmap( m_parentProjectedLayer.TileSize.Width, m_parentProjectedLayer.TileSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); } if (g == null) { g = Graphics.FromImage(b); } drawPolygon( m_parentProjectedLayer.Polygons[i], g, geoBB, b.Size); numberPolygonsInTile++; } } } } if (b != null) { System.Drawing.Imaging.BitmapData srcInfo = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); bool isBlank = true; unsafe { int *srcPointer = (int *)srcInfo.Scan0; for (int i = 0; i < b.Height; i++) { for (int j = 0; j < b.Width; j++) { int color = *srcPointer++; if (((color >> 24) & 0xff) > 0) { isBlank = false; break; } } srcPointer += (srcInfo.Stride >> 2) - b.Width; } } b.UnlockBits(srcInfo); if (isBlank) { numberPolygonsInTile = 0; } } // if(!m_parentProjectedLayer.EnableCaching) // { string id = System.DateTime.Now.Ticks.ToString(); if (b != null && numberPolygonsInTile > 0) { MemoryStream ms = new MemoryStream(); b.Save(ms, System.Drawing.Imaging.ImageFormat.Png); //must copy original stream into new stream, if not, error occurs, not sure why m_ImageStream = new MemoryStream(ms.GetBuffer()); imageLayer = new WorldWind.Renderable.ImageLayer( id, m_parentProjectedLayer.World, 0, m_ImageStream, System.Drawing.Color.Black.ToArgb(), (float)south, (float)north, (float)west, (float)east, 1.0f //(float)m_parentProjectedLayer.Opacity / 255.0f , m_parentProjectedLayer.World.TerrainAccessor); ms.Close(); } /* } * else if(imageFile.Exists || numberPolygonsInTile > 0) * { * string id = System.DateTime.Now.Ticks.ToString(); * * if(b != null) * { * MemoryStream ms = new MemoryStream(); * b.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); * if(!imageFile.Directory.Exists) * imageFile.Directory.Create(); * * //must copy original stream into new stream, if not, error occurs, not sure why * m_ImageStream = new MemoryStream(ms.GetBuffer()); * ImageHelper.ConvertToDxt3(m_ImageStream, imageFile.FullName); * * ms.Close(); * } * * imageLayer = new WorldWind.Renderable.ImageLayer( * id, * m_parentProjectedLayer.World, * 0, * imageFile.FullName, * //System.Drawing.Color.Black.ToArgb(), * (float)south, * (float)north, * (float)west, * (float)east, * 1.0f,//(float)m_parentProjectedLayer.Opacity / 255.0f, * m_parentProjectedLayer.World.TerrainAccessor); * * imageLayer.TransparentColor = System.Drawing.Color.Black.ToArgb(); * } */ if (b != null) { b.Dispose(); } if (g != null) { g.Dispose(); } b = null; g = null; //might not be necessary //GC.Collect(); return(imageLayer); }
private void DrawTrack(DrawArgs drawArgs) { UpdateTrackPositions(drawArgs); drawArgs.device.Transform.World = Matrix.Translation( (float)-drawArgs.WorldCamera.ReferenceCenter.X, (float)-drawArgs.WorldCamera.ReferenceCenter.Y, (float)-drawArgs.WorldCamera.ReferenceCenter.Z ); drawArgs.device.RenderState.ZBufferEnable = false; drawArgs.device.TextureState[0].ColorOperation = TextureOperation.Disable; drawArgs.device.VertexFormat = CustomVertex.PositionColored.Format; drawArgs.device.DrawUserPrimitives(PrimitiveType.LineStrip, track.Length-1, track); drawArgs.device.RenderState.ZBufferEnable = true; drawArgs.device.Transform.World = drawArgs.WorldCamera.WorldMatrix; }
private bool LoadMesh(DrawArgs drawArgs) { string LayerMeshFile =Path.Combine( meshFilePath,this.Name +".x"); //Get the mesh, if exists, else load default file if(System.IO.File.Exists(LayerMeshFile)) {//There is a mesh file for the satellite, load it. GraphicsStream adj; try { mesh = Mesh.FromFile(LayerMeshFile, MeshFlags.Managed, drawArgs.device, out adj, out materials ); } catch(Exception caught) { Utility.Log.Write( caught ); string msg = "Failed to read mesh from " + meshFilePath; System.Windows.Forms.MessageBox.Show( msg, this.name +" failed to load.", MessageBoxButtons.OK, MessageBoxIcon.Error); this.ParentList.IsOn = false; return false; } string textureFilePath = ""; try { // Extract the material properties and texture names. meshTextures = new Texture[materials.Length]; meshMaterials = new Material[materials.Length]; string xFilePath = Path.GetDirectoryName(LayerMeshFile); for(int i = 0; i < materials.Length; i++) { meshMaterials[i] = materials[i].Material3D; // Set the ambient color for the material (D3DX does not do this) meshMaterials[i].Ambient = meshMaterials[i].Diffuse; // Create the texture. if(materials[i].TextureFilename!=null) { textureFilePath = Path.Combine(xFilePath, materials[i].TextureFilename); meshTextures[i] = TextureLoader.FromFile(drawArgs.device, textureFilePath); } } isInitialized = true; isFirstRun = true; // Compute bounding box for a mesh. GraphicsStream vertexData; VertexBufferDescription description = mesh.VertexBuffer.Description; vertexData = mesh.VertexBuffer.Lock (0, 0, LockFlags.ReadOnly); Geometry.ComputeBoundingBox(vertexData, mesh.NumberVertices,description.VertexFormat, out meshBoundingBoxMinValue, out meshBoundingBoxMaxValue); mesh.VertexBuffer.Unlock(); //Compute Path localmeshloaded = true; } catch(Exception caught) { Utility.Log.Write( caught ); string msg = "Failed to read Texture from " + textureFilePath; System.Windows.Forms.MessageBox.Show( msg, this.name +" failed to load.", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } else { //There is not a mesh file for the satellite, use the layer's mesh file this.meshBoundingBoxMinValue = ((SatelliteTrackerOverlay)this.ParentList).meshBoundingBoxMinValue; this.meshBoundingBoxMaxValue = ((SatelliteTrackerOverlay)this.ParentList).meshBoundingBoxMaxValue; this.meshTextures = ((SatelliteTrackerOverlay)this.ParentList).meshTextures; this.meshMaterials = ((SatelliteTrackerOverlay)this.ParentList).meshMaterials; this.mesh = ((SatelliteTrackerOverlay)this.ParentList).mesh; localmeshloaded = false; } return true; }
public override void Initialize(DrawArgs drawArgs) { if (isInitialized) return; try { orbit = new Orbit(this.TwoLineElement); timer = new System.Timers.Timer(10000); UpdateTrackPositions(drawArgs); timer.Elapsed+=new System.Timers.ElapsedEventHandler(timer_Elapsed); timer.Start(); } catch(Exception caught) { Utility.Log.Write( caught ); string msg = "Failed to read TLE from " + this.TwoLineElement.Name; throw new Exception( msg); } this.IsOn = LoadMesh(drawArgs); isInitialized = true; }
/// <summary> /// Layer initialization code /// </summary> public override void Initialize(DrawArgs drawArgs) { try { this.device = drawArgs.device; if(this._imagePath == null && this._imageUrl != null && this._imageUrl.ToLower().StartsWith("http://")) { this._imagePath = getFilePathFromUrl(this._imageUrl); } FileInfo imageFileInfo = null; if(this._imagePath != null) imageFileInfo = new FileInfo(this._imagePath); if(this.downloadThread != null && this.downloadThread.IsAlive) return; if(this._imagePath != null && this.cacheExpiration != TimeSpan.MaxValue && this.cacheExpiration.TotalMilliseconds > 0 && this._imageUrl.ToLower().StartsWith("http://") && imageFileInfo != null && imageFileInfo.Exists && imageFileInfo.LastWriteTime < DateTime.Now - this.cacheExpiration) { //attempt to redownload it this.downloadThread = new Thread(new ThreadStart(this.DownloadImage)); this.downloadThread.Name = "ImageLayer.DownloadImage"; this.downloadThread.IsBackground = true; this.downloadThread.Start(); return; } if(this.m_TextureStream != null) { this.UpdateTexture(this.m_TextureStream, this.m_TransparentColor); this.verticalExaggeration = World.Settings.VerticalExaggeration; this.CreateMesh(); this.isInitialized = true; return; } else if(imageFileInfo != null && imageFileInfo.Exists) { this.UpdateTexture(this._imagePath); this.verticalExaggeration = World.Settings.VerticalExaggeration; this.CreateMesh(); this.isInitialized = true; return; } if(this._imageUrl != null && this._imageUrl.ToLower().StartsWith("http://")) { //download it... this.downloadThread = new Thread(new ThreadStart(this.DownloadImage)); this.downloadThread.Name = "ImageLayer.DownloadImage"; this.downloadThread.IsBackground = true; this.downloadThread.Start(); return; } // No image available this.Dispose(); this.isOn = false; return; } catch { } }
public void Render(DrawArgs drawArgs) { // if we aren't active do nothing. if ((!m_visible) || (!m_enabled)) return; if (!m_isInitialized) Initialize(drawArgs); drawArgs.defaultDrawingFont.DrawText( null, m_Text, new System.Drawing.Rectangle(AbsoluteLocation.X, AbsoluteLocation.Y, m_size.Width, m_size.Height), m_Format, m_ForeColor); if (m_clearOnRender) { m_Text = ""; m_isInitialized = false; } }
/// <summary> /// Forces display of lable if we are hooked /// </summary> /// <param name="drawArgs"></param> /// <param name="sprite"></param> /// <param name="projectedPoint"></param> /// <param name="color"></param> /// <param name="labelRectangles"></param> /// <param name="isMouseOver"></param> protected override void RenderLabel(DrawArgs drawArgs, Sprite sprite, Vector3 projectedPoint, int color, List <Rectangle> labelRectangles, bool isMouseOver) { base.RenderLabel(drawArgs, sprite, projectedPoint, color, labelRectangles, (isMouseOver || this.IsHooked)); }
private void UpdateImageLayers(DrawArgs drawArgs) { try { m_LastUpdate = System.DateTime.Now; if (m_NwImageLayer != null) { m_NwImageLayer.Dispose(); } if (m_NeImageLayer != null) { m_NeImageLayer.Dispose(); } if (m_SwImageLayer != null) { m_SwImageLayer.Dispose(); } if (m_SeImageLayer != null) { m_SeImageLayer.Dispose(); } double centerLatitude = 0.5 * (m_geographicBoundingBox.North + m_geographicBoundingBox.South); double centerLongitude = 0.5 * (m_geographicBoundingBox.West + m_geographicBoundingBox.East); m_NwImageLayer = CreateImageLayer(m_geographicBoundingBox.North, centerLatitude, m_geographicBoundingBox.West, centerLongitude, drawArgs, String.Format("{0}\\{1}\\{2}\\{3:D4}\\{3:D4}_{4:D4}.dds", null, //ShapeTile.CachePath, "R", //ConfigurationLoader.GetRenderablePathString(m_parentProjectedLayer), Level + 1, 2 * Row + 1, 2 * Col)); m_NeImageLayer = CreateImageLayer(m_geographicBoundingBox.North, centerLatitude, centerLongitude, m_geographicBoundingBox.East, drawArgs, String.Format("{0}\\{1}\\{2}\\{3:D4}\\{3:D4}_{4:D4}.dds", null, //ShapeTile.CachePath, "R", //ConfigurationLoader.GetRenderablePathString(m_parentProjectedLayer), Level + 1, 2 * Row + 1, 2 * Col + 1)); m_SwImageLayer = CreateImageLayer(centerLatitude, m_geographicBoundingBox.South, m_geographicBoundingBox.West, centerLongitude, drawArgs, String.Format("{0}\\{1}\\{2}\\{3:D4}\\{3:D4}_{4:D4}.dds", null, //ShapeTile.CachePath, "R", //ConfigurationLoader.GetRenderablePathString(m_parentProjectedLayer), Level + 1, 2 * Row, 2 * Col)); m_SeImageLayer = CreateImageLayer(centerLatitude, m_geographicBoundingBox.South, centerLongitude, m_geographicBoundingBox.East, drawArgs, String.Format("{0}\\{1}\\{2}\\{3:D4}\\{3:D4}_{4:D4}.dds", null, //ShapeTile.CachePath, "R", //ConfigurationLoader.GetRenderablePathString(m_parentProjectedLayer), Level + 1, 2 * Row, 2 * Col + 1)); if (m_NwImageLayer != null) { m_NwImageLayer.Initialize(drawArgs); } if (m_NeImageLayer != null) { m_NeImageLayer.Initialize(drawArgs); } if (m_SwImageLayer != null) { m_SwImageLayer.Initialize(drawArgs); } if (m_SeImageLayer != null) { m_SeImageLayer.Initialize(drawArgs); } } catch (Exception ex) { Log.Write(ex); } }
/// <summary> /// The ROL Render actually doesn't get called much because the World class used to do ROL rendering. /// Moved this code into Render(drawArgs, priority) so if your override Render, make sure to call either /// call that function OR replicate it's behavior. /// </summary> /// <param name="drawArgs"></param> public override void Render(DrawArgs drawArgs) { // if we dont know the current render priority then just use our own this.RenderChildren(drawArgs, this.RenderPriority); }
public override void Update(DrawArgs drawArgs) { }
public override void Render(DrawArgs drawArgs) { using (new DirectXProfilerEvent("PolygonFeature::Render")) { if (!this.isInitialized /*|| m_vertices == null*/ || drawArgs.WorldCamera.Altitude < this.m_minimumDisplayAltitude || drawArgs.WorldCamera.Altitude > this.m_maximumDisplayAltitude) { return; } if (!drawArgs.WorldCamera.ViewFrustum.Intersects(this.BoundingBox)) { return; } // save state Cull currentCull = drawArgs.device.GetRenderState <Cull>(RenderState.CullMode); bool currentZBufferEnable = drawArgs.device.GetRenderState <bool>(RenderState.ZEnable); try { drawArgs.device.SetRenderState(RenderState.CullMode, Cull.None); drawArgs.device.SetRenderState(RenderState.ZEnable, this.m_ZBufferEnable); drawArgs.device.SetTransform(TransformState.World, Matrix.Translation( (float)-drawArgs.WorldCamera.ReferenceCenter.X + this.m_localOrigin.X, (float)-drawArgs.WorldCamera.ReferenceCenter.Y + this.m_localOrigin.Y, (float)-drawArgs.WorldCamera.ReferenceCenter.Z + this.m_localOrigin.Z )); if (World.Settings.EnableSunShading) { Point3d sunPosition = SunCalculator.GetGeocentricPosition(TimeKeeper.CurrentTimeUtc); Vector3 sunVector = new Vector3( (float)sunPosition.X, (float)sunPosition.Y, (float)sunPosition.Z); drawArgs.device.SetRenderState(RenderState.Lighting, true); Material material = new Material(); material.Diffuse = Color.White.ToRawColor4();; material.Ambient = Color.White.ToRawColor4();; drawArgs.device.Material = material; drawArgs.device.SetRenderState(RenderState.Ambient, World.Settings.ShadingAmbientColor.ToArgb()); drawArgs.device.SetRenderState(RenderState.NormalizeNormals, true); drawArgs.device.SetRenderState(RenderState.AlphaBlendEnable, true); Light lLight = new Light { Diffuse = System.Drawing.Color.White.ToRawColor4(), Type = LightType.Directional, Range = 100000, Direction = sunVector, }; drawArgs.device.SetLight(0, ref lLight); drawArgs.device.SetTextureStageState(0, TextureStage.ColorOperation, TextureOperation.Modulate); drawArgs.device.SetTextureStageState(0, TextureStage.ColorArg1, TextureArgument.Diffuse); drawArgs.device.SetTextureStageState(0, TextureStage.ColorArg2, TextureArgument.Texture); } else { drawArgs.device.SetRenderState(RenderState.Lighting, false); drawArgs.device.SetRenderState(RenderState.Ambient, World.Settings.StandardAmbientColor.ToArgb()); } //if(m_vertices != null) if (this.Fill) { if (this.primList.Count > 0) { drawArgs.device.VertexFormat = CustomVertex.PositionNormalColored.Format; drawArgs.device.SetTextureStageState(0, TextureStage.ColorOperation, TextureOperation.Disable); for (int i = 0; i < this.primList.Count; i++) { int vertexCount = 0; PrimitiveType primType = (PrimitiveType)this.primTypes[i]; CustomVertex.PositionNormalColored[] vertices = (CustomVertex.PositionNormalColored[]) this.primList[i]; if (primType == PrimitiveType.TriangleList) { vertexCount = vertices.Length / 3; } else { vertexCount = vertices.Length - 2; } drawArgs.device.DrawUserPrimitives( primType,//PrimitiveType.TriangleList, vertexCount, vertices); } } } if (this.m_lineFeature != null) { for (int i = 0; i < this.m_lineFeature.Length; i++) { if (this.m_lineFeature[i] != null) { this.m_lineFeature[i].Render(drawArgs); } } } } catch (Exception ex) { Log.Write(ex); } finally { // restore device state drawArgs.device.SetTransform(TransformState.World, drawArgs.WorldCamera.WorldMatrix); drawArgs.device.SetRenderState(RenderState.CullMode, currentCull); drawArgs.device.SetRenderState(RenderState.ZEnable, currentZBufferEnable); } } }
/// <summary> /// Draws the layer /// </summary> public override void Render(DrawArgs drawArgs) { if(this.downloadThread != null && this.downloadThread.IsAlive) this.RenderProgress(drawArgs); if(!this.isInitialized) return; try { if(this.texture == null || this.m_SurfaceImage != null) return; drawArgs.device.SetTexture(0, this.texture); if(this._disableZbuffer) { if(drawArgs.device.GetRenderState<bool>(RenderState.ZEnable)) drawArgs.device.SetRenderState(RenderState.ZEnable , false); } else { if(!drawArgs.device.GetRenderState<bool>(RenderState.ZEnable)) drawArgs.device.SetRenderState(RenderState.ZEnable , true); } drawArgs.device.SetRenderState(RenderState.ZEnable , true); drawArgs.device.Clear(ClearFlags.ZBuffer, System.Drawing.Color.Black.ToRawColorBGRA(), 1.0f, 0); drawArgs.device.SetTransform(TransformState.World, Matrix.Translation( (float)-drawArgs.WorldCamera.ReferenceCenter.X, (float)-drawArgs.WorldCamera.ReferenceCenter.Y, (float)-drawArgs.WorldCamera.ReferenceCenter.Z )); this.device.VertexFormat = CustomVertex.PositionNormalTextured.Format; if (!this.RenderGrayscale || (this.device.Capabilities.PixelShaderVersion.Major < 1)) { if (World.Settings.EnableSunShading) { Point3d sunPosition = SunCalculator.GetGeocentricPosition(TimeKeeper.CurrentTimeUtc); Vector3 sunVector = new Vector3( (float)sunPosition.X, (float)sunPosition.Y, (float)sunPosition.Z); this.device.SetRenderState(RenderState.Lighting , true); Material material = new Material(); material.Diffuse = System.Drawing.Color.White.ToRawColor4(); material.Ambient = System.Drawing.Color.White.ToRawColor4(); this.device.Material = material; this.device.SetRenderState(RenderState.Ambient , World.Settings.ShadingAmbientColor.ToArgb()); this.device.SetRenderState(RenderState.NormalizeNormals , true); this.device.SetRenderState(RenderState.AlphaBlendEnable , true); Light lLight = new Light { Diffuse = System.Drawing.Color.White.ToRawColor4(), Type = LightType.Directional, Range = 100000, Direction = sunVector, }; drawArgs.device.SetLight(0, ref lLight); this.device.SetTextureStageState(0, TextureStage.ColorOperation , TextureOperation.Modulate); this.device.SetTextureStageState(0, TextureStage.ColorArg1, TextureArgument.Diffuse); this.device.SetTextureStageState(0, TextureStage.ColorArg2,TextureArgument.Texture); } else { this.device.SetRenderState(RenderState.Lighting , false); this.device.SetRenderState(RenderState.Ambient , World.Settings.StandardAmbientColor.ToArgb()); drawArgs.device.SetTextureStageState(0, TextureStage.ColorOperation , TextureOperation.SelectArg1); drawArgs.device.SetTextureStageState(0, TextureStage.ColorArg1, TextureArgument.Texture); } this.device.SetRenderState(RenderState.TextureFactor , System.Drawing.Color.FromArgb(this.m_opacity, 255, 255, 255).ToArgb()); this.device.SetTextureStageState(0, TextureStage.AlphaOperation, TextureOperation.Modulate); this.device.SetTextureStageState(0, TextureStage.AlphaArg1,TextureArgument.Texture); this.device.SetTextureStageState(0, TextureStage.AlphaArg2,TextureArgument.TFactor); drawArgs.device.VertexFormat = CustomVertex.PositionNormalTextured.Format; drawArgs.device.DrawIndexedUserPrimitives(PrimitiveType.TriangleList, 0, this.vertices.Length, this.indices.Length / 3, this.indices, Format.Index16, this.vertices); } else { if (grayscaleEffect == null) { this.device.DeviceReset += new EventHandler(this.device_DeviceReset); this.device_DeviceReset(this.device, null); } grayscaleEffect.Technique = "RenderGrayscaleBrightness"; grayscaleEffect.SetValue("WorldViewProj", Matrix.Multiply(this.device.SetTransform(TransformState.World, Matrix.Multiply(this.device.SetTransform(TransformState.View, this.device.SetTransform(TransformState.Projection))); grayscaleEffect.SetValue("Tex0", this.texture.NativePointer); grayscaleEffect.SetValue("Brightness", this.GrayscaleBrightness); float opacity = (float) this.m_opacity / 255.0f; grayscaleEffect.SetValue("Opacity", opacity); int numPasses = grayscaleEffect.Begin(0); for (int i = 0; i < numPasses; i++) { grayscaleEffect.BeginPass(i); drawArgs.device.DrawIndexedUserPrimitives(PrimitiveType.TriangleList, 0, this.vertices.Length, this.indices.Length / 3, this.indices, Format.Index16, this.vertices); grayscaleEffect.EndPass(); } grayscaleEffect.End(); } drawArgs.device.SetTransform(TransformState.World, drawArgs.WorldCamera.WorldMatrix); } finally { if (this.m_opacity < 255) { // Restore alpha blend state this.device.SetRenderState(RenderState.SourceBlend , Blend.SourceAlpha); this.device.SetRenderState(RenderState.DestinationBlend , Blend.InverseSourceAlpha); } if(this._disableZbuffer) drawArgs.device.SetRenderState(RenderState.ZEnable , true); } }
/// <summary> /// Handle mouse click /// </summary> /// <returns>true if click was handled.</returns> public override bool PerformSelectionAction(DrawArgs drawArgs) { return false; }
bool showGlow = false; // If shadows on, will render an atmospheric glow /// <summary> /// Constructor /// </summary> public PlanetaryRingsLayer(string LayerName, string pluginPath, WorldWindow worldWindow) : base(LayerName) { this.pluginPath = pluginPath; this.pluginName = LayerName; this.world = worldWindow.CurrentWorld; this.settingsFileName = this.world.Name + ".ini"; this.drawArgs = worldWindow.DrawArgs; this.RenderPriority = RenderPriority.AtmosphericImages; this.IsOn = false; ReadSettings(); }
public void GoTo(DrawArgs drawArgs) { drawArgs.WorldCamera.SetPosition(this.Latitude, this.Longitude, this.OnClickZoomHeading, this.OnClickZoomAltitude, this.OnClickZoomTilt); this.m_gotoMe = false; }
/// <summary> /// RenderableObject abstract member (needed) /// OBS: Worker thread (don't update UI directly from this thread) /// </summary> public override void Initialize(DrawArgs drawArgs) { try { texture = TextureLoader.FromFile(drawArgs.device, Path.Combine(pluginPath, textureFileName)); textureInverted = LoadtextureInverted(drawArgs.device, Path.Combine(pluginPath, textureFileName)); isInitialized = true; } catch { isOn = false; MessageBox.Show("Error loading texture " + Path.Combine(pluginPath, textureFileName) + ".", "Layer initialization failed.", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Initialize(DrawArgs drawArgs) { if (m_autoSize) ComputeAutoSize (drawArgs); m_isInitialized = true; }
/// <summary> /// This is where we do our rendering /// Called from UI thread = UI code safe in this function /// </summary> public override void Render(DrawArgs drawArgs) { if(!IsOn) return; if(!isInitialized) return; base.Render(drawArgs); }
private Mesh RingShadow(DrawArgs drawArgs) { //MessageBox.Show("Shadow mesh start", "Info", MessageBoxButtons.OK, MessageBoxIcon.Error ); // Camera and device shortcuts ;) CameraBase camera = drawArgs.WorldCamera; Device device = drawArgs.device; // Find shadow outer radius double equatorialRadius = camera.WorldRadius; double polarRadius = equatorialRadius * 1.0; // Flattening factor here double shadowRadius = equatorialRadius * 10; // Default if sun lat = 0; if (sunLat != 0) shadowRadius = polarRadius / Math.Tan(MathEngine.DegreesToRadians(sunLat)); if (shadowRadius < 0) shadowRadius *= -1; int stacks = 128; int slices = 12; int numVertices, numFaces; if (shadowRadius < outRadius) { numVertices = (slices + 1) + (stacks + 1) * 2 + 1; numFaces = slices + stacks * 2; } else { numVertices = (slices + 1) * 2 + (stacks + 1) * 2 + 1; numFaces = (slices + stacks) * 2; } int indexCount = numFaces * 3; Mesh mesh = new Mesh(numFaces, numVertices, MeshFlags.Managed, CustomVertex.PositionColored.Format, device); // Get the original mesh vertex buffer. int[] ranks = new int[1]; ranks[0] = mesh.NumberVertices; System.Array arr = mesh.VertexBuffer.Lock(0, typeof(CustomVertex.PositionColored), LockFlags.None, ranks); // Set the vertex buffer int vertIndex = 0; CustomVertex.PositionColored pnt; int shadowColor = Color.FromArgb(shadowOpacity, 0x00, 0x00, 0x00).ToArgb(); // Add central vertice pnt = new CustomVertex.PositionColored(); pnt.X = (float)(inRadius + ((outRadius - inRadius) * 0.9)); if (shadowRadius < outRadius) pnt.X = (float)(inRadius + ((shadowRadius - inRadius) * 0.9)); pnt.Y = 0.0f; pnt.Z = 0.0f; pnt.Color = shadowColor; arr.SetValue(pnt, vertIndex++); // Find start and end points along inner and outer edge of rings double er2 = equatorialRadius * equatorialRadius; double sr2 = shadowRadius * shadowRadius; double inr2 = inRadius * inRadius; double outr2 = outRadius * outRadius; double p1y2 = er2 * (1 - inr2 / sr2) / (1 - er2 / sr2); // Start point (inner) double p1y = Math.Sqrt(p1y2); double p1x = Math.Sqrt(inr2 - p1y2); double p2x, p2y; if (shadowRadius < outRadius) { // End point (outer) p2y = 0; p2x = shadowRadius; } else { double p2y2 = er2 * (1 - outr2 / sr2) / (1 - er2 / sr2); p2y = Math.Sqrt(p2y2); p2x = Math.Sqrt(outr2 - p2y2); } // Shadow edges double stepX = (p2x - p1x) / stacks; for (int stack = 0; stack <= stacks; stack++) { double px = p1x + stepX * stack; double px2 = px * px; double py = Math.Sqrt(er2 * (1 - px2 / sr2)); pnt = new CustomVertex.PositionColored(); pnt.X = (float)px; pnt.Y = (float)py; pnt.Z = 0.0f; pnt.Color = shadowColor; arr.SetValue(pnt, vertIndex++); pnt = new CustomVertex.PositionColored(); pnt.X = (float)px; pnt.Y = (float)-py; pnt.Z = 0.0f; pnt.Color = shadowColor; arr.SetValue(pnt, vertIndex++); } // Shadow inner edge Vector3 v = MathEngine.CartesianToSpherical((float)p1x, (float)p1y, 0f); double p1Lon = MathEngine.RadiansToDegrees(v.Z); double stepLon = -p1Lon * 2 / slices; for (int slice = 1; slice < slices; slice++) { v = MathEngine.SphericalToCartesian(0, p1Lon + slice * stepLon, inRadius); pnt = new CustomVertex.PositionColored(); pnt.X = v.X; pnt.Y = v.Y; pnt.Z = v.Z; pnt.Color = shadowColor; arr.SetValue(pnt, vertIndex++); } // Shadow outer edge if (shadowRadius > outRadius) { v = MathEngine.CartesianToSpherical((float)p2x, (float)p2y, 0f); double p2Lon = MathEngine.RadiansToDegrees(v.Z); stepLon = -p2Lon * 2 / slices; for (int slice = 1; slice < slices; slice++) { v = MathEngine.SphericalToCartesian(0, p2Lon + slice * stepLon, outRadius); pnt = new CustomVertex.PositionColored(); pnt.X = v.X; pnt.Y = v.Y; pnt.Z = v.Z; pnt.Color = shadowColor; arr.SetValue(pnt, vertIndex++); } } mesh.VertexBuffer.Unlock(); // Create indices ranks[0] = indexCount; arr = mesh.LockIndexBuffer(typeof(short), LockFlags.None, ranks); int i = 0; // Edges for (short x = 0; x < stacks; x++) { arr.SetValue((short)0, i++); arr.SetValue((short)(x * 2 + 1), i++); arr.SetValue((short)(x * 2 + 3), i++); arr.SetValue((short)(x * 2 + 2), i++); arr.SetValue((short)0, i++); arr.SetValue((short)(x * 2 + 4), i++); } // Inner edge short vert = (short)((stacks - 1) * 2 + 4 + 1); arr.SetValue((short)0, i++); arr.SetValue((short)vert, i++); arr.SetValue((short)1, i++); for (short x = 1; x < slices - 1; x++) { arr.SetValue((short)0, i++); arr.SetValue((short)(vert + 1), i++); arr.SetValue((short)(vert), i++); vert++; } arr.SetValue((short)0, i++); arr.SetValue((short)2, i++); arr.SetValue((short)vert, i++); vert++; // Shadow outer edge if (shadowRadius > outRadius) { arr.SetValue((short)0, i++); arr.SetValue((short)(stacks * 2 + 1), i++); arr.SetValue((short)vert, i++); for (short x = 1; x < slices - 1; x++) { arr.SetValue((short)0, i++); arr.SetValue((short)(vert), i++); arr.SetValue((short)(vert + 1), i++); vert++; } arr.SetValue((short)0, i++); arr.SetValue((short)vert, i++); arr.SetValue((short)(stacks * 2 + 2), i++); } mesh.IndexBuffer.SetData(arr, 0, LockFlags.None); //MessageBox.Show("Shadow mesh done" + shadowRadius.ToString(), "Info", MessageBoxButtons.OK, MessageBoxIcon.Error ); return mesh; }
public void Update(DrawArgs drawArgs) { try { double centerLatitude = 0.5 * (m_geographicBoundingBox.North + m_geographicBoundingBox.South); double centerLongitude = 0.5 * (m_geographicBoundingBox.West + m_geographicBoundingBox.East); double tileSize = m_geographicBoundingBox.North - m_geographicBoundingBox.South; if (!m_Initialized) { if (drawArgs.WorldCamera.ViewRange * 0.5f < Angle.FromDegrees(ShapeTileArgs.TileDrawDistance * tileSize) && MathEngine.SphericalDistance(Angle.FromDegrees(centerLatitude), Angle.FromDegrees(centerLongitude), drawArgs.WorldCamera.Latitude, drawArgs.WorldCamera.Longitude) < Angle.FromDegrees(ShapeTileArgs.TileSpreadFactor * tileSize * 1.25f) && drawArgs.WorldCamera.ViewFrustum.Intersects(BoundingBox) ) { Initialize(drawArgs); } } if (m_Initialized) { if (m_LastUpdate < m_parentProjectedLayer.LastUpdate) { UpdateImageLayers(drawArgs); } if (m_NwImageLayer != null) { m_NwImageLayer.Update(drawArgs); } if (m_NeImageLayer != null) { m_NeImageLayer.Update(drawArgs); } if (m_SwImageLayer != null) { m_SwImageLayer.Update(drawArgs); } if (m_SeImageLayer != null) { m_SeImageLayer.Update(drawArgs); } if ( drawArgs.WorldCamera.ViewRange < Angle.FromDegrees(ShapeTileArgs.TileDrawDistance * tileSize) && MathEngine.SphericalDistance(Angle.FromDegrees(centerLatitude), Angle.FromDegrees(centerLongitude), drawArgs.WorldCamera.Latitude, drawArgs.WorldCamera.Longitude) < Angle.FromDegrees(ShapeTileArgs.TileSpreadFactor * tileSize) && drawArgs.WorldCamera.ViewFrustum.Intersects(BoundingBox) ) { if (m_NorthEastChild == null && m_NorthWestChild == null && m_SouthEastChild == null && m_SouthWestChild == null) { ComputeChildren(drawArgs); } else { if (m_NorthEastChild != null) { m_NorthEastChild.Update(drawArgs); } if (m_NorthWestChild != null) { m_NorthWestChild.Update(drawArgs); } if (m_SouthEastChild != null) { m_SouthEastChild.Update(drawArgs); } if (m_SouthWestChild != null) { m_SouthWestChild.Update(drawArgs); } } } else { if (m_NorthWestChild != null) { m_NorthWestChild.Dispose(); m_NorthWestChild = null; } if (m_NorthEastChild != null) { m_NorthEastChild.Dispose(); m_NorthEastChild = null; } if (m_SouthEastChild != null) { m_SouthEastChild.Dispose(); m_SouthEastChild = null; } if (m_SouthWestChild != null) { m_SouthWestChild.Dispose(); m_SouthWestChild = null; } } } if (m_Initialized) { if (drawArgs.WorldCamera.ViewRange > Angle.FromDegrees(ShapeTileArgs.TileDrawDistance * tileSize * 1.5f) || MathEngine.SphericalDistance(Angle.FromDegrees(centerLatitude), Angle.FromDegrees(centerLongitude), drawArgs.WorldCamera.Latitude, drawArgs.WorldCamera.Longitude) > Angle.FromDegrees(ShapeTileArgs.TileSpreadFactor * tileSize * 1.5f)) { if (this.Level != 0) { //{ Dispose(); } //} } } } catch (Exception ex) { Log.Write(ex); } }
/// <summary> /// This is where we do our rendering /// Called from UI thread = UI code safe in this function /// </summary> public override void Render(DrawArgs drawArgs) { if (!isInitialized) return; if (CheckMoonLayer) FindMoonLayer(); // Check if we have a moon layer if (MoonLayer != null) { if (MoonLayer.IsOn) return; // if moon layer on, no rings } // Camera and device shortcuts ;) CameraBase camera = drawArgs.WorldCamera; Device device = drawArgs.device; // Check WW sun shading setting WW 1.4 bool WWSunShading = World.Settings.EnableSunShading; // Camera position Vector3 cameraPos = camera.Position; Vector3 cameraCoord = MathEngine.CartesianToSpherical(cameraPos.X, cameraPos.Y, cameraPos.Z); float camLat = cameraCoord.Y; // Use current world radius for ring proportion inRadius = camera.WorldRadius * inFactor; outRadius = camera.WorldRadius * outFactor; // Create rings and occlusion mesh(s) if (layerMesh == null) layerMesh = TexturedRings(device, (float)inRadius, (float)outRadius, 128, 1); if (occlusionMesh == null) occlusionMesh = ColoredSphere(device, (float)camera.WorldRadius, 64, 32); // Adjust sun latitude with camera latitude if not locked // or use WW sun pos if SunShading on if (!sunLocked) { sunLat = MathEngine.RadiansToDegrees(sunInvert ? -camLat : camLat); sunLatBak = sunLat; // update Saved sun lat } else { if (WWSunShading) { // Reading current WorldWind Sun position (WW 1.4) Point3d sunPosition = -SunCalculator.GetGeocentricPosition(TimeKeeper.CurrentTimeUtc); Point3d sunSpherical = MathEngine.CartesianToSphericalD(sunPosition.X, sunPosition.Y, sunPosition.Z); sunLat = MathEngine.RadiansToDegrees(sunSpherical.Y); sunLon = MathEngine.RadiansToDegrees(sunSpherical.Z); } else { sunLat = sunLatBak; sunLon = sunLonBak; } } // Save fog status bool origFog = device.RenderState.FogEnable; device.RenderState.FogEnable = false; // Save original projection Matrix origProjection = device.Transform.Projection; Matrix origWorld = device.Transform.World; // Set new one (to avoid being clipped) - probably better ways of doing this? float aspectRatio = (float)device.Viewport.Width / device.Viewport.Height; float near = (float)(camera.WorldRadius + camera.Altitude - outRadius); float far = (float)(camera.WorldRadius + camera.Altitude + outRadius); if (near < 10000) near = 10000; device.Transform.Projection = Matrix.PerspectiveFovRH((float)camera.Fov.Radians, aspectRatio, near, far); // No lighting please device.RenderState.Lighting = false; device.RenderState.Ambient = Color.White; // Draw atmospheric glow if ((shadowsOn || WWSunShading) && showGlow) { if (glowMesh == null || sunLat != shadowsLat) { if (glowMesh != null) glowMesh.Dispose(); glowMesh = AtmoSphere(device, (float)(camera.WorldRadius + 100000), 64, 32); } // Set world transform device.Transform.World = Matrix.Identity; Recenter(drawArgs); // No ZBuffer device.RenderState.ZBufferEnable = false; // No texture device.SetTexture(0, null); // Alpha blending device.RenderState.AlphaBlendEnable = true; device.RenderState.SourceBlend = Blend.SourceAlpha; device.RenderState.DestinationBlend = Blend.InvSourceAlpha; //device.RenderState.BlendOperation = BlendOperation.Min // Here we add the vertex colors (black) with the standard texture device.TextureState[0].ColorOperation = TextureOperation.SelectArg2; device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse; // No more further texture stages device.TextureState[1].ColorOperation = TextureOperation.Disable; // Take the alpha channel from the standard texture as result device.TextureState[0].AlphaOperation = TextureOperation.SelectArg2; device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse; // No further alpha stages device.TextureState[1].AlphaOperation = TextureOperation.Disable; // Draw glowMesh.DrawSubset(0); // Restore world transform device.Transform.World = origWorld; } // Draw rings projected shadows on day side if ((shadowsOn || WWSunShading) && showRingsShadow) { if (projMesh == null || sunLat != shadowsLat) { if (projMesh != null) projMesh.Dispose(); projMesh = ProjectedRings(device, (float)(camera.WorldRadius + 100000), 128, 64); } // Set world transform according to sun lat/lon device.Transform.World = Matrix.Identity; if (sunLat > 0) device.Transform.World *= Matrix.RotationX((float)Math.PI); device.Transform.World *= Matrix.RotationY((float)MathEngine.DegreesToRadians(-sunLat)); device.Transform.World *= Matrix.RotationZ((float)MathEngine.DegreesToRadians(sunLon)); Recenter(drawArgs); // No ZBuffer device.RenderState.ZBufferEnable = false; // Texture set up and filtering // Here we add the vertex colors (black) with the standard texture device.TextureState[0].ColorOperation = TextureOperation.Add; device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor; device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse; // No more further texture stages device.TextureState[1].ColorOperation = TextureOperation.Disable; // Take the alpha channel from the standard texture as result device.TextureState[0].AlphaOperation = TextureOperation.Modulate; device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor; device.TextureState[0].AlphaArgument2 = TextureArgument.Diffuse; // No further alpha stages device.TextureState[1].AlphaOperation = TextureOperation.Disable; device.SamplerState[0].MipFilter = TextureFilter.Linear; device.SamplerState[0].MinFilter = TextureFilter.Linear; device.SamplerState[0].MagFilter = TextureFilter.Linear; device.SetTexture(0, textureInverted); // Draw projMesh.DrawSubset(0); // Restore world transform device.Transform.World = origWorld; } // Draw shadows on night side if ((shadowsOn || WWSunShading) && showNightSide) { if (nightSideMesh == null) nightSideMesh = NightSideShadow(device, (float)(camera.WorldRadius + 100000), 64, 64); // Set world transform according to sun lat/lon device.Transform.World = Matrix.RotationY((float)MathEngine.DegreesToRadians(sunLat + 90)); device.Transform.World *= Matrix.RotationZ((float)MathEngine.DegreesToRadians(sunLon + 180)); Recenter(drawArgs); // Draw night side shadow device.RenderState.ZBufferEnable = false; device.SetTexture(0, null); nightSideMesh.DrawSubset(0); // Restore world transform device.Transform.World = origWorld; } // Use ZBuffer device.RenderState.ZBufferEnable = true; // Clear ZBuffer device.Clear(ClearFlags.ZBuffer, Color.Black, 1.0f, 0); // Recenter world transform Recenter(drawArgs); // Draw occlusion sphere to ZBuffer only // Enable alpha blending in the device effectively disabling drawing to target device.RenderState.SourceBlend = Blend.Zero; device.RenderState.DestinationBlend = Blend.One; device.RenderState.AlphaBlendEnable = true; device.SetTexture(0, null); device.RenderState.CullMode = Cull.Clockwise; occlusionMesh.DrawSubset(0); // Draw device.RenderState.SourceBlend = Blend.SourceAlpha; device.RenderState.DestinationBlend = Blend.InvSourceAlpha; // Show top side of rings if above equator if (camLat > 0) device.RenderState.CullMode = Cull.CounterClockwise; // Texture set up and filtering device.TextureState[0].ColorOperation = TextureOperation.BlendCurrentAlpha; drawArgs.device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor; drawArgs.device.TextureState[0].ColorArgument2 = TextureArgument.Diffuse; drawArgs.device.TextureState[0].AlphaOperation = TextureOperation.SelectArg1; drawArgs.device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor; device.SamplerState[0].MipFilter = TextureFilter.Linear; device.SamplerState[0].MinFilter = TextureFilter.Linear; device.SamplerState[0].MagFilter = TextureFilter.Linear; // Decide upon texture or inverted texture device.SetTexture(0, (camLat * sunLat < 0 && shadowsOn && showUnlitSide) ? textureInverted : texture); // Dont write to ZBuffer this time device.RenderState.ZBufferWriteEnable = false; // Draw rings layerMesh.DrawSubset(0); // Restore world transform device.Transform.World = origWorld; // Draw shadows on rings if ((shadowsOn || WWSunShading) && showGlobeShadow) { if (shadowsMesh == null || sunLat != shadowsLat) { if (shadowsMesh != null) shadowsMesh.Dispose(); shadowsMesh = RingShadow(drawArgs); shadowsLat = sunLat; } // Set world transform according to sun lon //float offsetZ = (camLat > 0) ? 1000000f : -1000000f; //device.Transform.World = Matrix.Translation(0, 0, offsetZ); device.Transform.World = Matrix.RotationZ((float)MathEngine.DegreesToRadians(sunLon + 180)); Recenter(drawArgs); // Draw shadow on rings device.SetTexture(0, null); shadowsMesh.DrawSubset(0); } // Restore device states device.RenderState.CullMode = Cull.Clockwise; device.Transform.Projection = origProjection; device.Transform.World = origWorld; device.RenderState.ZBufferEnable = true; device.RenderState.ZBufferWriteEnable = true; device.RenderState.FogEnable = origFog; // Clear ZBuffer again device.Clear(ClearFlags.ZBuffer, Color.Black, 1.0f, 0); }
/// <summary> /// Intialize Polygon with Tessalation /// </summary> /// <param name="drawArgs"></param> public override void Initialize(DrawArgs drawArgs) { this.UpdateVertices(); this.isInitialized = true; }
/// <summary> /// RenderableObject abstract member (needed) /// OBS: Worker thread (don't update UI directly from this thread) /// </summary> public override void Initialize(DrawArgs drawArgs) { // Add us to the list of renderable objects - this puts us in the render loop Dispose(); ArrayList SatelliteList; SatelliteList = GetFromWeb(this.tlepath); SatelliteList.Sort(); LoadMesh(drawArgs); try //Make sure the overlay is on. An error will turn it off { for(int x = 0; x < SatelliteList.Count;x++) { Tle twoLineElement = (Tle) SatelliteList[x]; //Check for a specific satellite mesh SatelliteTrack iss = new SatelliteTrack(this.Plugin.PluginDirectory ,twoLineElement ); this.Add(iss); } SetChildrenModelScale(m_scale); } catch(Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); this.IsOn=false; } this.drawArgs = drawArgs; isInitialized = true; }
public string presetFileName; // preset file (will overide defaults) /// <summary> /// Constructor /// </summary> public SkyGradientLayer(string LayerName, string pluginPath, WorldWindow worldWindow) : base(LayerName) { this.pluginPath = pluginPath; this.pluginName = LayerName; this.world = worldWindow.CurrentWorld; this.settingsFileName = this.world.Name + ".ini"; this.drawArgs = worldWindow.DrawArgs; //this.RenderPriority = RenderPriority.AtmosphericImages; this.RenderPriority = RenderPriority.SurfaceImages; ReadSettings(); }
public override void Update(DrawArgs drawArgs) { try { if(!this.IsOn) return; if(!this.isInitialized) this.Initialize(drawArgs); foreach(RenderableObject ro in this.m_children) { if(ro.IsOn) { ro.Update(drawArgs); } } } catch(Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); //Critical error, turn off layer this.IsOn=false; throw ex; } base.Update (drawArgs); }
// Recenter world projection in WW 1.4 public void Recenter(DrawArgs drawArgs) { drawArgs.device.Transform.World *= Matrix.Translation( (float)-drawArgs.WorldCamera.ReferenceCenter.X, (float)-drawArgs.WorldCamera.ReferenceCenter.Y, (float)-drawArgs.WorldCamera.ReferenceCenter.Z ); }
public override void Render(DrawArgs drawArgs) { try { if(!isInitialized || mesh==null) return; m_elapsedMinutes = orbit.TPlusEpoch()/60; // Calculating orbit for all the satellites is cumbersome only calculate if shown if(m_showTrack) { DrawTrack(drawArgs); } Eci eci = orbit.getPosition(m_elapsedMinutes); CoordGeo cog = eci.toGeo(); if(isFirstRun) { isFirstRun=false; } m_Lat = cog.Latitude ; m_Lon = cog.Longitude ; m_Alt = cog.Altitude ; if(m_cameraFollows) drawArgs.WorldCamera.SetPosition(Angle.FromRadians(cog.Latitude ).Degrees, Angle.FromRadians(cog.Longitude ).Degrees, double.NaN, double.NaN, double.NaN); drawArgs.device.RenderState.CullMode = Cull.None; drawArgs.device.RenderState.Lighting = true; drawArgs.device.RenderState.Ambient = Color.Black; drawArgs.device.RenderState.NormalizeNormals = true; drawArgs.device.Lights[0].Diffuse = Color.FromArgb(255, 255, 215); drawArgs.device.Lights[0].Type = LightType.Directional; drawArgs.device.Lights[0].Direction = new Vector3(1f,1f,1f); drawArgs.device.Lights[0].Enabled = true; Vector3 sv = MathEngine.SphericalToCartesian(Angle.FromRadians(cog.Latitude), Angle.FromRadians(cog.Longitude ), drawArgs.WorldCamera.WorldRadius + cog.Altitude *1000 ); Vector3 xyzPosition = sv; drawArgs.device.Lights[0].Position = new Vector3( (float)sv.X*2, (float)sv.Y*2, (float)sv.Z); drawArgs.device.RenderState.AlphaBlendEnable = true; drawArgs.device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor; drawArgs.device.TextureState[0].ColorOperation = TextureOperation.SelectArg1; drawArgs.device.SamplerState[0].MipFilter = TextureFilter.Anisotropic; drawArgs.device.SamplerState[0].MipMapLevelOfDetailBias = -1; drawArgs.device.SamplerState[0].AddressU = TextureAddress.Mirror; drawArgs.device.SamplerState[0].AddressV = TextureAddress.Mirror; Matrix currentWorld = drawArgs.device.Transform.World; drawArgs.device.Transform.World = Matrix.Identity; drawArgs.device.Transform.World *= Matrix.Scaling(m_scale, m_scale, m_scale); //TODO: Change to Allow Speeding up of time double time = TimeKeeper.CurrentTimeUtc.TimeOfDay.TotalSeconds/60; double fraction = time-Math.Round(time); drawArgs.device.Transform.World *= Matrix.RotationX((float)(fraction*Math.PI*2)); drawArgs.device.Transform.World *= Matrix.Translation( (float)sv.X, (float)sv.Y, (float)sv.Z); drawArgs.device.Transform.World *= Matrix.Translation( (float)-drawArgs.WorldCamera.ReferenceCenter.X, (float)-drawArgs.WorldCamera.ReferenceCenter.Y, (float)-drawArgs.WorldCamera.ReferenceCenter.Z ); drawArgs.device.RenderState.ZBufferEnable = true; for( int i = 0; i < meshMaterials.Length; i++ ) { drawArgs.device.Material = meshMaterials[i]; Texture texture = meshTextures[i]; drawArgs.device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor; drawArgs.device.SetTexture(0, texture); mesh.DrawSubset(i); } drawArgs.device.Transform.World = currentWorld; drawArgs.device.RenderState.Lighting = false; drawArgs.device.RenderState.CullMode = Cull.Clockwise; Vector3 rc = new Vector3( (float)drawArgs.WorldCamera.ReferenceCenter.X, (float)drawArgs.WorldCamera.ReferenceCenter.Y, (float)drawArgs.WorldCamera.ReferenceCenter.Z ); Vector3 projectedPoint = drawArgs.WorldCamera.Project(xyzPosition - rc); Ray foundRay; int mouseBuffer = 15; // if (GetMeshIntersect(out foundRay, drawArgs.WorldCamera.WorldRadius, drawArgs.device.Viewport, // drawArgs.device.Transform.Projection, drawArgs.device.Transform.View, Matrix.Translation(sv), // DrawArgs.LastMousePosition.X, DrawArgs.LastMousePosition.Y)) if(projectedPoint.X >= DrawArgs.LastMousePosition.X - mouseBuffer && projectedPoint.X <= DrawArgs.LastMousePosition.X + mouseBuffer && projectedPoint.Y >= DrawArgs.LastMousePosition.Y - mouseBuffer && projectedPoint.Y <= DrawArgs.LastMousePosition.Y + mouseBuffer) { m_orbitColor = Color.FromArgb(m_opacity, Color.Purple).ToArgb(); ShowLabelData(drawArgs, projectedPoint); DrawTrack(drawArgs); } else { m_orbitColor = Color.FromArgb(m_opacity,255,255,22).ToArgb(); } } catch(Exception ex) { throw ex; } }
/// <summary> /// RenderableObject abstract member (needed) /// OBS: Worker thread (don't update UI directly from this thread) /// </summary> public override void Update(DrawArgs drawArgs) { if(!isInitialized) Initialize(drawArgs); }
/// <summary> /// Updates the array track with the future positions of the satellite. Called initially and then when the timer fires. /// </summary> /// <param name="drawArgs"></param> private void UpdateTrackPositions(DrawArgs drawArgs) { //Do not update the track every render, very CPU intensive. Update after the timer sets UpdateTrack //to true. if(UpdateTrack) { periodMin = (int) orbit.Period()/60; track = new CustomVertex.PositionColored[periodMin*m_trackorbits]; for(int i=0;i<track.Length;i++) { try { Eci e = orbit.getPosition(i+m_elapsedMinutes); CoordGeo cg = e.toGeo(); Vector3 s = MathEngine.SphericalToCartesian(Angle.FromRadians(cg.Latitude ), Angle.FromRadians(cg.Longitude ), drawArgs.WorldCamera.WorldRadius + cg.Altitude *1000 ); track[i].X = s.X; track[i].Y = s.Y; track[i].Z = s.Z; track[i].Color = m_orbitColor; } catch(Exception ex) { //Do not throw decayed orbit erroes. if(!ex.Message.Equals("Satellite orbit may have decayed")) throw ex; } } UpdateTrack = false; } }
/// <summary> /// Helper function to render icon texture. Broken out so that child classes can override this behavior. /// </summary> /// <param name="drawArgs"></param> /// <param name="sprite"></param> /// <param name="projectedPoint"></param> /// <param name="color">the color to render the icon</param> /// <param name="isMouseOver">Whether or not the mouse is over the icon</param> protected override void RenderTexture(DrawArgs drawArgs, Sprite sprite, Vector3 projectedPoint, int color, bool isMouseOver) { Matrix scaleTransform; Matrix rotationTransform; Matrix rotation2Transform; Matrix rotation3Transform; //Do Altitude depedent scaling for KMLIcons if (this.AutoScaleIcon) { float factor = 1; if (this.DistanceToIcon > this.MinIconZoomDistance) { factor -= (float)((this.DistanceToIcon - this.MinIconZoomDistance) / this.DistanceToIcon); } if (factor < this.MinScaleFactor) { factor = this.MinScaleFactor; } this.XScale = factor * ((float)this.Width / this.IconTexture.Width); this.YScale = factor * ((float)this.Height / this.IconTexture.Height); } //scale and rotate image scaleTransform = Matrix.Scaling(this.XScale, this.YScale, 0); if (this.IsRotated) { rotationTransform = Matrix.RotationZ((float)this.Rotation.Radians - (float)drawArgs.WorldCamera.Heading.Radians); } else { rotationTransform = Matrix.Identity; } sprite.Transform = scaleTransform * rotationTransform * Matrix.Translation(projectedPoint.X, projectedPoint.Y, 0); sprite.Draw(this.IconTexture.Texture, new Vector3(this.IconTexture.Width >> 1, this.IconTexture.Height >> 1, 0), Vector3.Zero, color); if (this.m_iconTexture2Show) { Matrix tmpMatrix = sprite.Transform; if (this.Texture2IsRotatedDifferent) { if (this.Texture2UseHeading) { rotation2Transform = Matrix.RotationZ((float)this.Rotation.Radians - (float)drawArgs.WorldCamera.Heading.Radians); } else { rotation2Transform = Matrix.RotationZ((float)this.Texture2Rotation.Radians - (float)drawArgs.WorldCamera.Heading.Radians); } sprite.Transform = scaleTransform * rotation2Transform * Matrix.Translation(projectedPoint.X, projectedPoint.Y, 0); } sprite.Draw(this.m_iconTexture2.Texture, new Vector3(this.m_iconTexture2.Width >> 1, this.m_iconTexture2.Height >> 1, 0), Vector3.Zero, normalColor); // restore the main texture transform if (this.Texture2IsRotatedDifferent) { sprite.Transform = tmpMatrix; } } if (this.m_iconTexture3Show) { if (this.Texture3IsRotatedDifferent) { if (this.Texture3UseHeading) { rotation3Transform = Matrix.RotationZ((float)this.Rotation.Radians - (float)drawArgs.WorldCamera.Heading.Radians); } else { rotation3Transform = Matrix.RotationZ((float)this.Texture3Rotation.Radians - (float)drawArgs.WorldCamera.Heading.Radians); } sprite.Transform = scaleTransform * rotation3Transform * Matrix.Translation(projectedPoint.X, projectedPoint.Y, 0); } sprite.Draw(this.m_iconTexture3.Texture, new Vector3(this.m_iconTexture3.Width >> 1, this.m_iconTexture3.Height >> 1, 0), Vector3.Zero, normalColor); } // Reset transform to prepare for text rendering later sprite.Transform = Matrix.Identity; }
private void ShowLabelData(DrawArgs drawArgs, Vector3 projectedPoint) { try { // Object with labels: In array // // / \ // / \ // |--------| /-----\ |---------| |--------| /-----\ |---------| // | W || B/C/D/AC|| E/F | | 0 || 1 || 2 | // |--------|-----------|---------| |--------|-----------|---------| // | X/Y |xxxxxxxxxxx| G | | 3 |xxxxx4xxxxx| 5 | // |--------|-----------|---------| |--------|-----------|---------| // | V | AA | H | | 6 | 7 | 8 | // |--------|-----------|---------| |--------|-----------|---------| // | T |xxxxxxxxxxx| M | | 9 |xxxxx10xxxx| 11 | // |--------|xxxxxxxxxxx|---------| |--------|xxxxxxxxxxx|---------| // | Z |-----------|J/K/L/N/P| | 12 |-----------| 14 | // |--------| R/AG |---------| |--------| 13 |---------| // |-----------| |-----------| String[] lblString = new String[15]; System.Globalization.NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat; nfi.NumberDecimalDigits = 4; bool Use2525B = false; switch(mStr_TrackData) { case "Labels": lblString[0] = "W"; lblString[1] = "B/C/D/AC"; lblString[2] = "E/F"; lblString[3] = "X/Y"; lblString[4] = ""; lblString[5] = "G"; lblString[6] = "V"; lblString[7] = "AA"; lblString[8] = "H"; lblString[9] = "T"; lblString[10] = ""; lblString[11] = "M"; lblString[12] = "Z"; lblString[13] = "R/AG"; lblString[14] = "JJ/KKKKK/L/N/PPPPP"; Use2525B = true; break; default: lblString[0] = DateTime.Now.ToUniversalTime().ToString("ddHHmmssZMMMyy"); lblString[1] = ""; lblString[2] = ""; lblString[3] = (m_Alt).ToString("0000") + "km/" + ToDDMMSS(Angle.FromRadians(m_Lat).Degrees)+","+ToDDMMSS(Angle.FromRadians(m_Lon).Degrees); lblString[4] = ""; lblString[5] = ""; lblString[6] = "Elapsed Min:" + m_elapsedMinutes.ToString("000000.00"); lblString[7] = ""; lblString[8] = ""; lblString[9] = orbit.SatName(); lblString[10] = ""; lblString[11] = ""; lblString[12] = "Period:" + periodMin.ToString() + " min"; lblString[13] = ""; lblString[14] = ""; break; } Rectangle[] lblRects = new Rectangle[15]; for (int i = 0; i < 15; i++) { lblRects[i] = drawArgs.defaultDrawingFont.MeasureString(null, lblString[i], DrawTextFormat.None, 0); } Rectangle rectMax = new Rectangle((int) projectedPoint.X, (int) projectedPoint.Y, 1, 1); for (int i = 0; i < 15; i++) { rectMax.Width = System.Math.Max(rectMax.Width, lblRects[i].Width); rectMax.Height = System.Math.Max(rectMax.Height , lblRects[i].Height ); } double XoffsetFactor = 1.5; if(!Use2525B) XoffsetFactor =1; rectMax.X = rectMax.X - (int) (rectMax.Width * XoffsetFactor); rectMax.Y = rectMax.Y - (int) (rectMax.Height * 2.5); //Max size of a rectangle int col, row = 0; Rectangle rectDraw = new Rectangle(rectMax.Location, rectMax.Size); Color color = Color.FromArgb(125,Color.Gray); for (int i = 0; i < 15; i++) { col = i % 3; row = i / 3; rectDraw.X = (int)rectMax.X + (rectMax.Width*col); rectDraw.Y = (int)rectMax.Y+ (rectMax.Height *row); //draw background box if(lblString[i].Length!=0) DrawBox(rectDraw.X,rectDraw.Y, rectMax.Size.Width,rectMax.Size.Height, 0.00f,color.ToArgb(),drawArgs.device); drawArgs.defaultDrawingFont.DrawText(null, lblString[i],rectDraw, DrawTextFormat.Right - col,Color.Yellow.ToArgb() ); } } catch(Exception ex) { string s = ex.Message; } //Draw box in lower right corder with data // string text = "2D MouseX:" + DrawArgs.LastMousePosition.X.ToString("000000") + // "\n2D MouseY:" +DrawArgs.LastMousePosition.Y.ToString("000000") ; // Rectangle bounds = drawArgs.defaultDrawingFont.MeasureString(null, text, DrawTextFormat.None, 0); // drawArgs.defaultDrawingFont.DrawText(null, text, // drawArgs.screenWidth-bounds.Width-5, drawArgs.screenHeight-bounds.Height-5, // Color.GreenYellow.ToArgb() ); }
public override void Initialize(DrawArgs drawArgs) { this.isInitialized = true; }
/// <summary> /// This is where we do our rendering /// Called from UI thread = UI code safe in this function /// </summary> public override void Render(DrawArgs drawArgs) { if(!isInitialized || (this.world.Name == "Earth" && World.Settings.EnableAtmosphericScattering)) return; // Camera & Device shortcuts ;) CameraBase camera = drawArgs.WorldCamera; Device device = drawArgs.device; //if(camera.Altitude > 200e3) return; Vector3 cameraPos = camera.Position; double distToCenterOfPlanet = (camera.Altitude + camera.WorldRadius); // Create or refresh SkyGradient dome if(mesh == null || lastAltitude != camera.Altitude) { // Compute distance to horizon and dome radius double tangentalDistance = Math.Sqrt( distToCenterOfPlanet*distToCenterOfPlanet - camera.WorldRadius*camera.WorldRadius); double domeRadius = tangentalDistance; // horizon latitude double horizonLat = (-Math.PI / 2 + Math.Acos(tangentalDistance / distToCenterOfPlanet)) * 180 / Math.PI; // zenith latitude double zenithLat = 90; if(camera.Altitude >= thickness) { double tangentalDistanceZenith = Math.Sqrt( distToCenterOfPlanet*distToCenterOfPlanet - (camera.WorldRadius + thickness)*(camera.WorldRadius + thickness)); zenithLat = (-Math.PI / 2 + Math.Acos(tangentalDistanceZenith / distToCenterOfPlanet)) * 180 / Math.PI; } if(camera.Altitude < thickness && camera.Altitude > thickness * 0.8) { zenithLat = (thickness - camera.Altitude) / (thickness - thickness * 0.8) * 90; } // new mesh if(mesh != null) mesh.Dispose(); mesh = ColoredSphere(device, (float)domeRadius, horizonLat, zenithLat, 128, 24); lastAltitude = camera.Altitude; } // set texture to null device.SetTexture(0,null); device.TextureState[0].ColorOperation = TextureOperation.BlendCurrentAlpha; device.VertexFormat = CustomVertex.PositionColored.Format; // save world and projection transform Matrix origWorld = device.Transform.World; Matrix origProjection = device.Transform.Projection; // move SkyGradient dome Matrix SkyGradientTrans; Vector3 cameraCoord = MathEngine.CartesianToSpherical(cameraPos.X, cameraPos.Y, cameraPos.Z); float camLat = cameraCoord.Y; float camLon = cameraCoord.Z; SkyGradientTrans = Matrix.Translation(0,0,(float)distToCenterOfPlanet); SkyGradientTrans = Matrix.Multiply(SkyGradientTrans, Matrix.RotationY(-camLat+(float)Math.PI/2)); SkyGradientTrans = Matrix.Multiply(SkyGradientTrans, Matrix.RotationZ(camLon)); device.Transform.World = SkyGradientTrans; // Recenter Recenter(drawArgs); // Save fog status bool origFog = device.RenderState.FogEnable; device.RenderState.FogEnable = false; // Set new one (to avoid being clipped) - probably better ways of doing this? float aspectRatio = (float)device.Viewport.Width / device.Viewport.Height; device.Transform.Projection = Matrix.PerspectiveFovRH((float)camera.Fov.Radians, aspectRatio, 1, float.MaxValue ); // draw //device.RenderState.FillMode = FillMode.WireFrame; mesh.DrawSubset(0); // Restore device states device.RenderState.FillMode = FillMode.Solid; device.Transform.World = origWorld; device.Transform.Projection = origProjection; device.RenderState.FogEnable = origFog; device.RenderState.ZBufferEnable = true; // Fog effect if(useFog) { // Compute distance to horizon and camera altitude double tangentalDistance = Math.Sqrt( distToCenterOfPlanet*distToCenterOfPlanet - camera.WorldRadius*camera.WorldRadius); float a = (float)camera.Altitude; device.RenderState.FogEnable = true; device.RenderState.FogColor = horizonColor; device.RenderState.FogTableMode = FogMode.Linear; device.RenderState.FogStart = a * nearFactor; device.RenderState.FogEnd = (float)tangentalDistance * farFactor; } }
/// <summary> /// This method updates the Icons to reflect only those in view /// </summary> /// <param name="drawArgs"></param> public override void Update(WorldWind.DrawArgs drawArgs) { base.Update(drawArgs); double distance = WorldWind.World.ApproxAngularDistance(drawArgs.WorldCamera.Latitude, drawArgs.WorldCamera.Longitude, this.lastUpdatelat, this.lastUpdatelon).Degrees; double altchange = Math.Abs(this.lastUpdatealt - drawArgs.WorldCamera.Altitude); if (distance > 10 || altchange < 10000.0 || m_needsupdate) { this.lastUpdatelon = drawArgs.WorldCamera.Longitude; this.lastUpdatelat = drawArgs.WorldCamera.Latitude; this.lastUpdatealt = drawArgs.WorldCamera.Altitude; this.m_needsupdate = false; double viewNorth = drawArgs.WorldCamera.Latitude.Degrees + drawArgs.WorldCamera.TrueViewRange.Degrees * 0.5; double viewSouth = drawArgs.WorldCamera.Latitude.Degrees - drawArgs.WorldCamera.TrueViewRange.Degrees * 0.5; double viewWest = drawArgs.WorldCamera.Longitude.Degrees - drawArgs.WorldCamera.TrueViewRange.Degrees * 0.5; double viewEast = drawArgs.WorldCamera.Longitude.Degrees + drawArgs.WorldCamera.TrueViewRange.Degrees * 0.5; //Need lock on the folder lock (this) { //TODO: Implement temporary caching and redownload on request PhotoCollection allPhotos = GetPhotoCollection(viewWest, viewSouth, viewEast, viewNorth); this.RemoveAll(); foreach (Photo photo in allPhotos) { double photolat = Convert.ToDouble(photo.Latitude); double photolon = Convert.ToDouble(photo.Longitude); WorldWind.Renderable.Icon ic = new WorldWind.Renderable.Icon(photo.Title, photolat , photolon); ic.Image = Image; ic.Width = 16; ic.Height = 16; //ic.MinimumDisplayDistance = 100000; //WorldWind.Renderable.ScreenOverlay overlay //= new WorldWind.Renderable.ScreenOverlay(ic.Name,0.0f,0.0f,photo.ThumbnailUrl); //ic.AddOverlay(overlay); ic.isSelectable = true; ic.Description = "<img src=\"" + photo.ThumbnailUrl + "\"/><br>" + photo.License + "<br>" + photo.DateTaken; double distanceToIcon = Vector3.Length(ic.Position - drawArgs.WorldCamera.Position); //If Camera is far render as icon //if(ic.MinimumDisplayDistance < distanceToIcon) this.Add(ic); //if Camera is near render as textured polygon /* * else * { * Point3d[] lineends = new Point3d[2]; * lineends[0].X = photolon - 0.1; * lineends[0].Y = photolat - 0.1; * lineends[0].Z = 1000; * lineends[1].X = photolon + 0.1; * lineends[1].Y = photolat + 0.1; * lineends[1].Z = 1000; * * WorldWind.LineFeature line = new LineFeature(photo.Title, * m_world,lineends,photo.ThumbnailUrl); * line.AltitudeMode = AltitudeMode.RelativeToGround; * line.DistanceAboveSurface = 0; * line.Extrude = true; * * this.Add(line); * } */ //Console.WriteLine("Photos title is " + photo.Title + photo.Latitude + photo.Longitude); } } } }
/// <summary> /// RenderableObject abstract member (needed) /// OBS: Worker thread (don't update UI directly from this thread) /// </summary> public override void Initialize(DrawArgs drawArgs) { try { savedSkyColor = World.Settings.SkyColor; World.Settings.SkyColor = Color.Black; ReadPresets(); isInitialized = true; } catch { isOn = false; MessageBox.Show("Error initializing", "Layer initialization failed.", MessageBoxButtons.OK, MessageBoxIcon.Error ); } }
public override void Render(DrawArgs drawArgs) { if (!isInitialized || drawArgs.WorldCamera.Altitude < m_minimumDisplayAltitude || drawArgs.WorldCamera.Altitude > m_maximumDisplayAltitude) { return; } try { if (m_lineString != null) { return; } Cull currentCull = drawArgs.device.RenderState.CullMode; drawArgs.device.RenderState.CullMode = Cull.None; Vector3 rc = new Vector3( (float)drawArgs.WorldCamera.ReferenceCenter.X, (float)drawArgs.WorldCamera.ReferenceCenter.Y, (float)drawArgs.WorldCamera.ReferenceCenter.Z ); drawArgs.device.Transform.World = Matrix.Translation( (float)-drawArgs.WorldCamera.ReferenceCenter.X, (float)-drawArgs.WorldCamera.ReferenceCenter.Y, (float)-drawArgs.WorldCamera.ReferenceCenter.Z ); if (m_wallVertices != null) { drawArgs.device.RenderState.ZBufferEnable = true; if (m_texture != null && !m_texture.Disposed) { drawArgs.device.SetTexture(0, m_texture); drawArgs.device.TextureState[0].AlphaOperation = TextureOperation.Modulate; drawArgs.device.TextureState[0].ColorOperation = TextureOperation.Add; drawArgs.device.TextureState[0].AlphaArgument1 = TextureArgument.TextureColor; } else { drawArgs.device.TextureState[0].ColorOperation = TextureOperation.Disable; } drawArgs.device.VertexFormat = CustomVertex.PositionColoredTextured.Format; drawArgs.device.DrawUserPrimitives(PrimitiveType.TriangleStrip, m_wallVertices.Length - 2, m_wallVertices); if (m_outline) { drawArgs.device.TextureState[0].ColorOperation = TextureOperation.Disable; drawArgs.device.VertexFormat = CustomVertex.PositionColored.Format; drawArgs.device.DrawUserPrimitives(PrimitiveType.LineStrip, m_topVertices.Length - 1, m_topVertices); if (m_bottomVertices != null) { drawArgs.device.DrawUserPrimitives(PrimitiveType.LineStrip, m_bottomVertices.Length - 1, m_bottomVertices); } if (m_sideVertices != null) { drawArgs.device.DrawUserPrimitives(PrimitiveType.LineList, m_sideVertices.Length / 2, m_sideVertices); } } } else { drawArgs.device.TextureState[0].ColorOperation = TextureOperation.Disable; drawArgs.device.VertexFormat = CustomVertex.PositionColored.Format; drawArgs.device.DrawUserPrimitives(PrimitiveType.LineStrip, m_topVertices.Length - 1, m_topVertices); } drawArgs.device.Transform.World = drawArgs.WorldCamera.WorldMatrix; drawArgs.device.RenderState.CullMode = currentCull; } catch //(Exception ex) { //Utility.Log.Write(ex); } }
/// <summary> /// Gets called when user left clicks. /// RenderableObject abstract member (needed) /// Called from UI thread = UI code safe in this function /// </summary> public override bool PerformSelectionAction(DrawArgs drawArgs) { return false; }
/// <summary> /// Called after icon render. Always updates the hook form so the hook form still updates position even when the icon /// is out of view. /// </summary> /// <param name="drawArgs"></param> /// <param name="isMouseOver">Whether or not the mouse is over the icon</param> public override void PostRender(DrawArgs drawArgs, bool isMouseOver) { base.PostRender(drawArgs, isMouseOver); this.UpdateHookForm(); }