Ejemplo n.º 1
0
 protected override string GetDownloadUrl(QuadTile qt)
 {
     return(string.Format(CultureInfo.InvariantCulture,
                          m_formatString, m_serverUri,
                          m_dataSetName, qt.Level, qt.Col, qt.Row,
                          qt.West, qt.South, qt.East, qt.North));
 }
Ejemplo n.º 2
0
        void QueueDownload(QuadTile qt, string filePath)
        {
            string url = this.GetDownloadUrl(qt);

            qt.QuadTileSet.AddToDownloadQueue(qt.QuadTileSet.Camera,
                                              new GeoSpatialDownloadRequest(qt, this, filePath, url));
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref= "T:Qrst.Renderable.GeoSpatialDownloadRequest"/> class.
 /// </summary>
 /// <param name="quadTile"></param>
 public GeoSpatialDownloadRequest(QuadTile quadTile, ImageStore imageStore, string localFilePath, string downloadUrl)
 {
     m_quadTile      = quadTile;
     m_url           = downloadUrl;
     m_localFilePath = localFilePath;
     m_imageStore    = imageStore;
 }
Ejemplo n.º 4
0
		/// <summary>
		/// Initializes a new instance of the <see cref= "T:WorldWind.SetSamplerState(0, SamplerStateNet.SetSamplerState(0, SamplerStateImageTileRequest"/> class.SetSamplerState(0, SamplerState
		/// </summary>
		/// <param name="owner"></param>
		/// <param name="quadTile"></param>
		public ImageTileRequest(object owner, QuadTile quadTile) : 
			base( owner, quadTile.SetSamplerState(0, SamplerStateImageTileInfo.SetSamplerState(0, SamplerStateUri )
		{
			m_quadTile = quadTile;
			download.SetSamplerState(0, SamplerStateDownloadType = DownloadType.SetSamplerState(0, SamplerStateWms;
			SaveFilePath = QuadTile.SetSamplerState(0, SamplerStateImageTileInfo.SetSamplerState(0, SamplerStateImagePath;
		}
Ejemplo n.º 5
0
        /// <summary>
        /// Finds the "best" tile from queue
        /// </summary>
        public virtual GeoSpatialDownloadRequest GetClosestDownloadRequest()
        {
            GeoSpatialDownloadRequest closestRequest = null;
            float largestArea = float.MinValue;

            lock (m_downloadRequests.SyncRoot)
            {
                foreach (GeoSpatialDownloadRequest curRequest in m_downloadRequests.Values)
                {
                    if (curRequest.IsDownloading)
                    {
                        continue;
                    }

                    QuadTile qt = curRequest.QuadTile;
                    if (!m_camera.ViewFrustum.Intersects(qt.BoundingBox))
                    {
                        continue;
                    }

                    float screenArea = qt.BoundingBox.CalcRelativeScreenArea(m_camera);
                    if (screenArea > largestArea)
                    {
                        largestArea    = screenArea;
                        closestRequest = curRequest;
                    }
                }
            }

            return(closestRequest);
        }
Ejemplo n.º 6
0
    private void DrawPath(QuadTile target)
    {
        if (target == oldTarget)
        {
            return;
        }
        oldTarget = target;

        List <QuadTile> path = target.Path();

        Clear(PathfindingClear.Path);

        Arrow.gameObject.SetActive(true);
        Arrow.transform.position = path[path.Count - 1].PositionWithHeight;
        Arrow.transform.SetParent(path[path.Count - 1].transform);
        Arrow.UpdateSegment(path[path.Count - 1].pathFindingData.cameFrom.PositionWithHeight, Vector3.zero);

        for (int i = 0; i < path.Count - 1; i++)
        {
            LineSegment segment = GetLineSegmentFromPool();

            segment.transform.position = path[i].PositionWithHeight;
            segment.transform.SetParent(path[i].transform);
            segment.name = "Segment " + i;
            segment.UpdateSegment(path[i].pathFindingData.cameFrom.PositionWithHeight, path[i + 1].PositionWithHeight);
        }
    }
Ejemplo n.º 7
0
		/// <summary>
		/// Tile download completed callback
		/// </summary>
		protected override void DownloadComplete()
		{
			try
			{
				download.SetSamplerState(0, SamplerStateVerify();

				if(download.SetSamplerState(0, SamplerStateSavedFilePath != null && File.SetSamplerState(0, SamplerStateExists(download.SetSamplerState(0, SamplerStateSavedFilePath))
					// Rename from .SetSamplerState(0, SamplerStatexxx.SetSamplerState(0, SamplerStatetmp -> .SetSamplerState(0, SamplerStatexxx
					File.SetSamplerState(0, SamplerStateMove(download.SetSamplerState(0, SamplerStateSavedFilePath, SaveFilePath);

				// Make the quad tile reload the new image
				m_quadTile.SetSamplerState(0, SamplerStateisInitialized = false;
				QuadTile.SetSamplerState(0, SamplerStateDownloadRequest = null;
			}
			catch(WebException caught)
			{
				System.SetSamplerState(0, SamplerStateNet.SetSamplerState(0, SamplerStateHttpWebResponse response = caught.SetSamplerState(0, SamplerStateResponse as System.SetSamplerState(0, SamplerStateNet.SetSamplerState(0, SamplerStateHttpWebResponse;
				if(response!=null && response.SetSamplerState(0, SamplerStateStatusCode==System.SetSamplerState(0, SamplerStateNet.SetSamplerState(0, SamplerStateHttpStatusCode.SetSamplerState(0, SamplerStateNotFound)
					FlagBadFile();
			}
			catch(IOException)
			{
				FlagBadFile();
			}	
		}
Ejemplo n.º 8
0
        public void Render(DrawArgs drawArgs)
        {
            const int screenMargin = 10;

            m_renderPosition = new Vector2(drawArgs.screenWidth - HalfWidth - screenMargin, drawArgs.screenHeight - screenMargin);
            ImageAccessor logoAccessor = null;

            // 显示下载进度条
            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);
            }
        }
Ejemplo n.º 9
0
        protected void RemoveInvisibleTiles(CameraBase camera)
        {
            ArrayList deletionList = new ArrayList();

            lock (m_topmostTiles.SyncRoot)
            {
                foreach (long key in m_topmostTiles.Keys)
                {
                    QuadTile qt = (QuadTile)m_topmostTiles[key];
                    if (!camera.ViewFrustum.Intersects(qt.BoundingBox))
                    {
                        deletionList.Add(key);
                    }
                }

                foreach (long deleteThis in deletionList)
                {
                    QuadTile qt = (QuadTile)m_topmostTiles[deleteThis];
                    if (qt != null)
                    {
                        m_topmostTiles.Remove(deleteThis);
                        qt.Dispose();
                    }
                }
            }
        }
Ejemplo n.º 10
0
        public virtual void ResetCacheForCurrentView(Qrst.Camera.CameraBase camera)
        {
            //                      if (!ImageStore.IsDownloadableLayer)
            //                              return;

            ArrayList deletionList = new ArrayList();

            //reset "root" tiles that intersect current view
            lock (m_topmostTiles.SyncRoot)
            {
                foreach (long key in m_topmostTiles.Keys)
                {
                    QuadTile qt = (QuadTile)m_topmostTiles[key];
                    if (camera.ViewFrustum.Intersects(qt.BoundingBox))
                    {
                        qt.ResetCache();
                        deletionList.Add(key);
                    }
                }

                foreach (long deletionKey in deletionList)
                {
                    m_topmostTiles.Remove(deletionKey);
                }
            }
        }
Ejemplo n.º 11
0
 public ImageTileRequest(object owner, QuadTile quadTile) :
     base(owner, quadTile.ImageTileInfo.Uri)
 {
     m_quadTile            = quadTile;
     download.DownloadType = DownloadType.Wms;
     SaveFilePath          = QuadTile.ImageTileInfo.ImagePath;
 }
Ejemplo n.º 12
0
        protected override string GetDownloadUrl(QuadTile qt)
        {
            if (this.m_serverGetMapUrl.IndexOf('?') >= 0)
            {
                // Allow custom format string url
                // http://server.net/path?imageformat=png&width={WIDTH}&north={NORTH}...
                string url = this.m_serverGetMapUrl;
                url = url.Replace("{WIDTH}", this.m_textureSizePixels.ToString(CultureInfo.InvariantCulture));
                url = url.Replace("{HEIGHT}", this.m_textureSizePixels.ToString(CultureInfo.InvariantCulture));
                url = url.Replace("{WEST}", qt.West.ToString(CultureInfo.InvariantCulture));
                url = url.Replace("{EAST}", qt.East.ToString(CultureInfo.InvariantCulture));
                url = url.Replace("{NORTH}", qt.North.ToString(CultureInfo.InvariantCulture));
                url = url.Replace("{SOUTH}", qt.South.ToString(CultureInfo.InvariantCulture));

                return(url);
            }
            else
            {
                string url = string.Format(CultureInfo.InvariantCulture,
                                           "{0}?request=GetMap&layers={1}&srs=EPSG:4326&width={2}&height={3}&bbox={4},{5},{6},{7}&format={8}&version={9}&styles={10}", this.m_serverGetMapUrl, this.m_wmsLayerName, this.m_textureSizePixels, this.m_textureSizePixels,
                                           qt.West, qt.South, qt.East, qt.North, this.m_imageFormat, this.m_version, this.m_wmsLayerStyle);

                return(url);
            }
        }
Ejemplo n.º 13
0
        public virtual string GetLocalPath(QuadTile qt)
        {
            if (qt.Level >= m_levelCount)
            {
                throw new ArgumentException(string.Format("Level {0} not available.",
                                                          qt.Level));
            }

            string relativePath = String.Format(@"{0}\{1:D4}\{1:D4}_{2:D4}.{3}",
                                                qt.Level, qt.Row, qt.Col, m_imageFileExtension);

            if (m_dataDirectory != null)
            {
                // Search data directory first
                string rawFullPath = Path.Combine(m_dataDirectory, relativePath);
                if (File.Exists(rawFullPath))
                {
                    return(rawFullPath);
                }
            }

            // If cache doesn't exist, fall back to duplicate texture path.
            if (m_cacheDirectory == null)
            {
                return(m_duplicateTexturePath);
            }

            // Try cache with default file extension
            string cacheFullPath = Path.Combine(m_cacheDirectory, relativePath);

            if (File.Exists(cacheFullPath))
            {
                return(cacheFullPath);
            }

            // Try cache but accept any valid image file extension
            const string ValidExtensions = ".bmp.dds.dib.hdr.jpg.jpeg.pfm.png.ppm.tga.gif.tif";

            string cacheSearchPath = Path.GetDirectoryName(cacheFullPath);

            if (Directory.Exists(cacheSearchPath))
            {
                foreach (string imageFile in Directory.GetFiles(
                             cacheSearchPath,
                             Path.GetFileNameWithoutExtension(cacheFullPath) + ".*"))
                {
                    string extension = Path.GetExtension(imageFile).ToLower();
                    if (ValidExtensions.IndexOf(extension) < 0)
                    {
                        continue;
                    }

                    return(imageFile);
                }
            }

            return(cacheFullPath);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Deletes the cached copy of the tile.
        /// </summary>
        /// <param name="qt"></param>
        public virtual void DeleteLocalCopy(QuadTile qt)
        {
            string filename = this.GetLocalPath(qt);

            if (File.Exists(filename))
            {
                File.Delete(filename);
            }
        }
Ejemplo n.º 15
0
        protected override string GetDownloadUrl(QuadTile qt)
        {
            return(string.Format(CultureInfo.InvariantCulture,
                                 "{0}?T={1}&L={2}&X={3}&Y={4}", m_serverUri,
                                 m_dataSetName, qt.Level, qt.Col, qt.Row));

            //return string.Format(CultureInfo.InvariantCulture,
            //  "{0}?layer={1}&level={2}&row={3}&col={4}", m_serverUri,
            //  m_dataSetName, qt.Level, qt.Col, qt.Row);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Figure out how to download the image.
        /// TODO: Allow subclasses to have control over how images are downloaded,
        /// not just the download url.
        /// </summary>
        protected virtual string GetDownloadUrl(QuadTile qt)
        {
            // No local image, return our "duplicate" tile if any
            if (this.m_duplicateTexturePath != null && File.Exists(this.m_duplicateTexturePath))
            {
                return(this.m_duplicateTexturePath);
            }

            // No image available anywhere, give up
            return("");
        }
Ejemplo n.º 17
0
        void QueueDownload(QuadTile qt, string SavedFilePath)
        {
            string url = GetDownloadUrl(qt);
            // Download to file
            string targetDirectory = Path.GetDirectoryName(SavedFilePath);

            if (targetDirectory.Length > 0)
            {
                Directory.CreateDirectory(targetDirectory);
            }
            FileStream ContentStream = new FileStream(SavedFilePath, FileMode.Create);

            // Create the request object.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.UserAgent = "";

            request.Proxy = ProxyHelper.DetermineProxyForUrl(
                url,
                true,
                true,
                "",
                "",
                "");
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    string strContentLength = response.Headers["Content-Length"];
                    int    ContentLength;
                    if (strContentLength != null)
                    {
                        ContentLength = int.Parse(strContentLength, CultureInfo.InvariantCulture);
                    }

                    byte[] readBuffer = new byte[1500];
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        while (true)
                        {
                            int bytesRead = responseStream.Read(readBuffer, 0, readBuffer.Length);
                            if (bytesRead <= 0)
                            {
                                break;
                            }
                            ContentStream.Write(readBuffer, 0, bytesRead);
                        }
                    }
                }
            }
            ContentStream.Close();
            ContentStream = null;
        }
Ejemplo n.º 18
0
        public IEnumerator Move()
        {
            ShowMove();

            ToggleWindow(false, false);

            QuadTile target = null;

            // Wait for click
            while (!target)
            {
                if (Input.GetButtonDown("Fire1"))
                {
                    target = QuadTileMap.GetTarget(LayerMask.GetMask("Viable Marker"));
                }
                yield return(null);
            }

            mover.StopUpdatingPath = true;

            ConfirmationDialog dialog = Instantiate(dialogPrefab, transform.parent);

            // Wait for dialog input
            while (dialog.Result == DialogResult.None)
            {
                yield return(null);
            }

            if (dialog.Result == DialogResult.Yes)
            {
                Destroy(dialog.gameObject);
                CharacterData data       = turnManager.CurrentCharacter.Data;
                MoveParams    moveParams = moved ? data.rushParams : data.moveParams;
                yield return(StartCoroutine(mover.Move(turnManager.CurrentCharacter, target.Path(), moveParams,
                                                       data.jumpParams)));

                turnManager.CurrentCharacter.LoseActionPoints(moveCost);
                moveCost++;

                if (moved)
                {
                    MoveButton.interactable = false;
                }
                moved = true;
            }
            else
            {
                Destroy(dialog.gameObject);
            }

            mover.Clear(PathfindingClear.Both);
            ToggleWindow(true, false);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Removes a request from the download queue.
 /// </summary>
 public virtual void RemoveFromDownloadQueue(GeoSpatialDownloadRequest removeRequest)
 {
     lock (m_downloadRequests.SyncRoot)
     {
         QuadTile key = removeRequest.QuadTile;
         GeoSpatialDownloadRequest request = (GeoSpatialDownloadRequest)m_downloadRequests[key];
         if (request != null)
         {
             m_downloadRequests.Remove(key);
             request.QuadTile.DownloadRequest = null;
         }
     }
 }
Ejemplo n.º 20
0
        private IEnumerator PickTarget()
        {
            ToggleHideUI();
            while (!Input.GetButtonDown("Fire1"))
            {
                yield return(null);
            }
            QuadTile target = QuadTileMap.GetTarget(LayerMask.GetMask("Default"));

            UpdateTarget(target.PositionVector2Int);
            targetXInput.text = lastSelected.dialogEvent.target.x.ToString();
            targetYInput.text = lastSelected.dialogEvent.target.y.ToString();
            ToggleHideUI();
        }
Ejemplo n.º 21
0
    private void Update()
    {
        if (StopUpdatingPath)
        {
            return;
        }

        QuadTile target = QuadTileMap.GetTarget(LayerMask.GetMask("Viable Marker"));

        if (target)
        {
            DrawPath(target);
        }
    }
Ejemplo n.º 22
0
        protected override string GetDownloadUrl(QuadTile qt)
        {
            if (m_serverGetMapUrl.IndexOf('?') >= 0)
            {
                // Allow custom format string url
                // http://server.net/path?imageformat=png&width={WIDTH}&north={NORTH}...
                string url = m_serverGetMapUrl;
                url = url.Replace("{WIDTH}", m_textureSizePixels.ToString(CultureInfo.InvariantCulture));
                url = url.Replace("{HEIGHT}", m_textureSizePixels.ToString(CultureInfo.InvariantCulture));
                url = url.Replace("{WEST}", qt.West.ToString(CultureInfo.InvariantCulture));
                url = url.Replace("{EAST}", qt.East.ToString(CultureInfo.InvariantCulture));
                url = url.Replace("{NORTH}", qt.North.ToString(CultureInfo.InvariantCulture));
                url = url.Replace("{SOUTH}", qt.South.ToString(CultureInfo.InvariantCulture));

                return(url);
            }
            else
            {
                string url = "";
                //徐辉改 休整了 如何调用 WMS 1.3.0 版本的问题
                if (m_version == "1.3.0")
                {
                    url = string.Format(CultureInfo.InvariantCulture,
                                        "{0}?REQUEST=GetMap&Layers={1}&STYLES={10}&CRS=EPSG:4326&BBOX={4},{5},{6},{7}&WIDTH={2}&HEIGHT={3}&FORMAT={8}&VERSION={9}",
                                        m_serverGetMapUrl,
                                        m_wmsLayerName,
                                        m_textureSizePixels,
                                        m_textureSizePixels,
                                        qt.West, qt.South, qt.East, qt.North,
                                        m_imageFormat,
                                        m_version,
                                        m_wmsLayerStyle);
                }
                else if (m_version == "1.1.1")
                {
                    url = string.Format(CultureInfo.InvariantCulture,
                                        "{0}?request=GetMap&layers={1}&srs=EPSG:4326&width={2}&height={3}&bbox={4},{5},{6},{7}&format={8}&version={9}&styles={10}",
                                        m_serverGetMapUrl,
                                        m_wmsLayerName,
                                        m_textureSizePixels,
                                        m_textureSizePixels,
                                        qt.West, qt.South, qt.East, qt.North,
                                        m_imageFormat,
                                        m_version,
                                        m_wmsLayerStyle);
                }
                return(url);
            }
        }
Ejemplo n.º 23
0
        public IEnumerator Attack()
        {
            attacker.ShowPossible(turnManager.CurrentCharacter);

            ToggleWindow(false, false);

            QuadTile target = null;

            while (!target)
            {
                if (Input.GetButtonDown("Fire1"))
                {
                    target = QuadTileMap.GetTarget(LayerMask.GetMask("Viable Marker"));
                }
                yield return(null);
            }

            ConfirmationDialog dialog = Instantiate(dialogPrefab, transform.parent);

            // Wait for dialog input
            while (dialog.Result == DialogResult.None)
            {
                yield return(null);
            }

            if (dialog.Result == DialogResult.Yes)
            {
                Destroy(dialog.gameObject);

                CharacterData data = turnManager.CurrentCharacter.Data;
                attacker.Attack(target);
                turnManager.CurrentCharacter.LoseActionPoints(attackCost);
                attackCost++;

                if (moved)
                {
                    MoveButton.interactable = false;
                }
                moved = true;
            }
            else
            {
                Destroy(dialog.gameObject);
            }

            attacker.Clear();
            ToggleWindow(true, false);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 获取本地存储的路径
        /// </summary>
        /// <param name="qt">图层中的一块图片</param>
        /// <returns>图片应该保存的本地路径</returns>
        public virtual string GetLocalPath(QuadTile qt)
        {
            if (qt.Level >= _levelCount)
            {
                throw new ArgumentException(string.Format("Level {0} not available.", qt.Level));
            }

            string relativePath = String.Format(@"{0}\{1:D4}\{1:D4}_{2:D4}.{3}", qt.Level, qt.Row, qt.Col, _imageFileExtension);

            if (_dataDirectory != null)
            {
                // Search data directory first
                string rawFullPath = Path.Combine(_dataDirectory, relativePath);
                if (File.Exists(rawFullPath))
                {
                    return(rawFullPath);
                }
            }

            // Try cache with default file extension
            string cacheFullPath = Path.Combine(_cacheDirectory, relativePath);

            if (File.Exists(cacheFullPath))
            {
                return(cacheFullPath);
            }

            // Try cache but accept any valid image file extension
            string cacheSearchPath = Path.GetDirectoryName(cacheFullPath);

            if (Directory.Exists(cacheSearchPath))
            {
                foreach (string imageFile in Directory.GetFiles(cacheSearchPath, Path.GetFileNameWithoutExtension(cacheFullPath) + ".*"))
                {
                    string extension = Path.GetExtension(imageFile).ToLower();
                    if (ValidExtensions.IndexOf(extension) < 0)
                    {
                        continue;
                    }

                    return(imageFile);
                }
            }

            return(cacheFullPath);
        }
Ejemplo n.º 25
0
        protected override void OnEnable()
        {
            SceneView.duringSceneGui -= OnSceneGui;
            SceneView.duringSceneGui += OnSceneGui;

            ignoreLayer  = LayerMask.NameToLayer("Ignore Editor");
            defaultLayer = LayerMask.NameToLayer("Default");

            tilePrefab      = AssetDatabase.LoadAssetAtPath <QuadTile>("Assets/Prefabs/QuadTile.prefab");
            selectionPrefab = AssetDatabase.LoadAssetAtPath <QuadTile>("Assets/Prefabs/Editor/SelectionTile.prefab");
            brush           = AssetDatabase.LoadAssetAtPath <QuadTileData>("Assets/tiles/Mat/GrassLight.asset");

            _selectionTile = Instantiate(selectionPrefab);

            _selectionTile.name = "SelectionMarker";

            base.OnEnable();
        }
Ejemplo n.º 26
0
        public virtual void AddToDownloadQueue(CameraBase camera, GeoSpatialDownloadRequest newRequest)
        {
            QuadTile key = newRequest.QuadTile;

            key.WaitingForDownload = true;
            lock (m_downloadRequests.SyncRoot)
            {
                if (m_downloadRequests.Contains(key))
                {
                    return;
                }

                m_downloadRequests.Add(key, newRequest);

                if (m_downloadRequests.Count >= m_maxQueueSize)
                {
                    //remove spatially farthest request
                    GeoSpatialDownloadRequest farthestRequest = null;
                    Angle curDistance      = Angle.Zero;
                    Angle farthestDistance = Angle.Zero;
                    foreach (GeoSpatialDownloadRequest curRequest in m_downloadRequests.Values)
                    {
                        curDistance = MathEngine.SphericalDistance(
                            curRequest.QuadTile.CenterLatitude,
                            curRequest.QuadTile.CenterLongitude,
                            camera.Latitude,
                            camera.Longitude);

                        if (curDistance > farthestDistance)
                        {
                            farthestRequest  = curRequest;
                            farthestDistance = curDistance;
                        }
                    }

                    farthestRequest.Dispose();
                    farthestRequest.QuadTile.DownloadRequest = null;
                    m_downloadRequests.Remove(farthestRequest.QuadTile);
                }
            }

            ServiceDownloadQueue();
        }
Ejemplo n.º 27
0
        public override Texture LoadFile(QuadTile qt)
        {
            //获取切片的本地路径
            string filePath = GetLocalPath(qt);

            qt.ImageFilePath = filePath;
            Texture texture = null;
            string  ddsPath = filePath;

            ////判断是否是DDS文件
            if (World.Settings.ConvertDownloadedImagesToDds)
            {
                ddsPath = Path.GetDirectoryName(filePath) + "\\" + Path.GetFileNameWithoutExtension(filePath) + ".dds";
            }

            filePath = ddsPath;
            //判断磁盘上,是否有当前文件,若有,则直接读取,若没有,则重新加载
            if (!File.Exists(filePath))
            {
                QueueDownload(qt, filePath);
                //return null;
            }

            //设置是否显示图片的无效值
            if (qt.QuadTileSet.HasTransparentRange)
            {
                texture = ImageHelper.LoadTexture(filePath, qt.QuadTileSet.ColorKey,
                                                  qt.QuadTileSet.ColorKeyMax);
            }
            else
            {
                texture = ImageHelper.LoadTexture(filePath, qt.QuadTileSet.ColorKey);
            }

            ////判断,是否转化为dds文件
            if (World.Settings.ConvertDownloadedImagesToDds)
            {
                ConvertImage(texture, filePath);
            }
            //返回当前纹理
            return(texture);
        }
Ejemplo n.º 28
0
        public Texture LoadFile(QuadTile qt)
        {
            string filePath = this.GetLocalPath(qt);

            qt.ImageFilePath = filePath;

            // remove broken files
            if (File.Exists(filePath))
            {
                FileInfo fi = new FileInfo(filePath);
                if (fi.Length == 0)
                {
                    File.Delete(filePath);
                }
            }

            if (!File.Exists(filePath))
            {
                string badFlag = filePath + ".txt";
                if (File.Exists(badFlag))
                {
                    FileInfo fi = new FileInfo(badFlag);
                    if (DateTime.Now - fi.LastWriteTime < TimeSpan.FromDays(1))
                    {
                        return(null);
                    }
                    // Timeout period elapsed, retry
                    File.Delete(badFlag);
                }

                if (this.IsDownloadableLayer)
                {
                    this.QueueDownload(qt, filePath);
                    return(null);
                }

                if (this.DuplicateTexturePath == null)
                {
                    // No image available, neither local nor online.
                    return(null);
                }

                filePath = this.DuplicateTexturePath;
            }

            // Use color key
            Texture texture = null;

            if (qt.QuadTileSet.HasTransparentRange)
            {
                texture = ImageHelper.LoadTexture(filePath, qt.QuadTileSet.ColorKey,
                                                  qt.QuadTileSet.ColorKeyMax);
            }
            else
            {
                texture = ImageHelper.LoadTexture(filePath, qt.QuadTileSet.ColorKey, this.TextureFormat);
            }

            if (qt.QuadTileSet.CacheExpirationTime != TimeSpan.MaxValue)
            {
                FileInfo fi     = new FileInfo(filePath);
                DateTime expiry = fi.LastWriteTimeUtc.Add(qt.QuadTileSet.CacheExpirationTime);
                if (DateTime.UtcNow > expiry)
                {
                    this.QueueDownload(qt, filePath);
                }
            }

            // Only convert images that are downloadable (don't mess with things the user put here!)
            if (World.Settings.ConvertDownloadedImagesToDds && this.IsDownloadableLayer)
            {
                this.ConvertImage(texture, filePath);
            }

            return(texture);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Returns a path to be used for local storage of the tile
        /// Checks through various places before just assinging to cache, in this order.
        /// If it finds a tile in any of these places, it immediately returns the path.
        /// 1. The "Data" directory (if existent), under its folder structure
        /// 2. If the QTS doesn't have a cache directory, it just returns the m_duplicateTexturePath
        /// 3. If it has a cache directory, first with the default file extension, then checks for others
        /// 4. If not found in any of these, it simply constructs the path
        ///    from cache directory and default extension, and returns that path
        ///
        /// This method also checks for tiles in the old, pre-1.4.1 cache structure if it can't find it
        /// in the new WWJ format.  If it can't find it in the old structure, it returns a WWJ-style
        /// path to store a new tile in.
        /// </summary>
        public virtual string GetLocalPath(QuadTile qt)
        {
            if (qt.Level >= this.m_levelCount)
            {
                throw new ArgumentException(string.Format("Level {0} not available.",
                                                          qt.Level));
            }

            //List of cache structures to try, in order of preference
            string[] patternArray =
            {
                @"{0}\{1:D1}\{1:D1}_{2:D1}.{3}",
                @"{0}\{1:D4}\{1:D4}_{2:D4}.{3}"
            };

            foreach (string relativePattern in patternArray)
            {
                //Try each pattern through
                string relativePath = String.Format(relativePattern,
                                                    qt.Level, qt.Row, qt.Col, this.m_imageFileExtension);

                if (this.m_dataDirectory != null)
                {
                    // Search data directory first
                    string rawFullPath = Path.Combine(this.m_dataDirectory, relativePath);
                    if (File.Exists(rawFullPath))
                    {
                        return(rawFullPath);
                    }
                }

                // If cache doesn't exist, fall back to duplicate texture path.
                if (this.m_cacheDirectory == null)
                {
                    return(this.m_duplicateTexturePath);
                }

                // Try cache with default file extension
                string cacheFullPath = Path.Combine(this.m_cacheDirectory, relativePath);
                if (File.Exists(cacheFullPath))
                {
                    return(cacheFullPath);
                }

                // Try cache but accept any valid image file extension
                const string ValidExtensions = ".bmp.dds.dib.hdr.jpg.jpeg.pfm.png.ppm.tga.gif.tif";

                string cacheSearchPath = Path.GetDirectoryName(cacheFullPath);
                if (Directory.Exists(cacheSearchPath))
                {
                    foreach (string imageFile in Directory.GetFiles(
                                 cacheSearchPath,
                                 Path.GetFileNameWithoutExtension(cacheFullPath) + ".*"))
                    {
                        string extension = Path.GetExtension(imageFile).ToLower();
                        if (ValidExtensions.IndexOf(extension) < 0)
                        {
                            continue;
                        }

                        return(imageFile);
                    }
                }
            }

            //If it's not anywhere in cache, use the first (preferred) pattern, in the cache directory
            string defaultPath = String.Format(patternArray[0],
                                               qt.Level, qt.Row, qt.Col, this.m_imageFileExtension);
            string defaultFullPath = Path.Combine(this.m_cacheDirectory, defaultPath);

            return(defaultFullPath);
        }
Ejemplo n.º 30
0
        public override void Update(DrawArgs drawArgs)
        {
            if (!isInitialized)
            {
                Initialize(drawArgs);
            }

            if (m_effectPath != null && m_effect == null)
            {
                string errs = string.Empty;
                m_effect = Effect.FromFile(DrawArgs.Device, m_effectPath, null, "", ShaderFlags.None, m_effectPool, out errs);

                if (errs != null && errs != string.Empty)
                {
                    Log.Write(Log.Levels.Warning, "Could not load effect " + m_effectPath + ": " + errs);
                    Log.Write(Log.Levels.Warning, "Effect has been disabled.");
                    m_effectPath = null;
                    m_effect     = null;
                }
            }

            if (ImageStores[0].LevelZeroTileSizeDegrees < 180)
            {
                // Check for layer outside view
                double vrd          = DrawArgs.Camera.ViewRange.Degrees;
                double latitudeMax  = DrawArgs.Camera.Latitude.Degrees + vrd;
                double latitudeMin  = DrawArgs.Camera.Latitude.Degrees - vrd;
                double longitudeMax = DrawArgs.Camera.Longitude.Degrees + vrd;
                double longitudeMin = DrawArgs.Camera.Longitude.Degrees - vrd;
                if (latitudeMax < m_south || latitudeMin > m_north || longitudeMax < m_west || longitudeMin > m_east)
                {
                    return;
                }
            }

            if (DrawArgs.Camera.ViewRange * 0.5f >
                Angle.FromDegrees(TileDrawDistance * ImageStores[0].LevelZeroTileSizeDegrees))
            {
                lock (m_topmostTiles.SyncRoot)
                {
                    foreach (QuadTile qt in m_topmostTiles.Values)
                    {
                        qt.Dispose();
                    }
                    m_topmostTiles.Clear();
                    ClearDownloadRequests();
                }

                return;
            }

            RemoveInvisibleTiles(DrawArgs.Camera);

            try
            {
                int middleRow = MathEngine.GetRowFromLatitude(DrawArgs.Camera.Latitude, ImageStores[0].LevelZeroTileSizeDegrees);
                int middleCol = MathEngine.GetColFromLongitude(DrawArgs.Camera.Longitude, ImageStores[0].LevelZeroTileSizeDegrees);

                double middleSouth = -90.0f + middleRow * ImageStores[0].LevelZeroTileSizeDegrees;
                double middleNorth = -90.0f + middleRow * ImageStores[0].LevelZeroTileSizeDegrees + ImageStores[0].LevelZeroTileSizeDegrees;
                double middleWest  = -180.0f + middleCol * ImageStores[0].LevelZeroTileSizeDegrees;
                double middleEast  = -180.0f + middleCol * ImageStores[0].LevelZeroTileSizeDegrees + ImageStores[0].LevelZeroTileSizeDegrees;

                double middleCenterLat = 0.5f * (middleNorth + middleSouth);
                double middleCenterLon = 0.5f * (middleWest + middleEast);

                int tileSpread = 4;
                for (int i = 0; i < tileSpread; i++)
                {
                    for (double j = middleCenterLat - i * ImageStores[0].LevelZeroTileSizeDegrees; j < middleCenterLat + i * ImageStores[0].LevelZeroTileSizeDegrees; j += ImageStores[0].LevelZeroTileSizeDegrees)
                    {
                        for (double k = middleCenterLon - i * ImageStores[0].LevelZeroTileSizeDegrees; k < middleCenterLon + i * ImageStores[0].LevelZeroTileSizeDegrees; k += ImageStores[0].LevelZeroTileSizeDegrees)
                        {
                            int  curRow = MathEngine.GetRowFromLatitude(Angle.FromDegrees(j), ImageStores[0].LevelZeroTileSizeDegrees);
                            int  curCol = MathEngine.GetColFromLongitude(Angle.FromDegrees(k), ImageStores[0].LevelZeroTileSizeDegrees);
                            long key    = ((long)curRow << 32) + curCol;

                            QuadTile qt = (QuadTile)m_topmostTiles[key];
                            if (qt != null)
                            {
                                qt.Update(drawArgs);
                                continue;
                            }

                            // Check for tile outside layer boundaries
                            double west = -180.0f + curCol * ImageStores[0].LevelZeroTileSizeDegrees;
                            if (west > m_east)
                            {
                                continue;
                            }

                            double east = west + ImageStores[0].LevelZeroTileSizeDegrees;
                            if (east < m_west)
                            {
                                continue;
                            }

                            double south = -90.0f + curRow * ImageStores[0].LevelZeroTileSizeDegrees;
                            if (south > m_north)
                            {
                                continue;
                            }

                            double north = south + ImageStores[0].LevelZeroTileSizeDegrees;
                            if (north < m_south)
                            {
                                continue;
                            }

                            qt = new QuadTile(south, north, west, east, 0, this);
                            if (DrawArgs.Camera.ViewFrustum.Intersects(qt.BoundingBox))
                            {
                                lock (m_topmostTiles.SyncRoot)
                                    m_topmostTiles.Add(key, qt);
                                qt.Update(drawArgs);
                            }
                        }
                    }
                }
            }
            catch (System.Threading.ThreadAbortException)
            {
            }
            catch (Exception caught)
            {
                Log.Write(caught);
            }
        }