From abd170e0c055a5fc60368a7bca8f4e65d3cb7c46 Mon Sep 17 00:00:00 2001 From: bergwerkgis Date: Tue, 9 May 2017 12:50:19 +0200 Subject: [PATCH 01/11] update to latest mapbox-sdk-cs@IAsyncFactory --- dependencies/mapbox-sdk-cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies/mapbox-sdk-cs b/dependencies/mapbox-sdk-cs index 4c004a746..4824dab71 160000 --- a/dependencies/mapbox-sdk-cs +++ b/dependencies/mapbox-sdk-cs @@ -1 +1 @@ -Subproject commit 4c004a746e4c82770d99f59325209995d37339f4 +Subproject commit 4824dab71812725cf34859f77757f5786cb3b6b4 From d3c9026da8990df71743fe2f89e22df205ca3b56 Mon Sep 17 00:00:00 2001 From: bergwerkgis Date: Tue, 9 May 2017 12:55:17 +0200 Subject: [PATCH 02/11] update to latest mapbox-sdk-cs@IAsyncFactory --- dependencies/mapbox-sdk-cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies/mapbox-sdk-cs b/dependencies/mapbox-sdk-cs index 4824dab71..e7cc5a591 160000 --- a/dependencies/mapbox-sdk-cs +++ b/dependencies/mapbox-sdk-cs @@ -1 +1 @@ -Subproject commit 4824dab71812725cf34859f77757f5786cb3b6b4 +Subproject commit e7cc5a59109b76e2bb4d2753335bf13117e4375c From 9641a64903be3cbc617a15609efdf12a6be380d8 Mon Sep 17 00:00:00 2001 From: bergwerkgis Date: Tue, 9 May 2017 13:02:14 +0200 Subject: [PATCH 03/11] add dispatcher --- .../Core/Unity/Utilities/DispatcherEditor.cs | 51 ++++++++ .../UnityToolbagDispatcher.meta | 9 ++ .../UnityToolbagDispatcher/Dispatcher.cs | 114 ++++++++++++++++++ .../UnityToolbagDispatcher/Dispatcher.cs.meta | 12 ++ 4 files changed, 186 insertions(+) create mode 100644 sdkproject/Assets/Mapbox/Core/Unity/Utilities/DispatcherEditor.cs create mode 100644 sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher.meta create mode 100644 sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs create mode 100644 sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs.meta diff --git a/sdkproject/Assets/Mapbox/Core/Unity/Utilities/DispatcherEditor.cs b/sdkproject/Assets/Mapbox/Core/Unity/Utilities/DispatcherEditor.cs new file mode 100644 index 000000000..55f57bc3e --- /dev/null +++ b/sdkproject/Assets/Mapbox/Core/Unity/Utilities/DispatcherEditor.cs @@ -0,0 +1,51 @@ +namespace Mapbox.Unity { + + + using System; + using System.Collections.Generic; + using System.Threading; + using UnityEditor; + + + [InitializeOnLoad] + public static class DispatcherEditor { + + + static DispatcherEditor() { + _mainThread = Thread.CurrentThread; + EditorApplication.update += Update; + } + + + private static object _lock = new object(); + private static readonly Queue _actions = new Queue(); + private static Thread _mainThread; + + + private static bool isMainThread { + get { return Thread.CurrentThread == _mainThread; } + } + + + public static void Update() { + lock (_lock) { + while (_actions.Count > 0) { + _actions.Dequeue()(); + } + } + } + + + public static void InvokeAsync(Action action) { + if (isMainThread) { + action(); + }else { + lock (_lock) { + _actions.Enqueue(action); + } + } + } + + + } +} \ No newline at end of file diff --git a/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher.meta b/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher.meta new file mode 100644 index 000000000..e898ff19b --- /dev/null +++ b/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 9b8e3a59ff0dc4000a4fda4d9fa6931d +folderAsset: yes +timeCreated: 1493311191 +licenseType: Pro +DefaultImporter: + userData: + assetBundleName: + assetBundleVariant: diff --git a/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs b/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs new file mode 100644 index 000000000..c76ef5f1c --- /dev/null +++ b/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs @@ -0,0 +1,114 @@ +using UnityEngine; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace UnityToolbag { + /// + /// A system for dispatching code to execute on the main thread. + /// + [AddComponentMenu("UnityToolbag/Dispatcher")] + public class Dispatcher : MonoBehaviour { + private static Dispatcher _instance; + + // We can't use the behaviour reference from other threads, so we use a separate bool + // to track the instance so we can use that on the other threads. + // edit by BergWerkGIS: make public to see if dispatcher is attached + public static bool _instanceExists; + + private static Thread _mainThread; + private static object _lockObject = new object(); + private static readonly Queue _actions = new Queue(); + + /// + /// Gets a value indicating whether or not the current thread is the game's main thread. + /// + public static bool isMainThread { + get { + return Thread.CurrentThread == _mainThread; + } + } + + /// + /// Queues an action to be invoked on the main game thread. + /// + /// The action to be queued. + public static void InvokeAsync(Action action) { + + if (!_instanceExists) { + Debug.LogError("No Dispatcher exists in the scene. Actions will not be invoked!"); + return; + } + + if (isMainThread) { + // Don't bother queuing work on the main thread; just execute it. + action(); + } else { + lock (_lockObject) { + _actions.Enqueue(action); + } + } + } + + /// + /// Queues an action to be invoked on the main game thread and blocks the + /// current thread until the action has been executed. + /// + /// The action to be queued. + public static void Invoke(Action action) { + + if (!_instanceExists) { + Debug.LogError("No Dispatcher exists in the scene. Actions will not be invoked!"); + return; + } + + + bool hasRun = false; + + InvokeAsync(() => { + action(); + hasRun = true; + }); + + // Lock until the action has run + while (!hasRun) { +#if !NETFX_CORE + Thread.Sleep(5); +#else + System.Threading.Tasks.Task.Delay(5).Wait(); +#endif + } + } + + void Awake() { + if (_instance) { + DestroyImmediate(this); + } else { + _instance = this; + _instanceExists = true; + _mainThread = Thread.CurrentThread; + } + } + + void OnDestroy() { + if (_instance == this) { + _instance = null; + _instanceExists = false; + } + } + + //int cnt = 0; + void Update() { + //cnt++; + //if (cnt < 100) { return; } + //cnt = 0; + ////if (_actions.Count > 0) UnityEngine.Debug.Log("-------------------- update -----------------" + DateTime.Now.Ticks); + lock (_lockObject) { + while (_actions.Count > 0) { + //UnityEngine.Debug.Log("QUEUE: " + _actions.Count + " " + DateTime.Now.Ticks); + _actions.Dequeue()(); + } + } + } + } +} diff --git a/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs.meta b/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs.meta new file mode 100644 index 000000000..99c6c3dc6 --- /dev/null +++ b/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: dd2511162df91294fa0c4ea0b0d740ed +timeCreated: 1493142390 +licenseType: Pro +MonoImporter: + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: From 526e104fcf978e9a60675ddf62904b3626babd33 Mon Sep 17 00:00:00 2001 From: bergwerkgis Date: Tue, 9 May 2017 13:50:43 +0200 Subject: [PATCH 04/11] * update to latest mapbox-sdk-cs@IAsyncRequestFactory * changes to account for latest mapbox-sdk-cs --- dependencies/mapbox-sdk-cs | 2 +- .../Assets/Mapbox/Core/Unity/MapboxAccess.cs | 300 +++---- .../Factories/MapImageFactory.cs | 184 ++--- .../MeshGeneration/Factories/MeshFactory.cs | 210 +++-- .../Factories/TerrainFactory.cs | 751 +++++++++--------- .../Core/Unity/Utilities/HTTPRequest.cs | 96 +-- .../Playground/Scripts/RasterTileExample.cs | 239 +++--- .../Playground/Scripts/VectorTileExample.cs | 145 ++-- .../Examples/Voxels/Scripts/VoxelTile.cs | 364 ++++----- 9 files changed, 1083 insertions(+), 1208 deletions(-) diff --git a/dependencies/mapbox-sdk-cs b/dependencies/mapbox-sdk-cs index e7cc5a591..5b440ead2 160000 --- a/dependencies/mapbox-sdk-cs +++ b/dependencies/mapbox-sdk-cs @@ -1 +1 @@ -Subproject commit e7cc5a59109b76e2bb4d2753335bf13117e4375c +Subproject commit 5b440ead209b4a66f51f41995666119be7e57c64 diff --git a/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs b/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs index 526762788..1cb5e94cd 100644 --- a/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs +++ b/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs @@ -1,181 +1,181 @@ namespace Mapbox.Unity { - using UnityEngine; - using System.IO; - using System; - using System.Net; - using Mapbox.Geocoding; - using Mapbox.Directions; - using Mapbox.Platform; - using Mapbox.Unity.Utilities; + using UnityEngine; + using System.IO; + using System; + using System.Net; + using Mapbox.Geocoding; + using Mapbox.Directions; + using Mapbox.Platform; + using Mapbox.Unity.Utilities; #if !NETFX_CORE - using System.Security.Cryptography.X509Certificates; + using System.Security.Cryptography.X509Certificates; #endif - using System.Net.Security; + using System.Net.Security; - /// - /// Object for retrieving an API token and making http requests. - /// Contains a lazy Geocoder and a lazy Directions for convenience. - /// - public class MapboxAccess : IFileSource { + /// + /// Object for retrieving an API token and making http requests. + /// Contains a lazy Geocoder and a lazy Directions for convenience. + /// + public class MapboxAccess : IFileSource { - private readonly string _accessPath = Path.Combine(Application.streamingAssetsPath, Constants.Path.TOKEN_FILE); + private readonly string _accessPath = Path.Combine(Application.streamingAssetsPath, Constants.Path.TOKEN_FILE); - static MapboxAccess _instance = new MapboxAccess(); + static MapboxAccess _instance = new MapboxAccess(); - /// - /// The singleton instance. - /// - public static MapboxAccess Instance { - get { - return _instance; - } - } + /// + /// The singleton instance. + /// + public static MapboxAccess Instance { + get { + return _instance; + } + } - MapboxAccess() { + MapboxAccess() { #if !NETFX_CORE - ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback; + ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback; #endif - ValidateMapboxAccessFile(); - LoadAccessToken(); - } - - - /// - /// The Mapbox API access token. - /// See Mapbox API Congfiguration in Unity. - /// - private string _accessToken; - public string AccessToken { - get { - return _accessToken; - } - set { - if (string.IsNullOrEmpty(value)) { - throw new InvalidTokenException("Please configure your access token in the menu!"); - } - _accessToken = value; - } - } - - - private void ValidateMapboxAccessFile() { + ValidateMapboxAccessFile(); + LoadAccessToken(); + } + + + /// + /// The Mapbox API access token. + /// See Mapbox API Congfiguration in Unity. + /// + private string _accessToken; + public string AccessToken { + get { + return _accessToken; + } + set { + if (string.IsNullOrEmpty(value)) { + throw new InvalidTokenException("Please configure your access token in the menu!"); + } + _accessToken = value; + } + } + + + private void ValidateMapboxAccessFile() { #if !UNITY_ANDROID - if (!Directory.Exists(Application.streamingAssetsPath) || !File.Exists(_accessPath)) { - throw new InvalidTokenException("Please configure your access token in the menu!"); - } + if (!Directory.Exists(Application.streamingAssetsPath) || !File.Exists(_accessPath)) { + throw new InvalidTokenException("Please configure your access token in the menu!"); + } #endif - } + } - /// - /// Loads the access token from StreamingAssets. - /// - private void LoadAccessToken() { + /// + /// Loads the access token from StreamingAssets. + /// + private void LoadAccessToken() { #if UNITY_EDITOR || !UNITY_ANDROID - AccessToken = File.ReadAllText(_accessPath); + AccessToken = File.ReadAllText(_accessPath); #else AccessToken = LoadMapboxAccess(); #endif - } + } - /// - /// Android-specific token file loading. - /// - private string LoadMapboxAccess() { + /// + /// Android-specific token file loading. + /// + private string LoadMapboxAccess() { - var request = new WWW(_accessPath); - // Implement a custom timeout - just in case - var timeout = Time.realtimeSinceStartup + 5f; - while (!request.isDone) { - if (Time.realtimeSinceStartup > timeout) { - throw new InvalidTokenException("Could not load access token!"); - } + var request = new WWW(_accessPath); + // Implement a custom timeout - just in case + var timeout = Time.realtimeSinceStartup + 5f; + while (!request.isDone) { + if (Time.realtimeSinceStartup > timeout) { + throw new InvalidTokenException("Could not load access token!"); + } #if NETFX_CORE System.Threading.Tasks.Task.Delay(10).Wait(); #else - System.Threading.Thread.Sleep(10); + System.Threading.Thread.Sleep(10); #endif - } - return request.text; - } - - - /// - /// Makes an asynchronous url query. - /// - /// The request. - /// URL. - /// Callback. - public IAsyncRequest Request(string url, Action callback) { - - var uriBuilder = new UriBuilder(url); - string accessTokenQuery = "access_token=" + AccessToken; - - if (uriBuilder.Query != null && uriBuilder.Query.Length > 1) { - uriBuilder.Query = uriBuilder.Query.Substring(1) + "&" + accessTokenQuery; - } else { - uriBuilder.Query = accessTokenQuery; - } - return new HTTPRequest(uriBuilder.ToString(), callback); - } - - - class InvalidTokenException : Exception { - public InvalidTokenException(string message) : base(message) { - } - } - - - /// - /// Lazy geocoder. - /// - Geocoder _geocoder; - public Geocoder Geocoder { - get { - if (_geocoder == null) { - _geocoder = new Geocoder(this); - } - return _geocoder; - } - } - - - /// - /// Lazy Directions. - /// - Directions _directions; - public Directions Directions { - get { - if (_directions == null) { - _directions = new Directions(this); - } - return _directions; - } - } + } + return request.text; + } + + + /// + /// Makes an asynchronous url query. + /// + /// The request. + /// URL. + /// Callback. + public IAsyncRequest Request(string url, Action callback, int timeout = 10) { + + var uriBuilder = new UriBuilder(url); + string accessTokenQuery = "access_token=" + AccessToken; + + if (uriBuilder.Query != null && uriBuilder.Query.Length > 1) { + uriBuilder.Query = uriBuilder.Query.Substring(1) + "&" + accessTokenQuery; + } else { + uriBuilder.Query = accessTokenQuery; + } + return IAsyncRequestFactory.CreateRequest(uriBuilder.ToString(), callback, timeout); + } + + + class InvalidTokenException : Exception { + public InvalidTokenException(string message) : base(message) { + } + } + + + /// + /// Lazy geocoder. + /// + Geocoder _geocoder; + public Geocoder Geocoder { + get { + if (_geocoder == null) { + _geocoder = new Geocoder(this); + } + return _geocoder; + } + } + + + /// + /// Lazy Directions. + /// + Directions _directions; + public Directions Directions { + get { + if (_directions == null) { + _directions = new Directions(this); + } + return _directions; + } + } #if !NETFX_CORE - public bool MyRemoteCertificateValidationCallback(System.Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { - bool isOk = true; - // If there are errors in the certificate chain, look at each error to determine the cause. - if (sslPolicyErrors != SslPolicyErrors.None) { - for (int i = 0; i < chain.ChainStatus.Length; i++) { - if (chain.ChainStatus[i].Status != X509ChainStatusFlags.RevocationStatusUnknown) { - chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; - chain.ChainPolicy.RevocationMode = X509RevocationMode.Online; - chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0); - chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags; - bool chainIsValid = chain.Build((X509Certificate2)certificate); - if (!chainIsValid) { - isOk = false; - } - } - } - } - return isOk; - } + public bool MyRemoteCertificateValidationCallback(System.Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { + bool isOk = true; + // If there are errors in the certificate chain, look at each error to determine the cause. + if (sslPolicyErrors != SslPolicyErrors.None) { + for (int i = 0; i < chain.ChainStatus.Length; i++) { + if (chain.ChainStatus[i].Status != X509ChainStatusFlags.RevocationStatusUnknown) { + chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; + chain.ChainPolicy.RevocationMode = X509RevocationMode.Online; + chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0); + chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags; + bool chainIsValid = chain.Build((X509Certificate2)certificate); + if (!chainIsValid) { + isOk = false; + } + } + } + } + return isOk; + } #endif - } + } } diff --git a/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/MapImageFactory.cs b/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/MapImageFactory.cs index 0965f39c3..6426aebb7 100644 --- a/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/MapImageFactory.cs +++ b/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/MapImageFactory.cs @@ -1,117 +1,101 @@ using Mapbox.Unity.Utilities; -namespace Mapbox.Unity.MeshGeneration.Factories -{ - using System; - using System.Collections.Generic; - using Mapbox.Map; - using UnityEngine; - using Mapbox.Unity.MeshGeneration.Enums; - using Mapbox.Unity.MeshGeneration.Data; - using Mapbox.Platform; +namespace Mapbox.Unity.MeshGeneration.Factories { + using System; + using System.Collections.Generic; + using Mapbox.Map; + using UnityEngine; + using Mapbox.Unity.MeshGeneration.Enums; + using Mapbox.Unity.MeshGeneration.Data; + using Mapbox.Platform; - public enum MapImageType - { - BasicMapboxStyle, - Custom, - None - } + public enum MapImageType { + BasicMapboxStyle, + Custom, + None + } - /// - /// Uses raster image services to create materials & textures for terrain - /// - [CreateAssetMenu(menuName = "Mapbox/Factories/Map Image Factory")] - public class MapImageFactory : Factory - { - [SerializeField] - private MapImageType _mapIdType; - [SerializeField] - private string _customMapId = ""; - [SerializeField] - private string _mapId = ""; - [SerializeField] - public Material _baseMaterial; + /// + /// Uses raster image services to create materials & textures for terrain + /// + [CreateAssetMenu(menuName = "Mapbox/Factories/Map Image Factory")] + public class MapImageFactory : Factory { + [SerializeField] + private MapImageType _mapIdType; + [SerializeField] + private string _customMapId = ""; + [SerializeField] + private string _mapId = ""; + [SerializeField] + public Material _baseMaterial; - [SerializeField] - TextureFormat _textureFormat = TextureFormat.DXT1; + [SerializeField] + TextureFormat _textureFormat = TextureFormat.DXT1; - [SerializeField] - bool _useMipMap = false; + [SerializeField] + bool _useMipMap = false; - [SerializeField] - bool _useRetina; + [SerializeField] + bool _useRetina; - private Dictionary _tiles; + private Dictionary _tiles; - public override void Initialize(IFileSource fs) - { - base.Initialize(fs); - _tiles = new Dictionary(); - } + public override void Initialize(IFileSource fs) { + base.Initialize(fs); + _tiles = new Dictionary(); + } - public override void Register(UnityTile tile) - { - base.Register(tile); - _tiles.Add(tile.TileCoordinate, tile); - Run(tile); - } + public override void Register(UnityTile tile) { + base.Register(tile); + _tiles.Add(tile.TileCoordinate, tile); + Run(tile); + } - public override void Update() - { - base.Update(); - foreach (var tile in _tiles.Values) - { - Run(tile); - } - } + public override void Update() { + base.Update(); + foreach (var tile in _tiles.Values) { + Run(tile); + } + } - /// - /// Fetches the image and applies it to tile material. - /// MapImage factory currently supports both new (RasterTile) and classic (ClassicRasterTile) Mapbox styles. - /// - /// - private void Run(UnityTile tile) - { - if (!string.IsNullOrEmpty(_mapId)) - { - var parameters = new Tile.Parameters(); - parameters.Fs = this.FileSource; - parameters.Id = new CanonicalTileId(tile.Zoom, (int)tile.TileCoordinate.x, (int)tile.TileCoordinate.y); - parameters.MapId = _mapId; + /// + /// Fetches the image and applies it to tile material. + /// MapImage factory currently supports both new (RasterTile) and classic (ClassicRasterTile) Mapbox styles. + /// + /// + private void Run(UnityTile tile) { + if (!string.IsNullOrEmpty(_mapId)) { + var parameters = new Tile.Parameters(); + parameters.Fs = this.FileSource; + parameters.Id = new CanonicalTileId(tile.Zoom, (int)tile.TileCoordinate.x, (int)tile.TileCoordinate.y); + parameters.MapId = _mapId; - tile.ImageDataState = TilePropertyState.Loading; + tile.ImageDataState = TilePropertyState.Loading; - RasterTile rasterTile; - if (parameters.MapId.StartsWith("mapbox://", StringComparison.Ordinal)) - { - rasterTile = _useRetina ? new RetinaRasterTile() : new RasterTile(); - } - else - { - rasterTile = _useRetina ? new ClassicRetinaRasterTile() : new ClassicRasterTile(); - } + RasterTile rasterTile; + if (parameters.MapId.StartsWith("mapbox://", StringComparison.Ordinal)) { + rasterTile = _useRetina ? new RetinaRasterTile() : new RasterTile(); + } else { + rasterTile = _useRetina ? new ClassicRetinaRasterTile() : new ClassicRasterTile(); + } - rasterTile.Initialize(parameters, (Action)(() => - { - if (rasterTile.Error != null) - { - tile.ImageDataState = TilePropertyState.Error; - return; - } + rasterTile.Initialize(parameters, (Action)(() => { + if (rasterTile.HasError) { + tile.ImageDataState = TilePropertyState.Error; + return; + } - var rend = tile.GetComponent(); - rend.material = _baseMaterial; - tile.ImageData = new Texture2D(0, 0, _textureFormat, _useMipMap); - tile.ImageData.LoadImage(rasterTile.Data); - rend.material.mainTexture = tile.ImageData; - tile.ImageDataState = TilePropertyState.Loaded; + var rend = tile.GetComponent(); + rend.material = _baseMaterial; + tile.ImageData = new Texture2D(0, 0, _textureFormat, _useMipMap); + tile.ImageData.LoadImage(rasterTile.Data); + rend.material.mainTexture = tile.ImageData; + tile.ImageDataState = TilePropertyState.Loaded; - })); - } - else - { - var rend = tile.GetComponent(); - rend.material = _baseMaterial; - } - } - } + })); + } else { + var rend = tile.GetComponent(); + rend.material = _baseMaterial; + } + } + } } diff --git a/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/MeshFactory.cs b/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/MeshFactory.cs index 31704b475..9665bb367 100644 --- a/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/MeshFactory.cs +++ b/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/MeshFactory.cs @@ -1,130 +1,108 @@ -namespace Mapbox.Unity.MeshGeneration.Factories -{ - using System.Collections.Generic; - using UnityEngine; - using Mapbox.Unity.MeshGeneration.Enums; - using Mapbox.Unity.MeshGeneration.Data; - using Mapbox.Unity.MeshGeneration.Interfaces; - using Mapbox.Platform; +namespace Mapbox.Unity.MeshGeneration.Factories { + using System.Collections.Generic; + using UnityEngine; + using Mapbox.Unity.MeshGeneration.Enums; + using Mapbox.Unity.MeshGeneration.Data; + using Mapbox.Unity.MeshGeneration.Interfaces; + using Mapbox.Platform; - /// - /// Uses vector tile api to visualize vector data. - /// Fetches the vector data for given tile and passes layer data to layer visualizers. - /// - [CreateAssetMenu(menuName = "Mapbox/Factories/Mesh Factory")] - public class MeshFactory : Factory - { - [SerializeField] - private string _mapId = ""; - public List Visualizers; + /// + /// Uses vector tile api to visualize vector data. + /// Fetches the vector data for given tile and passes layer data to layer visualizers. + /// + [CreateAssetMenu(menuName = "Mapbox/Factories/Mesh Factory")] + public class MeshFactory : Factory { + [SerializeField] + private string _mapId = ""; + public List Visualizers; - private Dictionary _tiles; - private Dictionary> _layerBuilder; + private Dictionary _tiles; + private Dictionary> _layerBuilder; - public void OnEnable() - { - if (Visualizers == null) - Visualizers = new List(); - } + public void OnEnable() { + if (Visualizers == null) + Visualizers = new List(); + } - /// - /// Sets up the Mesh Factory - /// - /// - public override void Initialize(IFileSource fs) - { - base.Initialize(fs); - _tiles = new Dictionary(); - _layerBuilder = new Dictionary>(); - foreach (LayerVisualizerBase factory in Visualizers) - { - if (_layerBuilder.ContainsKey(factory.Key)) - { - _layerBuilder[factory.Key].Add(factory); - } - else - { - _layerBuilder.Add(factory.Key, new List() { factory }); - } - } - } + /// + /// Sets up the Mesh Factory + /// + /// + public override void Initialize(IFileSource fs) { + base.Initialize(fs); + _tiles = new Dictionary(); + _layerBuilder = new Dictionary>(); + foreach (LayerVisualizerBase factory in Visualizers) { + if (_layerBuilder.ContainsKey(factory.Key)) { + _layerBuilder[factory.Key].Add(factory); + } else { + _layerBuilder.Add(factory.Key, new List() { factory }); + } + } + } - public override void Register(UnityTile tile) - { - base.Register(tile); - _tiles.Add(tile.TileCoordinate, tile); - Run(tile); - } + public override void Register(UnityTile tile) { + base.Register(tile); + _tiles.Add(tile.TileCoordinate, tile); + Run(tile); + } - /// - /// Mesh Factory waits for both Height and Image data to be processed if they are requested - /// - /// - private void Run(UnityTile tile) - { - if (tile.HeightDataState == TilePropertyState.Loading || - tile.ImageDataState == TilePropertyState.Loading) - { - tile.HeightDataChanged += HeightDataChangedHandler; - tile.ImageDataChanged += ImageDataChangedHandler; - } - else - { - CreateMeshes(tile, null); - } - } + /// + /// Mesh Factory waits for both Height and Image data to be processed if they are requested + /// + /// + private void Run(UnityTile tile) { + if (tile.HeightDataState == TilePropertyState.Loading || + tile.ImageDataState == TilePropertyState.Loading) { + tile.HeightDataChanged += HeightDataChangedHandler; + tile.ImageDataChanged += ImageDataChangedHandler; + } else { + CreateMeshes(tile, null); + } + } - private void HeightDataChangedHandler(UnityTile t, object e) - { - if (t.ImageDataState != TilePropertyState.Loading) - CreateMeshes(t, e); - } + private void HeightDataChangedHandler(UnityTile t, object e) { + if (t.ImageDataState != TilePropertyState.Loading) + CreateMeshes(t, e); + } - private void ImageDataChangedHandler(UnityTile t, object e) - { - if (t.HeightDataState != TilePropertyState.Loading) - CreateMeshes(t, e); - } + private void ImageDataChangedHandler(UnityTile t, object e) { + if (t.HeightDataState != TilePropertyState.Loading) + CreateMeshes(t, e); + } - /// - /// Fetches the vector data and passes each layer to relevant layer visualizers - /// - /// - /// - private void CreateMeshes(UnityTile tile, object e) - { - tile.HeightDataChanged -= HeightDataChangedHandler; - tile.ImageDataChanged -= ImageDataChangedHandler; + /// + /// Fetches the vector data and passes each layer to relevant layer visualizers + /// + /// + /// + private void CreateMeshes(UnityTile tile, object e) { + tile.HeightDataChanged -= HeightDataChangedHandler; + tile.ImageDataChanged -= ImageDataChangedHandler; - var parameters = new Mapbox.Map.Tile.Parameters - { - Fs = this.FileSource, - Id = new Mapbox.Map.CanonicalTileId(tile.Zoom, (int)tile.TileCoordinate.x, (int)tile.TileCoordinate.y), - MapId = _mapId - }; + var parameters = new Mapbox.Map.Tile.Parameters { + Fs = this.FileSource, + Id = new Mapbox.Map.CanonicalTileId(tile.Zoom, (int)tile.TileCoordinate.x, (int)tile.TileCoordinate.y), + MapId = _mapId + }; - var vectorTile = new Mapbox.Map.VectorTile(); - vectorTile.Initialize(parameters, () => - { - if (vectorTile.Error != null) - { - Debug.Log(vectorTile.Error); - return; - } + var vectorTile = new Mapbox.Map.VectorTile(); + vectorTile.Initialize(parameters, () => { + if (vectorTile.HasError) { + Debug.Log(vectorTile.ExceptionsAsString); + return; + } - foreach (var layerName in vectorTile.Data.LayerNames()) - { - if (_layerBuilder.ContainsKey(layerName)) - { - foreach (var builder in _layerBuilder[layerName]) - { - if (builder.Active) - builder.Create(vectorTile.Data.GetLayer(layerName), tile); - } - } - } - }); - } - } + foreach (var layerName in vectorTile.Data.LayerNames()) { + if (_layerBuilder.ContainsKey(layerName)) { + foreach (var builder in _layerBuilder[layerName]) { + if (builder.Active) + builder.Create(vectorTile.Data.GetLayer(layerName), tile); + } + } + } + }); + } + } } diff --git a/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/TerrainFactory.cs b/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/TerrainFactory.cs index a6dae00f0..2f5ad4397 100644 --- a/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/TerrainFactory.cs +++ b/sdkproject/Assets/Mapbox/Core/Unity/MeshGeneration/Factories/TerrainFactory.cs @@ -1,398 +1,355 @@ -namespace Mapbox.Unity.MeshGeneration.Factories -{ - using System.Collections.Generic; - using UnityEngine; - using Mapbox.Map; - using Mapbox.Unity.MeshGeneration.Enums; - using Mapbox.Unity.MeshGeneration.Data; - using Mapbox.Platform; - using Mapbox.Unity.Utilities; - using Utils; - - public enum TerrainGenerationType - { - Flat, - Height, - ModifiedHeight - } - - public enum MapIdType - { - Standard, - Custom - } - - /// - /// Uses Mapbox Terrain api and creates terrain meshes. - /// - [CreateAssetMenu(menuName = "Mapbox/Factories/Terrain Factory")] - public class TerrainFactory : Factory - { - [SerializeField] - private TerrainGenerationType _generationType; - [SerializeField] - private Material _baseMaterial; - - [SerializeField] - private MapIdType _mapIdType; - [SerializeField] - private string _customMapId = "mapbox.terrain-rgb"; - [SerializeField] - private string _mapId = ""; - [SerializeField] - private float _heightModifier = 1f; - [SerializeField] - private int _sampleCount = 40; - - private Dictionary _tiles; - private Vector2 _stitchTarget; - - public override void Initialize(IFileSource fs) - { - base.Initialize(fs); - _tiles = new Dictionary(); - } - - public override void Register(UnityTile tile) - { - base.Register(tile); - _tiles.Add(tile.TileCoordinate, tile); - Run(tile); - } - - /// - /// Clears the mesh data and re-runs the terrain creation procedure using current settings. Clearing the old mesh data is important as terrain stitching function checks if the data exists or not. - /// - public override void Update() - { - base.Update(); - foreach (var tile in _tiles.Values) - { - tile.MeshData = null; - } - foreach (var tile in _tiles.Values) - { - Run(tile); - } - } - - private void Run(UnityTile tile) - { - if (_generationType == TerrainGenerationType.Height) - { - CreateTerrainHeight(tile); - } - else if (_generationType == TerrainGenerationType.ModifiedHeight) - { - CreateTerrainHeight(tile, _heightModifier); - } - else if (_generationType == TerrainGenerationType.Flat) - { - CreateFlatMesh(tile); - } - } - - /// - /// Creates the non-flat terrain using a height multiplier - /// - /// - /// Multiplier for queried height value - private void CreateTerrainHeight(UnityTile tile, float heightMultiplier = 1) - { - if (tile.HeightData == null) - { - var parameters = new Tile.Parameters - { - Fs = this.FileSource, - Id = new CanonicalTileId(tile.Zoom, (int)tile.TileCoordinate.x, (int)tile.TileCoordinate.y), - MapId = _mapId - }; - - tile.HeightDataState = TilePropertyState.Loading; - var pngRasterTile = new RawPngRasterTile(); - pngRasterTile.Initialize(parameters, () => - { - if (pngRasterTile.Error != null) - { - tile.HeightDataState = TilePropertyState.Error; - return; - } - var texture = new Texture2D(256, 256); - texture.wrapMode = TextureWrapMode.Clamp; - texture.LoadImage(pngRasterTile.Data); - tile.HeightData = texture; - tile.HeightDataState = TilePropertyState.Loaded; - GenerateTerrainMesh(tile, heightMultiplier); - }); - } - else - { - GenerateTerrainMesh(tile, heightMultiplier); - } - } - - /// - /// Creates the non-flat terrain mesh, using a grid by defined resolution (_sampleCount). Vertex order goes right & up. Normals are calculated manually and UV map is fitted/stretched 1-1. - /// Any additional scripts or logic, like MeshCollider or setting layer, can be done here. - /// - /// - /// Multiplier for queried height value - private void GenerateTerrainMesh(UnityTile tile, float heightMultiplier) - { - var go = tile.gameObject; - var mesh = new MeshData(); - mesh.Vertices = new List(_sampleCount * _sampleCount); - var step = 1f / (_sampleCount - 1); - for (float y = 0; y < _sampleCount; y++) - { - var yrat = y / (_sampleCount - 1); - for (float x = 0; x < _sampleCount; x++) - { - var xrat = x / (_sampleCount - 1); - - var xx = Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, xrat); - var yy = Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, yrat); - - mesh.Vertices.Add(new Vector3( - (float)(xx - tile.Rect.Center.x), - heightMultiplier * Conversions.GetRelativeHeightFromColor(tile.HeightData.GetPixel( - (int)(xrat * 255), - (int)((1 - yrat) * 255)), - tile.RelativeScale), - (float)(yy - tile.Rect.Center.y))); - mesh.Normals.Add(Unity.Constants.Math.Vector3Up); - mesh.UV[0].Add(new Vector2(x * step, 1 - (y * step))); - } - } - - var trilist = new List(); - var dir = Vector3.zero; - int vertA, vertB, vertC; - for (int y = 0; y < _sampleCount - 1; y++) - { - for (int x = 0; x < _sampleCount - 1; x++) - { - vertA = (y * _sampleCount) + x; - vertB = (y * _sampleCount) + x + _sampleCount + 1; - vertC = (y * _sampleCount) + x + _sampleCount; - trilist.Add(vertA); - trilist.Add(vertB); - trilist.Add(vertC); - dir = Vector3.Cross(mesh.Vertices[vertB] - mesh.Vertices[vertA], mesh.Vertices[vertC] - mesh.Vertices[vertA]); - mesh.Normals[vertA] += dir; - mesh.Normals[vertB] += dir; - mesh.Normals[vertC] += dir; - - vertA = (y * _sampleCount) + x; - vertB = (y * _sampleCount) + x + 1; - vertC = (y * _sampleCount) + x + _sampleCount + 1; - trilist.Add(vertA); - trilist.Add(vertB); - trilist.Add(vertC); - dir = Vector3.Cross(mesh.Vertices[vertB] - mesh.Vertices[vertA], mesh.Vertices[vertC] - mesh.Vertices[vertA]); - mesh.Normals[vertA] += dir; - mesh.Normals[vertB] += dir; - mesh.Normals[vertC] += dir; - } - } - mesh.Triangles.Add(trilist); - - for (int i = 0; i < mesh.Vertices.Count; i++) - { - mesh.Normals[i].Normalize(); - } - - FixStitches(tile, mesh); - - tile.MeshData = mesh; - var uMesh = new Mesh(); - uMesh.SetVertices(mesh.Vertices); - uMesh.SetUVs(0, mesh.UV[0]); - uMesh.SetNormals(mesh.Normals); - uMesh.SetTriangles(mesh.Triangles[0], 0); - tile.MeshFilter.sharedMesh = uMesh; - - if (tile.MeshRenderer.material == null) - tile.MeshRenderer.material = _baseMaterial; - //BRNKHY Optional stuff - //go.AddComponent(); - //go.layer = LayerMask.NameToLayer("terrain"); - } - - /// - /// Creates a basic quad to be used as flat base mesh. Normals are up and UV is fitted to quad. - /// A quad is enough for basic usage but the resolution should be increased if any mesh deformation, like bending, to work. - /// - /// - private void CreateFlatMesh(UnityTile tile) - { - var mesh = new Mesh(); - var verts = new Vector3[4]; - - verts[0] = ((tile.Rect.Min - tile.Rect.Center).ToVector3xz()); - verts[2] = (new Vector3((float)(tile.Rect.Min.x - tile.Rect.Center.x), 0, (float)(tile.Rect.Max.y - tile.Rect.Center.y))); - verts[1] = (new Vector3((float)(tile.Rect.Max.x - tile.Rect.Center.x), 0, (float)(tile.Rect.Min.y - tile.Rect.Center.y))); - verts[3] = ((tile.Rect.Max - tile.Rect.Center).ToVector3xz()); - - mesh.vertices = verts; - var trilist = new int[6] { 0, 1, 2, 1, 3, 2 }; - mesh.SetTriangles(trilist, 0); - var uvlist = new Vector2[4] - { - new Vector2(0,1), - new Vector2(1,1), - new Vector2(0,0), - new Vector2(1,0) - }; - mesh.uv = uvlist; - mesh.RecalculateNormals(); - tile.MeshFilter.sharedMesh = mesh; - if (tile.MeshRenderer.material == null) - tile.MeshRenderer.material = _baseMaterial; - - //BRNKHY Optional stuff - //go.AddComponent(); - //go.layer = LayerMask.NameToLayer("terrain"); - } - - /// - /// Checkes all neighbours of the given tile and stitches the edges to achieve a smooth mesh surface. - /// - /// - /// - private void FixStitches(UnityTile tile, MeshData tmesh) - { - _stitchTarget.Set(tile.TileCoordinate.x, tile.TileCoordinate.y - 1); - if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) - { - var t2mesh = _tiles[_stitchTarget].MeshData; - - for (int i = 0; i < _sampleCount; i++) - { - //just snapping the y because vertex pos is relative and we'll have to do tile pos + vertex pos for x&z otherwise - tmesh.Vertices[i] = new Vector3( - tmesh.Vertices[i].x, - t2mesh.Vertices[tmesh.Vertices.Count - _sampleCount + i].y, - tmesh.Vertices[i].z); - tmesh.Normals[i] = new Vector3(t2mesh.Normals[tmesh.Vertices.Count - _sampleCount + i].x, - t2mesh.Normals[tmesh.Vertices.Count - _sampleCount + i].y, - t2mesh.Normals[tmesh.Vertices.Count - _sampleCount + i].z); - } - } - - _stitchTarget.Set(tile.TileCoordinate.x, tile.TileCoordinate.y + 1); - if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) - { - var t2mesh = _tiles[_stitchTarget].MeshData; - for (int i = 0; i < _sampleCount; i++) - { - tmesh.Vertices[tmesh.Vertices.Count - _sampleCount + i] = new Vector3( - tmesh.Vertices[tmesh.Vertices.Count - _sampleCount + i].x, - t2mesh.Vertices[i].y, - tmesh.Vertices[tmesh.Vertices.Count - _sampleCount + i].z); - - tmesh.Normals[tmesh.Vertices.Count - _sampleCount + i] = new Vector3( - t2mesh.Normals[i].x, - t2mesh.Normals[i].y, - t2mesh.Normals[i].z); - } - } - - _stitchTarget.Set(tile.TileCoordinate.x - 1, tile.TileCoordinate.y); - if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) - { - var t2mesh = _tiles[_stitchTarget].MeshData; - for (int i = 0; i < _sampleCount; i++) - { - tmesh.Vertices[i * _sampleCount] = new Vector3( - tmesh.Vertices[i * _sampleCount].x, - t2mesh.Vertices[i * _sampleCount + _sampleCount - 1].y, - tmesh.Vertices[i * _sampleCount].z); - tmesh.Normals[i * _sampleCount] = new Vector3( - t2mesh.Normals[i * _sampleCount + _sampleCount - 1].x, - t2mesh.Normals[i * _sampleCount + _sampleCount - 1].y, - t2mesh.Normals[i * _sampleCount + _sampleCount - 1].z); - } - } - - _stitchTarget.Set(tile.TileCoordinate.x + 1, tile.TileCoordinate.y); - if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) - { - var t2mesh = _tiles[_stitchTarget].MeshData; - for (int i = 0; i < _sampleCount; i++) - { - tmesh.Vertices[i * _sampleCount + _sampleCount - 1] = new Vector3( - tmesh.Vertices[i * _sampleCount + _sampleCount - 1].x, - t2mesh.Vertices[i * _sampleCount].y, - tmesh.Vertices[i * _sampleCount + _sampleCount - 1].z); - tmesh.Normals[i * _sampleCount + _sampleCount - 1] = new Vector3( - t2mesh.Normals[i * _sampleCount].x, - t2mesh.Normals[i * _sampleCount].y, - t2mesh.Normals[i * _sampleCount].z); - } - } - - _stitchTarget.Set(tile.TileCoordinate.x - 1, tile.TileCoordinate.y - 1); - if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) - { - var t2mesh = _tiles[_stitchTarget].MeshData; - tmesh.Vertices[0] = new Vector3( - tmesh.Vertices[0].x, - t2mesh.Vertices[t2mesh.Vertices.Count - 1].y, - tmesh.Vertices[0].z); - tmesh.Normals[0] = new Vector3( - t2mesh.Normals[t2mesh.Vertices.Count - 1].x, - t2mesh.Normals[t2mesh.Vertices.Count - 1].y, - t2mesh.Normals[t2mesh.Vertices.Count - 1].z); - } - - _stitchTarget.Set(tile.TileCoordinate.x + 1, tile.TileCoordinate.y - 1); - if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) - { - var t2mesh = _tiles[_stitchTarget].MeshData; - tmesh.Vertices[_sampleCount - 1] = new Vector3( - tmesh.Vertices[_sampleCount - 1].x, - t2mesh.Vertices[t2mesh.Vertices.Count - _sampleCount].y, - tmesh.Vertices[_sampleCount - 1].z); - tmesh.Normals[_sampleCount - 1] = new Vector3( - t2mesh.Normals[t2mesh.Vertices.Count - _sampleCount].x, - t2mesh.Normals[t2mesh.Vertices.Count - _sampleCount].y, - t2mesh.Normals[t2mesh.Vertices.Count - _sampleCount].z); - } - - _stitchTarget.Set(tile.TileCoordinate.x - 1, tile.TileCoordinate.y + 1); - if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) - { - var t2mesh = _tiles[_stitchTarget].MeshData; - tmesh.Vertices[tmesh.Vertices.Count - _sampleCount] = new Vector3( - tmesh.Vertices[tmesh.Vertices.Count - _sampleCount].x, - t2mesh.Vertices[_sampleCount - 1].y, - tmesh.Vertices[tmesh.Vertices.Count - _sampleCount].z); - tmesh.Normals[tmesh.Vertices.Count - _sampleCount] = new Vector3( - t2mesh.Normals[_sampleCount - 1].x, - t2mesh.Normals[_sampleCount - 1].y, - t2mesh.Normals[_sampleCount - 1].z); - } - - _stitchTarget.Set(tile.TileCoordinate.x + 1, tile.TileCoordinate.y + 1); - if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) - { - var t2mesh = _tiles[_stitchTarget].MeshData; - tmesh.Vertices[t2mesh.Vertices.Count - 1] = new Vector3( - tmesh.Vertices[t2mesh.Vertices.Count - 1].x, - t2mesh.Vertices[0].y, - tmesh.Vertices[t2mesh.Vertices.Count - 1].z); - tmesh.Normals[t2mesh.Vertices.Count - 1] = new Vector3( - t2mesh.Normals[0].x, - t2mesh.Normals[0].y, - t2mesh.Normals[0].z); - } - } - - private float GetHeightFromColor(Color c) - { - //additional *256 to switch from 0-1 to 0-256 - return (float)(-10000 + ((c.r * 16777216 + c.g * 65536 + c.b * 256) * 0.1)); - } - } +namespace Mapbox.Unity.MeshGeneration.Factories { + using System.Collections.Generic; + using UnityEngine; + using Mapbox.Map; + using Mapbox.Unity.MeshGeneration.Enums; + using Mapbox.Unity.MeshGeneration.Data; + using Mapbox.Platform; + using Mapbox.Unity.Utilities; + using Utils; + + public enum TerrainGenerationType { + Flat, + Height, + ModifiedHeight + } + + public enum MapIdType { + Standard, + Custom + } + + /// + /// Uses Mapbox Terrain api and creates terrain meshes. + /// + [CreateAssetMenu(menuName = "Mapbox/Factories/Terrain Factory")] + public class TerrainFactory : Factory { + [SerializeField] + private TerrainGenerationType _generationType; + [SerializeField] + private Material _baseMaterial; + + [SerializeField] + private MapIdType _mapIdType; + [SerializeField] + private string _customMapId = "mapbox.terrain-rgb"; + [SerializeField] + private string _mapId = ""; + [SerializeField] + private float _heightModifier = 1f; + [SerializeField] + private int _sampleCount = 40; + + private Dictionary _tiles; + private Vector2 _stitchTarget; + + public override void Initialize(IFileSource fs) { + base.Initialize(fs); + _tiles = new Dictionary(); + } + + public override void Register(UnityTile tile) { + base.Register(tile); + _tiles.Add(tile.TileCoordinate, tile); + Run(tile); + } + + /// + /// Clears the mesh data and re-runs the terrain creation procedure using current settings. Clearing the old mesh data is important as terrain stitching function checks if the data exists or not. + /// + public override void Update() { + base.Update(); + foreach (var tile in _tiles.Values) { + tile.MeshData = null; + } + foreach (var tile in _tiles.Values) { + Run(tile); + } + } + + private void Run(UnityTile tile) { + if (_generationType == TerrainGenerationType.Height) { + CreateTerrainHeight(tile); + } else if (_generationType == TerrainGenerationType.ModifiedHeight) { + CreateTerrainHeight(tile, _heightModifier); + } else if (_generationType == TerrainGenerationType.Flat) { + CreateFlatMesh(tile); + } + } + + /// + /// Creates the non-flat terrain using a height multiplier + /// + /// + /// Multiplier for queried height value + private void CreateTerrainHeight(UnityTile tile, float heightMultiplier = 1) { + if (tile.HeightData == null) { + var parameters = new Tile.Parameters { + Fs = this.FileSource, + Id = new CanonicalTileId(tile.Zoom, (int)tile.TileCoordinate.x, (int)tile.TileCoordinate.y), + MapId = _mapId + }; + + tile.HeightDataState = TilePropertyState.Loading; + var pngRasterTile = new RawPngRasterTile(); + pngRasterTile.Initialize(parameters, () => { + if (pngRasterTile.HasError) { + tile.HeightDataState = TilePropertyState.Error; + return; + } + var texture = new Texture2D(256, 256); + texture.wrapMode = TextureWrapMode.Clamp; + texture.LoadImage(pngRasterTile.Data); + tile.HeightData = texture; + tile.HeightDataState = TilePropertyState.Loaded; + GenerateTerrainMesh(tile, heightMultiplier); + }); + } else { + GenerateTerrainMesh(tile, heightMultiplier); + } + } + + /// + /// Creates the non-flat terrain mesh, using a grid by defined resolution (_sampleCount). Vertex order goes right & up. Normals are calculated manually and UV map is fitted/stretched 1-1. + /// Any additional scripts or logic, like MeshCollider or setting layer, can be done here. + /// + /// + /// Multiplier for queried height value + private void GenerateTerrainMesh(UnityTile tile, float heightMultiplier) { + var go = tile.gameObject; + var mesh = new MeshData(); + mesh.Vertices = new List(_sampleCount * _sampleCount); + var step = 1f / (_sampleCount - 1); + for (float y = 0; y < _sampleCount; y++) { + var yrat = y / (_sampleCount - 1); + for (float x = 0; x < _sampleCount; x++) { + var xrat = x / (_sampleCount - 1); + + var xx = Mathd.Lerp(tile.Rect.Min.x, tile.Rect.Max.x, xrat); + var yy = Mathd.Lerp(tile.Rect.Min.y, tile.Rect.Max.y, yrat); + + mesh.Vertices.Add(new Vector3( + (float)(xx - tile.Rect.Center.x), + heightMultiplier * Conversions.GetRelativeHeightFromColor(tile.HeightData.GetPixel( + (int)(xrat * 255), + (int)((1 - yrat) * 255)), + tile.RelativeScale), + (float)(yy - tile.Rect.Center.y))); + mesh.Normals.Add(Unity.Constants.Math.Vector3Up); + mesh.UV[0].Add(new Vector2(x * step, 1 - (y * step))); + } + } + + var trilist = new List(); + var dir = Vector3.zero; + int vertA, vertB, vertC; + for (int y = 0; y < _sampleCount - 1; y++) { + for (int x = 0; x < _sampleCount - 1; x++) { + vertA = (y * _sampleCount) + x; + vertB = (y * _sampleCount) + x + _sampleCount + 1; + vertC = (y * _sampleCount) + x + _sampleCount; + trilist.Add(vertA); + trilist.Add(vertB); + trilist.Add(vertC); + dir = Vector3.Cross(mesh.Vertices[vertB] - mesh.Vertices[vertA], mesh.Vertices[vertC] - mesh.Vertices[vertA]); + mesh.Normals[vertA] += dir; + mesh.Normals[vertB] += dir; + mesh.Normals[vertC] += dir; + + vertA = (y * _sampleCount) + x; + vertB = (y * _sampleCount) + x + 1; + vertC = (y * _sampleCount) + x + _sampleCount + 1; + trilist.Add(vertA); + trilist.Add(vertB); + trilist.Add(vertC); + dir = Vector3.Cross(mesh.Vertices[vertB] - mesh.Vertices[vertA], mesh.Vertices[vertC] - mesh.Vertices[vertA]); + mesh.Normals[vertA] += dir; + mesh.Normals[vertB] += dir; + mesh.Normals[vertC] += dir; + } + } + mesh.Triangles.Add(trilist); + + for (int i = 0; i < mesh.Vertices.Count; i++) { + mesh.Normals[i].Normalize(); + } + + FixStitches(tile, mesh); + + tile.MeshData = mesh; + var uMesh = new Mesh(); + uMesh.SetVertices(mesh.Vertices); + uMesh.SetUVs(0, mesh.UV[0]); + uMesh.SetNormals(mesh.Normals); + uMesh.SetTriangles(mesh.Triangles[0], 0); + tile.MeshFilter.sharedMesh = uMesh; + + if (tile.MeshRenderer.material == null) + tile.MeshRenderer.material = _baseMaterial; + //BRNKHY Optional stuff + //go.AddComponent(); + //go.layer = LayerMask.NameToLayer("terrain"); + } + + /// + /// Creates a basic quad to be used as flat base mesh. Normals are up and UV is fitted to quad. + /// A quad is enough for basic usage but the resolution should be increased if any mesh deformation, like bending, to work. + /// + /// + private void CreateFlatMesh(UnityTile tile) { + var mesh = new Mesh(); + var verts = new Vector3[4]; + + verts[0] = ((tile.Rect.Min - tile.Rect.Center).ToVector3xz()); + verts[2] = (new Vector3((float)(tile.Rect.Min.x - tile.Rect.Center.x), 0, (float)(tile.Rect.Max.y - tile.Rect.Center.y))); + verts[1] = (new Vector3((float)(tile.Rect.Max.x - tile.Rect.Center.x), 0, (float)(tile.Rect.Min.y - tile.Rect.Center.y))); + verts[3] = ((tile.Rect.Max - tile.Rect.Center).ToVector3xz()); + + mesh.vertices = verts; + var trilist = new int[6] { 0, 1, 2, 1, 3, 2 }; + mesh.SetTriangles(trilist, 0); + var uvlist = new Vector2[4] + { + new Vector2(0,1), + new Vector2(1,1), + new Vector2(0,0), + new Vector2(1,0) + }; + mesh.uv = uvlist; + mesh.RecalculateNormals(); + tile.MeshFilter.sharedMesh = mesh; + if (tile.MeshRenderer.material == null) + tile.MeshRenderer.material = _baseMaterial; + + //BRNKHY Optional stuff + //go.AddComponent(); + //go.layer = LayerMask.NameToLayer("terrain"); + } + + /// + /// Checkes all neighbours of the given tile and stitches the edges to achieve a smooth mesh surface. + /// + /// + /// + private void FixStitches(UnityTile tile, MeshData tmesh) { + _stitchTarget.Set(tile.TileCoordinate.x, tile.TileCoordinate.y - 1); + if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) { + var t2mesh = _tiles[_stitchTarget].MeshData; + + for (int i = 0; i < _sampleCount; i++) { + //just snapping the y because vertex pos is relative and we'll have to do tile pos + vertex pos for x&z otherwise + tmesh.Vertices[i] = new Vector3( + tmesh.Vertices[i].x, + t2mesh.Vertices[tmesh.Vertices.Count - _sampleCount + i].y, + tmesh.Vertices[i].z); + tmesh.Normals[i] = new Vector3(t2mesh.Normals[tmesh.Vertices.Count - _sampleCount + i].x, + t2mesh.Normals[tmesh.Vertices.Count - _sampleCount + i].y, + t2mesh.Normals[tmesh.Vertices.Count - _sampleCount + i].z); + } + } + + _stitchTarget.Set(tile.TileCoordinate.x, tile.TileCoordinate.y + 1); + if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) { + var t2mesh = _tiles[_stitchTarget].MeshData; + for (int i = 0; i < _sampleCount; i++) { + tmesh.Vertices[tmesh.Vertices.Count - _sampleCount + i] = new Vector3( + tmesh.Vertices[tmesh.Vertices.Count - _sampleCount + i].x, + t2mesh.Vertices[i].y, + tmesh.Vertices[tmesh.Vertices.Count - _sampleCount + i].z); + + tmesh.Normals[tmesh.Vertices.Count - _sampleCount + i] = new Vector3( + t2mesh.Normals[i].x, + t2mesh.Normals[i].y, + t2mesh.Normals[i].z); + } + } + + _stitchTarget.Set(tile.TileCoordinate.x - 1, tile.TileCoordinate.y); + if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) { + var t2mesh = _tiles[_stitchTarget].MeshData; + for (int i = 0; i < _sampleCount; i++) { + tmesh.Vertices[i * _sampleCount] = new Vector3( + tmesh.Vertices[i * _sampleCount].x, + t2mesh.Vertices[i * _sampleCount + _sampleCount - 1].y, + tmesh.Vertices[i * _sampleCount].z); + tmesh.Normals[i * _sampleCount] = new Vector3( + t2mesh.Normals[i * _sampleCount + _sampleCount - 1].x, + t2mesh.Normals[i * _sampleCount + _sampleCount - 1].y, + t2mesh.Normals[i * _sampleCount + _sampleCount - 1].z); + } + } + + _stitchTarget.Set(tile.TileCoordinate.x + 1, tile.TileCoordinate.y); + if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) { + var t2mesh = _tiles[_stitchTarget].MeshData; + for (int i = 0; i < _sampleCount; i++) { + tmesh.Vertices[i * _sampleCount + _sampleCount - 1] = new Vector3( + tmesh.Vertices[i * _sampleCount + _sampleCount - 1].x, + t2mesh.Vertices[i * _sampleCount].y, + tmesh.Vertices[i * _sampleCount + _sampleCount - 1].z); + tmesh.Normals[i * _sampleCount + _sampleCount - 1] = new Vector3( + t2mesh.Normals[i * _sampleCount].x, + t2mesh.Normals[i * _sampleCount].y, + t2mesh.Normals[i * _sampleCount].z); + } + } + + _stitchTarget.Set(tile.TileCoordinate.x - 1, tile.TileCoordinate.y - 1); + if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) { + var t2mesh = _tiles[_stitchTarget].MeshData; + tmesh.Vertices[0] = new Vector3( + tmesh.Vertices[0].x, + t2mesh.Vertices[t2mesh.Vertices.Count - 1].y, + tmesh.Vertices[0].z); + tmesh.Normals[0] = new Vector3( + t2mesh.Normals[t2mesh.Vertices.Count - 1].x, + t2mesh.Normals[t2mesh.Vertices.Count - 1].y, + t2mesh.Normals[t2mesh.Vertices.Count - 1].z); + } + + _stitchTarget.Set(tile.TileCoordinate.x + 1, tile.TileCoordinate.y - 1); + if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) { + var t2mesh = _tiles[_stitchTarget].MeshData; + tmesh.Vertices[_sampleCount - 1] = new Vector3( + tmesh.Vertices[_sampleCount - 1].x, + t2mesh.Vertices[t2mesh.Vertices.Count - _sampleCount].y, + tmesh.Vertices[_sampleCount - 1].z); + tmesh.Normals[_sampleCount - 1] = new Vector3( + t2mesh.Normals[t2mesh.Vertices.Count - _sampleCount].x, + t2mesh.Normals[t2mesh.Vertices.Count - _sampleCount].y, + t2mesh.Normals[t2mesh.Vertices.Count - _sampleCount].z); + } + + _stitchTarget.Set(tile.TileCoordinate.x - 1, tile.TileCoordinate.y + 1); + if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) { + var t2mesh = _tiles[_stitchTarget].MeshData; + tmesh.Vertices[tmesh.Vertices.Count - _sampleCount] = new Vector3( + tmesh.Vertices[tmesh.Vertices.Count - _sampleCount].x, + t2mesh.Vertices[_sampleCount - 1].y, + tmesh.Vertices[tmesh.Vertices.Count - _sampleCount].z); + tmesh.Normals[tmesh.Vertices.Count - _sampleCount] = new Vector3( + t2mesh.Normals[_sampleCount - 1].x, + t2mesh.Normals[_sampleCount - 1].y, + t2mesh.Normals[_sampleCount - 1].z); + } + + _stitchTarget.Set(tile.TileCoordinate.x + 1, tile.TileCoordinate.y + 1); + if (_tiles.ContainsKey(_stitchTarget) && _tiles[_stitchTarget].MeshData != null) { + var t2mesh = _tiles[_stitchTarget].MeshData; + tmesh.Vertices[t2mesh.Vertices.Count - 1] = new Vector3( + tmesh.Vertices[t2mesh.Vertices.Count - 1].x, + t2mesh.Vertices[0].y, + tmesh.Vertices[t2mesh.Vertices.Count - 1].z); + tmesh.Normals[t2mesh.Vertices.Count - 1] = new Vector3( + t2mesh.Normals[0].x, + t2mesh.Normals[0].y, + t2mesh.Normals[0].z); + } + } + + private float GetHeightFromColor(Color c) { + //additional *256 to switch from 0-1 to 0-256 + return (float)(-10000 + ((c.r * 16777216 + c.g * 65536 + c.b * 256) * 0.1)); + } + } } diff --git a/sdkproject/Assets/Mapbox/Core/Unity/Utilities/HTTPRequest.cs b/sdkproject/Assets/Mapbox/Core/Unity/Utilities/HTTPRequest.cs index 7ceb45546..bead61487 100644 --- a/sdkproject/Assets/Mapbox/Core/Unity/Utilities/HTTPRequest.cs +++ b/sdkproject/Assets/Mapbox/Core/Unity/Utilities/HTTPRequest.cs @@ -4,58 +4,62 @@ // //----------------------------------------------------------------------- -namespace Mapbox.Unity.Utilities -{ - using System; - using UnityEngine.Networking; - using System.Collections; - using Mapbox.Platform; + +namespace Mapbox.Unity.Utilities { + + using System; + using UnityEngine.Networking; + using System.Collections; + using Mapbox.Platform; #if UNITY_EDITOR - using UnityEditor; + using UnityEditor; #endif - internal sealed class HTTPRequest : IAsyncRequest - { - private UnityWebRequest _request; - private readonly Action _callback; + internal sealed class HTTPRequest : IAsyncRequest { + + private UnityWebRequest _request; + private int _timeout; + private readonly Action _callback; + + public bool IsCompleted { get; private set; } - public HTTPRequest(string url, Action callback) - { - _request = UnityWebRequest.Get(url); - _callback = callback; + public HTTPRequest(string url, Action callback, int timeout = 10) { + IsCompleted = false; + _timeout = timeout; + _request = UnityWebRequest.Get(url); + _callback = callback; #if UNITY_EDITOR - if (!EditorApplication.isPlaying) - { - Runnable.EnableRunnableInEditor(); - } + if (!EditorApplication.isPlaying) { + Runnable.EnableRunnableInEditor(); + } #endif - Runnable.Run(DoRequest()); - } - - public void Cancel() - { - if (_request != null) - { - _request.Abort(); - } - } - - private IEnumerator DoRequest() - { - _request.Send(); - while (!_request.isDone) - { - yield return 0; - } - var response = new Response(); - response.Error = this._request.error; - response.Data = this._request.downloadHandler.data; - - _callback(response); - _request.Dispose(); - _request = null; - } - } + Runnable.Run(DoRequest()); + } + + public void Cancel() { + if (_request != null) { + _request.Abort(); + } + } + + private IEnumerator DoRequest() { + _request.Send(); + while (!_request.isDone) { + yield return 0; + } + var response = new Response(); + // TODO: evalute _request more thoroughly and set properties of Response accordingly: status code, headers, etc. + if (!string.IsNullOrEmpty(_request.error)) { + response.AddException(new Exception(_request.error)); + } + response.Data = this._request.downloadHandler.data; + + _callback(response); + _request.Dispose(); + _request = null; + IsCompleted = true; + } + } } diff --git a/sdkproject/Assets/Mapbox/Examples/Playground/Scripts/RasterTileExample.cs b/sdkproject/Assets/Mapbox/Examples/Playground/Scripts/RasterTileExample.cs index c08d5aa96..0e190c8a4 100644 --- a/sdkproject/Assets/Mapbox/Examples/Playground/Scripts/RasterTileExample.cs +++ b/sdkproject/Assets/Mapbox/Examples/Playground/Scripts/RasterTileExample.cs @@ -4,129 +4,118 @@ // //----------------------------------------------------------------------- -namespace Mapbox.Examples.Playground -{ - using System.Linq; - using System; - using Mapbox.Map; - using Mapbox.Unity; - using UnityEngine; - using UnityEngine.UI; - using Mapbox.Utils; - using Mapbox.Unity.Utilities; - - public class RasterTileExample : MonoBehaviour, Mapbox.Utils.IObserver - { - [SerializeField] - ForwardGeocodeUserInput _searchLocation; - - [SerializeField] - Slider _zoomSlider; - - [SerializeField] - Dropdown _stylesDropdown; - - [SerializeField] - RawImage _imageContainer; - - Map _map; - - [Geocode] - [SerializeField] - string _latLon; - - // initialize _mapboxStyles - string[] _mapboxStyles = new string[] - { - "mapbox://styles/mapbox/satellite-v9", - "mapbox://styles/mapbox/streets-v9", - "mapbox://styles/mapbox/dark-v9", - "mapbox://styles/mapbox/light-v9" - }; - - // start location - San Francisco - Vector2d _startLoc = new Vector2d(); - - int _mapstyle = 0; - - void Awake() - { - _searchLocation.OnGeocoderResponse += SearchLocation_OnGeocoderResponse; - _stylesDropdown.ClearOptions(); - _stylesDropdown.AddOptions(_mapboxStyles.ToList()); - _stylesDropdown.onValueChanged.AddListener(ToggleDropdownStyles); - _zoomSlider.onValueChanged.AddListener(AdjustZoom); - - var parsed = _latLon.Split(','); - _startLoc.x = double.Parse(parsed[0]); - _startLoc.y = double.Parse(parsed[1]); - } - - void OnDestroy() - { - if (_searchLocation != null) - { - _searchLocation.OnGeocoderResponse -= SearchLocation_OnGeocoderResponse; - } - } - - void Start() - { - _map = new Map(MapboxAccess.Instance); - _map.MapId = _mapboxStyles[_mapstyle]; - _map.Center = _startLoc; - _map.Zoom = (int)_zoomSlider.value; - _map.Subscribe(this); - _map.Update(); - } - - /// - /// New search location has become available, begin a new _map query. - /// - /// Sender. - /// E. - void SearchLocation_OnGeocoderResponse(object sender, EventArgs e) - { - _map.Center = _searchLocation.Coordinate; - _map.Update(); - } - - /// - /// Zoom was modified by the slider, begin a new _map query. - /// - /// Value. - void AdjustZoom(float value) - { - _map.Zoom = (int)_zoomSlider.value; - _map.Update(); - } - - /// - /// Style dropdown updated, begin a new _map query. - /// - /// If set to true value. - void ToggleDropdownStyles(int target) - { - _mapstyle = target; - _map.MapId = _mapboxStyles[target]; - _map.Update(); - } - - /// - /// Update the texture with new data. - /// - /// Tile. - public void OnNext(RasterTile tile) - { - if (tile.CurrentState != Tile.State.Loaded || tile.Error != null) - { - return; - } - - // Can we utility this? Should users have to know source size? - var texture = new Texture2D(256, 256); - texture.LoadImage(tile.Data); - _imageContainer.texture = texture; - } - } +namespace Mapbox.Examples.Playground { + using System.Linq; + using System; + using Mapbox.Map; + using Mapbox.Unity; + using UnityEngine; + using UnityEngine.UI; + using Mapbox.Utils; + using Mapbox.Unity.Utilities; + + public class RasterTileExample : MonoBehaviour, Mapbox.Utils.IObserver { + [SerializeField] + ForwardGeocodeUserInput _searchLocation; + + [SerializeField] + Slider _zoomSlider; + + [SerializeField] + Dropdown _stylesDropdown; + + [SerializeField] + RawImage _imageContainer; + + Map _map; + + [Geocode] + [SerializeField] + string _latLon; + + // initialize _mapboxStyles + string[] _mapboxStyles = new string[] + { + "mapbox://styles/mapbox/satellite-v9", + "mapbox://styles/mapbox/streets-v9", + "mapbox://styles/mapbox/dark-v9", + "mapbox://styles/mapbox/light-v9" + }; + + // start location - San Francisco + Vector2d _startLoc = new Vector2d(); + + int _mapstyle = 0; + + void Awake() { + _searchLocation.OnGeocoderResponse += SearchLocation_OnGeocoderResponse; + _stylesDropdown.ClearOptions(); + _stylesDropdown.AddOptions(_mapboxStyles.ToList()); + _stylesDropdown.onValueChanged.AddListener(ToggleDropdownStyles); + _zoomSlider.onValueChanged.AddListener(AdjustZoom); + + var parsed = _latLon.Split(','); + _startLoc.x = double.Parse(parsed[0]); + _startLoc.y = double.Parse(parsed[1]); + } + + void OnDestroy() { + if (_searchLocation != null) { + _searchLocation.OnGeocoderResponse -= SearchLocation_OnGeocoderResponse; + } + } + + void Start() { + _map = new Map(MapboxAccess.Instance); + _map.MapId = _mapboxStyles[_mapstyle]; + _map.Center = _startLoc; + _map.Zoom = (int)_zoomSlider.value; + _map.Subscribe(this); + _map.Update(); + } + + /// + /// New search location has become available, begin a new _map query. + /// + /// Sender. + /// E. + void SearchLocation_OnGeocoderResponse(object sender, EventArgs e) { + _map.Center = _searchLocation.Coordinate; + _map.Update(); + } + + /// + /// Zoom was modified by the slider, begin a new _map query. + /// + /// Value. + void AdjustZoom(float value) { + _map.Zoom = (int)_zoomSlider.value; + _map.Update(); + } + + /// + /// Style dropdown updated, begin a new _map query. + /// + /// If set to true value. + void ToggleDropdownStyles(int target) { + _mapstyle = target; + _map.MapId = _mapboxStyles[target]; + _map.Update(); + } + + /// + /// Update the texture with new data. + /// + /// Tile. + public void OnNext(RasterTile tile) { + if (tile.CurrentState != Tile.State.Loaded || tile.HasError) { + return; + } + + // Can we utility this? Should users have to know source size? + var texture = new Texture2D(256, 256); + texture.LoadImage(tile.Data); + _imageContainer.texture = texture; + } + } } \ No newline at end of file diff --git a/sdkproject/Assets/Mapbox/Examples/Playground/Scripts/VectorTileExample.cs b/sdkproject/Assets/Mapbox/Examples/Playground/Scripts/VectorTileExample.cs index a69241de7..786cda0a5 100644 --- a/sdkproject/Assets/Mapbox/Examples/Playground/Scripts/VectorTileExample.cs +++ b/sdkproject/Assets/Mapbox/Examples/Playground/Scripts/VectorTileExample.cs @@ -5,93 +5,82 @@ //----------------------------------------------------------------------- using Mapbox.Unity; -namespace Mapbox.Examples.Playground -{ - using System; - using UnityEngine; - using UnityEngine.UI; - using Mapbox.Map; - using Mapbox.Json; - using Mapbox.VectorTile.ExtensionMethods; - using Mapbox.Utils.JsonConverters; +namespace Mapbox.Examples.Playground { + using System; + using UnityEngine; + using UnityEngine.UI; + using Mapbox.Map; + using Mapbox.Json; + using Mapbox.VectorTile.ExtensionMethods; + using Mapbox.Utils.JsonConverters; - public class VectorTileExample : MonoBehaviour, Mapbox.Utils.IObserver - { - [SerializeField] - ForwardGeocodeUserInput _searchLocation; + public class VectorTileExample : MonoBehaviour, Mapbox.Utils.IObserver { + [SerializeField] + ForwardGeocodeUserInput _searchLocation; - [SerializeField] - Text _resultsText; + [SerializeField] + Text _resultsText; - Map _map; + Map _map; - void Awake() - { - _searchLocation.OnGeocoderResponse += SearchLocation_OnGeocoderResponse; - } + void Awake() { + _searchLocation.OnGeocoderResponse += SearchLocation_OnGeocoderResponse; + } - void OnDestroy() - { - if (_searchLocation != null) - { - _searchLocation.OnGeocoderResponse -= SearchLocation_OnGeocoderResponse; - } - } + void OnDestroy() { + if (_searchLocation != null) { + _searchLocation.OnGeocoderResponse -= SearchLocation_OnGeocoderResponse; + } + } - void Start() - { - _map = new Map(MapboxAccess.Instance); - _map.Zoom = 18; - // This marks us an an observer to map. - // We will get each tile in OnNext(VectorTile tile) as they become available. - _map.Subscribe(this); - _map.Update(); - } + void Start() { + _map = new Map(MapboxAccess.Instance); + _map.Zoom = 18; + // This marks us an an observer to map. + // We will get each tile in OnNext(VectorTile tile) as they become available. + _map.Subscribe(this); + _map.Update(); + } - /// - /// Search location was changed. - /// - /// Sender. - /// E. - void SearchLocation_OnGeocoderResponse(object sender, EventArgs e) - { - Redraw(); - } + /// + /// Search location was changed. + /// + /// Sender. + /// E. + void SearchLocation_OnGeocoderResponse(object sender, EventArgs e) { + Redraw(); + } - /// - /// Request _map to update its tile data with new coordinates. - /// - void Redraw() - { - if (!_searchLocation.HasResponse) - { - _resultsText.text = "no results"; - return; - } + /// + /// Request _map to update its tile data with new coordinates. + /// + void Redraw() { + if (!_searchLocation.HasResponse) { + _resultsText.text = "no results"; + return; + } - //zoom in to get results for consecutive searches - _map.Center = _searchLocation.Coordinate; - _map.Update(); - } + //zoom in to get results for consecutive searches + _map.Center = _searchLocation.Coordinate; + _map.Update(); + } - /// - /// Handle tile data from _map as they become available. - /// - /// Tile. - public void OnNext(VectorTile tile) - { - if (tile.CurrentState != Tile.State.Loaded || tile.Error != null) - { - return; - } + /// + /// Handle tile data from _map as they become available. + /// + /// Tile. + public void OnNext(VectorTile tile) { + if (tile.CurrentState != Tile.State.Loaded || tile.HasError) { + return; + } - var data = JsonConvert.SerializeObject( - tile.Data.ToGeoJson((ulong)tile.Id.Z, (ulong)tile.Id.X, (ulong)tile.Id.Y), - Formatting.Indented, - JsonConverters.Converters - ); - string sub = data.Length < 5000 ? data : data.Substring(0, 5000) + "\n. . . "; - _resultsText.text = sub; - } - } + var data = JsonConvert.SerializeObject( + tile.Data.ToGeoJson((ulong)tile.Id.Z, (ulong)tile.Id.X, (ulong)tile.Id.Y), + Formatting.Indented, + JsonConverters.Converters + ); + string sub = data.Length < 5000 ? data : data.Substring(0, 5000) + "\n. . . "; + _resultsText.text = sub; + } + } } \ No newline at end of file diff --git a/sdkproject/Assets/Mapbox/Examples/Voxels/Scripts/VoxelTile.cs b/sdkproject/Assets/Mapbox/Examples/Voxels/Scripts/VoxelTile.cs index 3ad580043..e3e894f49 100644 --- a/sdkproject/Assets/Mapbox/Examples/Voxels/Scripts/VoxelTile.cs +++ b/sdkproject/Assets/Mapbox/Examples/Voxels/Scripts/VoxelTile.cs @@ -1,196 +1,170 @@ -namespace Mapbox.Examples.Voxels -{ - using Mapbox.Map; - using Mapbox.Unity; - using System.Collections.Generic; - using UnityEngine; - using System.Collections; - using System.Linq; - using System; - using Mapbox.Utils; - using Mapbox.Platform; - using Mapbox.Unity.Utilities; - class VoxelTile : MonoBehaviour, Mapbox.Utils.IObserver, Mapbox.Utils.IObserver - { - [SerializeField] - ForwardGeocodeUserInput _geocodeInput; - - [SerializeField] - int _zoom = 17; - - [SerializeField] - float _elevationMultiplier = 1f; - - [SerializeField] - int _voxelDepthPadding = 1; - - [SerializeField] - int _tileWidthInVoxels; - - [SerializeField] - VoxelFetcher _voxelFetcher; - - [SerializeField] - GameObject _camera; - - [SerializeField] - int _voxelBatchCount = 100; - - [SerializeField] - string _styleUrl; - - Map _raster; - Map _elevation; - - Texture2D _rasterTexture; - Texture2D _elevationTexture; - - IFileSource _fileSource; - - List _voxels = new List(); - - List _instantiatedVoxels = new List(); - - float _tileScale; - - void Awake() - { - _geocodeInput.OnGeocoderResponse += GeocodeInput_OnGeocoderResponse; - } - - void OnDestroy() - { - if (_geocodeInput) - { - _geocodeInput.OnGeocoderResponse -= GeocodeInput_OnGeocoderResponse; - } - } - - void Start() - { - _fileSource = MapboxAccess.Instance; - - _raster = new Map(_fileSource); - _elevation = new Map(_fileSource); - - if (!string.IsNullOrEmpty(_styleUrl)) - { - _raster.MapId = _styleUrl; - } - - _elevation.Subscribe(this); - _raster.Subscribe(this); - - // Torres Del Paine - FetchWorldData(new Vector2d(-50.98306, -72.96639)); - } - - void GeocodeInput_OnGeocoderResponse(object sender, EventArgs e) - { - Cleanup(); - FetchWorldData(_geocodeInput.Coordinate); - } - - void Cleanup() - { - StopAllCoroutines(); - _rasterTexture = null; - _elevationTexture = null; - _voxels.Clear(); - foreach (var voxel in _instantiatedVoxels) - { - Destroy(voxel); - } - } - - void FetchWorldData(Vector2d coordinates) - { - _tileScale = (_tileWidthInVoxels / 256f) / Conversions.GetTileScaleInMeters((float)coordinates.x, _zoom); - var bounds = new Vector2dBounds(); - bounds.Center = coordinates; - _raster.SetVector2dBoundsZoom(bounds, _zoom); - _elevation.SetVector2dBoundsZoom(bounds, _zoom); - _raster.Update(); - _elevation.Update(); - } - - public void OnNext(RasterTile tile) - { - if (tile.CurrentState == Tile.State.Loaded && string.IsNullOrEmpty(tile.Error)) - { - _rasterTexture = new Texture2D(2, 2); - _rasterTexture.LoadImage(tile.Data); - TextureScale.Point(_rasterTexture, _tileWidthInVoxels, _tileWidthInVoxels); - - if (ShouldBuildWorld()) - { - BuildVoxelWorld(); - } - } - } - - public void OnNext(RawPngRasterTile tile) - { - if (tile.CurrentState == Tile.State.Loaded && string.IsNullOrEmpty(tile.Error)) - { - _elevationTexture = new Texture2D(2, 2); - _elevationTexture.LoadImage(tile.Data); - TextureScale.Point(_elevationTexture, _tileWidthInVoxels, _tileWidthInVoxels); - - if (ShouldBuildWorld()) - { - BuildVoxelWorld(); - } - } - } - - bool ShouldBuildWorld() - { - return _rasterTexture != null && _elevationTexture != null; - } - - void BuildVoxelWorld() - { - var baseHeight = (int)Conversions.GetRelativeHeightFromColor((_elevationTexture.GetPixel(_elevationTexture.width / 2, _elevationTexture.height / 2)), - _elevationMultiplier * _tileScale); - for (int x = 0; x < _rasterTexture.width; x++) - { - for (int z = 0; z < _rasterTexture.height; z++) - { - var height = (int)Conversions.GetRelativeHeightFromColor(_elevationTexture.GetPixel(x, z), - _elevationMultiplier * _tileScale) - baseHeight; - - var startHeight = height - _voxelDepthPadding - 1; - var color = _rasterTexture.GetPixel(x, z); - - for (int y = startHeight; y < height; y++) - { - _voxels.Add(new VoxelData() { Position = new Vector3(x, y, z), Prefab = _voxelFetcher.GetVoxelFromColor(color) }); - } - } - } - - _camera.transform.position = new Vector3(_tileWidthInVoxels * .5f, 2f, _tileWidthInVoxels * .5f); - StartCoroutine(BuildRoutine()); - } - - IEnumerator BuildRoutine() - { - var distanceOrderedVoxels = _voxels.OrderBy(x => (_camera.transform.position - x.Position).magnitude).ToList(); - - for (int i = 0; i < distanceOrderedVoxels.Count; i += _voxelBatchCount) - { - for (int j = 0; j < _voxelBatchCount; j++) - { - var index = i + j; - if (index < distanceOrderedVoxels.Count) - { - var voxel = distanceOrderedVoxels[index]; - _instantiatedVoxels.Add(Instantiate(voxel.Prefab, voxel.Position, Quaternion.identity, transform) as GameObject); - } - } - yield return null; - } - } - } +namespace Mapbox.Examples.Voxels { + using Mapbox.Map; + using Mapbox.Unity; + using System.Collections.Generic; + using UnityEngine; + using System.Collections; + using System.Linq; + using System; + using Mapbox.Utils; + using Mapbox.Platform; + using Mapbox.Unity.Utilities; + class VoxelTile : MonoBehaviour, Mapbox.Utils.IObserver, Mapbox.Utils.IObserver { + [SerializeField] + ForwardGeocodeUserInput _geocodeInput; + + [SerializeField] + int _zoom = 17; + + [SerializeField] + float _elevationMultiplier = 1f; + + [SerializeField] + int _voxelDepthPadding = 1; + + [SerializeField] + int _tileWidthInVoxels; + + [SerializeField] + VoxelFetcher _voxelFetcher; + + [SerializeField] + GameObject _camera; + + [SerializeField] + int _voxelBatchCount = 100; + + [SerializeField] + string _styleUrl; + + Map _raster; + Map _elevation; + + Texture2D _rasterTexture; + Texture2D _elevationTexture; + + IFileSource _fileSource; + + List _voxels = new List(); + + List _instantiatedVoxels = new List(); + + float _tileScale; + + void Awake() { + _geocodeInput.OnGeocoderResponse += GeocodeInput_OnGeocoderResponse; + } + + void OnDestroy() { + if (_geocodeInput) { + _geocodeInput.OnGeocoderResponse -= GeocodeInput_OnGeocoderResponse; + } + } + + void Start() { + _fileSource = MapboxAccess.Instance; + + _raster = new Map(_fileSource); + _elevation = new Map(_fileSource); + + if (!string.IsNullOrEmpty(_styleUrl)) { + _raster.MapId = _styleUrl; + } + + _elevation.Subscribe(this); + _raster.Subscribe(this); + + // Torres Del Paine + FetchWorldData(new Vector2d(-50.98306, -72.96639)); + } + + void GeocodeInput_OnGeocoderResponse(object sender, EventArgs e) { + Cleanup(); + FetchWorldData(_geocodeInput.Coordinate); + } + + void Cleanup() { + StopAllCoroutines(); + _rasterTexture = null; + _elevationTexture = null; + _voxels.Clear(); + foreach (var voxel in _instantiatedVoxels) { + Destroy(voxel); + } + } + + void FetchWorldData(Vector2d coordinates) { + _tileScale = (_tileWidthInVoxels / 256f) / Conversions.GetTileScaleInMeters((float)coordinates.x, _zoom); + var bounds = new Vector2dBounds(); + bounds.Center = coordinates; + _raster.SetVector2dBoundsZoom(bounds, _zoom); + _elevation.SetVector2dBoundsZoom(bounds, _zoom); + _raster.Update(); + _elevation.Update(); + } + + public void OnNext(RasterTile tile) { + if (tile.CurrentState == Tile.State.Loaded && !tile.HasError) { + _rasterTexture = new Texture2D(2, 2); + _rasterTexture.LoadImage(tile.Data); + TextureScale.Point(_rasterTexture, _tileWidthInVoxels, _tileWidthInVoxels); + + if (ShouldBuildWorld()) { + BuildVoxelWorld(); + } + } + } + + public void OnNext(RawPngRasterTile tile) { + if (tile.CurrentState == Tile.State.Loaded && !tile.HasError) { + _elevationTexture = new Texture2D(2, 2); + _elevationTexture.LoadImage(tile.Data); + TextureScale.Point(_elevationTexture, _tileWidthInVoxels, _tileWidthInVoxels); + + if (ShouldBuildWorld()) { + BuildVoxelWorld(); + } + } + } + + bool ShouldBuildWorld() { + return _rasterTexture != null && _elevationTexture != null; + } + + void BuildVoxelWorld() { + var baseHeight = (int)Conversions.GetRelativeHeightFromColor((_elevationTexture.GetPixel(_elevationTexture.width / 2, _elevationTexture.height / 2)), + _elevationMultiplier * _tileScale); + for (int x = 0; x < _rasterTexture.width; x++) { + for (int z = 0; z < _rasterTexture.height; z++) { + var height = (int)Conversions.GetRelativeHeightFromColor(_elevationTexture.GetPixel(x, z), + _elevationMultiplier * _tileScale) - baseHeight; + + var startHeight = height - _voxelDepthPadding - 1; + var color = _rasterTexture.GetPixel(x, z); + + for (int y = startHeight; y < height; y++) { + _voxels.Add(new VoxelData() { Position = new Vector3(x, y, z), Prefab = _voxelFetcher.GetVoxelFromColor(color) }); + } + } + } + + _camera.transform.position = new Vector3(_tileWidthInVoxels * .5f, 2f, _tileWidthInVoxels * .5f); + StartCoroutine(BuildRoutine()); + } + + IEnumerator BuildRoutine() { + var distanceOrderedVoxels = _voxels.OrderBy(x => (_camera.transform.position - x.Position).magnitude).ToList(); + + for (int i = 0; i < distanceOrderedVoxels.Count; i += _voxelBatchCount) { + for (int j = 0; j < _voxelBatchCount; j++) { + var index = i + j; + if (index < distanceOrderedVoxels.Count) { + var voxel = distanceOrderedVoxels[index]; + _instantiatedVoxels.Add(Instantiate(voxel.Prefab, voxel.Position, Quaternion.identity, transform) as GameObject); + } + } + yield return null; + } + } + } } \ No newline at end of file From 8285990afd6b8e902003dcb624b281482bf30c7e Mon Sep 17 00:00:00 2001 From: bergwerkgis Date: Tue, 9 May 2017 14:49:24 +0200 Subject: [PATCH 05/11] update to latest mapbox-sdk-cs@IAsyncRequestFactory --- dependencies/mapbox-sdk-cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies/mapbox-sdk-cs b/dependencies/mapbox-sdk-cs index 5b440ead2..da62fc6b3 160000 --- a/dependencies/mapbox-sdk-cs +++ b/dependencies/mapbox-sdk-cs @@ -1 +1 @@ -Subproject commit 5b440ead209b4a66f51f41995666119be7e57c64 +Subproject commit da62fc6b39855ca2b990d47ceb0df65bb2082828 From 6b1de5491ee7891f0e93d0feb11c788cc23511e2 Mon Sep 17 00:00:00 2001 From: bergwerkgis Date: Tue, 9 May 2017 16:42:16 +0200 Subject: [PATCH 06/11] remove dispatcher --- .../Core/Unity/Utilities/DispatcherEditor.cs | 51 -------- .../UnityToolbagDispatcher.meta | 9 -- .../UnityToolbagDispatcher/Dispatcher.cs | 114 ------------------ .../UnityToolbagDispatcher/Dispatcher.cs.meta | 12 -- 4 files changed, 186 deletions(-) delete mode 100644 sdkproject/Assets/Mapbox/Core/Unity/Utilities/DispatcherEditor.cs delete mode 100644 sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher.meta delete mode 100644 sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs delete mode 100644 sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs.meta diff --git a/sdkproject/Assets/Mapbox/Core/Unity/Utilities/DispatcherEditor.cs b/sdkproject/Assets/Mapbox/Core/Unity/Utilities/DispatcherEditor.cs deleted file mode 100644 index 55f57bc3e..000000000 --- a/sdkproject/Assets/Mapbox/Core/Unity/Utilities/DispatcherEditor.cs +++ /dev/null @@ -1,51 +0,0 @@ -namespace Mapbox.Unity { - - - using System; - using System.Collections.Generic; - using System.Threading; - using UnityEditor; - - - [InitializeOnLoad] - public static class DispatcherEditor { - - - static DispatcherEditor() { - _mainThread = Thread.CurrentThread; - EditorApplication.update += Update; - } - - - private static object _lock = new object(); - private static readonly Queue _actions = new Queue(); - private static Thread _mainThread; - - - private static bool isMainThread { - get { return Thread.CurrentThread == _mainThread; } - } - - - public static void Update() { - lock (_lock) { - while (_actions.Count > 0) { - _actions.Dequeue()(); - } - } - } - - - public static void InvokeAsync(Action action) { - if (isMainThread) { - action(); - }else { - lock (_lock) { - _actions.Enqueue(action); - } - } - } - - - } -} \ No newline at end of file diff --git a/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher.meta b/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher.meta deleted file mode 100644 index e898ff19b..000000000 --- a/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher.meta +++ /dev/null @@ -1,9 +0,0 @@ -fileFormatVersion: 2 -guid: 9b8e3a59ff0dc4000a4fda4d9fa6931d -folderAsset: yes -timeCreated: 1493311191 -licenseType: Pro -DefaultImporter: - userData: - assetBundleName: - assetBundleVariant: diff --git a/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs b/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs deleted file mode 100644 index c76ef5f1c..000000000 --- a/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs +++ /dev/null @@ -1,114 +0,0 @@ -using UnityEngine; -using System; -using System.Collections.Generic; -using System.Threading; - -namespace UnityToolbag { - /// - /// A system for dispatching code to execute on the main thread. - /// - [AddComponentMenu("UnityToolbag/Dispatcher")] - public class Dispatcher : MonoBehaviour { - private static Dispatcher _instance; - - // We can't use the behaviour reference from other threads, so we use a separate bool - // to track the instance so we can use that on the other threads. - // edit by BergWerkGIS: make public to see if dispatcher is attached - public static bool _instanceExists; - - private static Thread _mainThread; - private static object _lockObject = new object(); - private static readonly Queue _actions = new Queue(); - - /// - /// Gets a value indicating whether or not the current thread is the game's main thread. - /// - public static bool isMainThread { - get { - return Thread.CurrentThread == _mainThread; - } - } - - /// - /// Queues an action to be invoked on the main game thread. - /// - /// The action to be queued. - public static void InvokeAsync(Action action) { - - if (!_instanceExists) { - Debug.LogError("No Dispatcher exists in the scene. Actions will not be invoked!"); - return; - } - - if (isMainThread) { - // Don't bother queuing work on the main thread; just execute it. - action(); - } else { - lock (_lockObject) { - _actions.Enqueue(action); - } - } - } - - /// - /// Queues an action to be invoked on the main game thread and blocks the - /// current thread until the action has been executed. - /// - /// The action to be queued. - public static void Invoke(Action action) { - - if (!_instanceExists) { - Debug.LogError("No Dispatcher exists in the scene. Actions will not be invoked!"); - return; - } - - - bool hasRun = false; - - InvokeAsync(() => { - action(); - hasRun = true; - }); - - // Lock until the action has run - while (!hasRun) { -#if !NETFX_CORE - Thread.Sleep(5); -#else - System.Threading.Tasks.Task.Delay(5).Wait(); -#endif - } - } - - void Awake() { - if (_instance) { - DestroyImmediate(this); - } else { - _instance = this; - _instanceExists = true; - _mainThread = Thread.CurrentThread; - } - } - - void OnDestroy() { - if (_instance == this) { - _instance = null; - _instanceExists = false; - } - } - - //int cnt = 0; - void Update() { - //cnt++; - //if (cnt < 100) { return; } - //cnt = 0; - ////if (_actions.Count > 0) UnityEngine.Debug.Log("-------------------- update -----------------" + DateTime.Now.Ticks); - lock (_lockObject) { - while (_actions.Count > 0) { - //UnityEngine.Debug.Log("QUEUE: " + _actions.Count + " " + DateTime.Now.Ticks); - _actions.Dequeue()(); - } - } - } - } -} diff --git a/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs.meta b/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs.meta deleted file mode 100644 index 99c6c3dc6..000000000 --- a/sdkproject/Assets/ThirdPartyAssets/UnityToolbagDispatcher/Dispatcher.cs.meta +++ /dev/null @@ -1,12 +0,0 @@ -fileFormatVersion: 2 -guid: dd2511162df91294fa0c4ea0b0d740ed -timeCreated: 1493142390 -licenseType: Pro -MonoImporter: - serializedVersion: 2 - defaultReferences: [] - executionOrder: 0 - icon: {instanceID: 0} - userData: - assetBundleName: - assetBundleVariant: From 2ea662947ae3db7b0b53be1a515f86f9d162a3c9 Mon Sep 17 00:00:00 2001 From: bergwerkgis Date: Tue, 9 May 2017 16:42:55 +0200 Subject: [PATCH 07/11] use Response.FromWebResponse --- .../Assets/Mapbox/Core/Unity/Utilities/HTTPRequest.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/sdkproject/Assets/Mapbox/Core/Unity/Utilities/HTTPRequest.cs b/sdkproject/Assets/Mapbox/Core/Unity/Utilities/HTTPRequest.cs index bead61487..44c1954be 100644 --- a/sdkproject/Assets/Mapbox/Core/Unity/Utilities/HTTPRequest.cs +++ b/sdkproject/Assets/Mapbox/Core/Unity/Utilities/HTTPRequest.cs @@ -49,12 +49,8 @@ private IEnumerator DoRequest() { while (!_request.isDone) { yield return 0; } - var response = new Response(); - // TODO: evalute _request more thoroughly and set properties of Response accordingly: status code, headers, etc. - if (!string.IsNullOrEmpty(_request.error)) { - response.AddException(new Exception(_request.error)); - } - response.Data = this._request.downloadHandler.data; + + var response = Response.FromWebResponse(this, _request, null); _callback(response); _request.Dispose(); From f7c596ca4338e9bbbb327aa590675114b26d1663 Mon Sep 17 00:00:00 2001 From: bergwerkgis Date: Tue, 9 May 2017 16:43:44 +0200 Subject: [PATCH 08/11] update to latest mapbox-sdk-cs@IAsyncRequestFactory --- dependencies/mapbox-sdk-cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies/mapbox-sdk-cs b/dependencies/mapbox-sdk-cs index da62fc6b3..3a9810765 160000 --- a/dependencies/mapbox-sdk-cs +++ b/dependencies/mapbox-sdk-cs @@ -1 +1 @@ -Subproject commit da62fc6b39855ca2b990d47ceb0df65bb2082828 +Subproject commit 3a981076520edcbfa34d3a9d1caf7e52e5e9bfaf From fea412d21f5b827a9d3344e330bb689b1a34ff79 Mon Sep 17 00:00:00 2001 From: bergwerkgis Date: Tue, 9 May 2017 17:09:33 +0200 Subject: [PATCH 09/11] update to latest mapbox-sdk-cs@IAsyncRequestFactory --- dependencies/mapbox-sdk-cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies/mapbox-sdk-cs b/dependencies/mapbox-sdk-cs index 3a9810765..8c29eade5 160000 --- a/dependencies/mapbox-sdk-cs +++ b/dependencies/mapbox-sdk-cs @@ -1 +1 @@ -Subproject commit 3a981076520edcbfa34d3a9d1caf7e52e5e9bfaf +Subproject commit 8c29eade5f20b77bf76f6abece242a2852466973 From 790503d2d5003a040a13117f226a526629db9e89 Mon Sep 17 00:00:00 2001 From: David Rhodes Date: Tue, 9 May 2017 13:52:35 -0600 Subject: [PATCH 10/11] Removing server certificate validation stuff and letting UnityWebRequest handle this. --- .../Assets/Mapbox/Core/Unity/MapboxAccess.cs | 37 ++----------------- 1 file changed, 3 insertions(+), 34 deletions(-) diff --git a/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs b/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs index 1cb5e94cd..de664a471 100644 --- a/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs +++ b/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs @@ -7,10 +7,6 @@ namespace Mapbox.Unity { using Mapbox.Directions; using Mapbox.Platform; using Mapbox.Unity.Utilities; -#if !NETFX_CORE - using System.Security.Cryptography.X509Certificates; -#endif - using System.Net.Security; /// /// Object for retrieving an API token and making http requests. @@ -33,9 +29,6 @@ public static MapboxAccess Instance { } MapboxAccess() { -#if !NETFX_CORE - ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback; -#endif ValidateMapboxAccessFile(); LoadAccessToken(); } @@ -86,16 +79,15 @@ private void LoadAccessToken() { private string LoadMapboxAccess() { var request = new WWW(_accessPath); + // Implement a custom timeout - just in case var timeout = Time.realtimeSinceStartup + 5f; while (!request.isDone) { if (Time.realtimeSinceStartup > timeout) { throw new InvalidTokenException("Could not load access token!"); } -#if NETFX_CORE - System.Threading.Tasks.Task.Delay(10).Wait(); -#else - System.Threading.Thread.Sleep(10); +#if !NETFX_CORE + System.Threading.Thread.Sleep(10); #endif } return request.text; @@ -154,28 +146,5 @@ public Directions Directions { return _directions; } } - - -#if !NETFX_CORE - public bool MyRemoteCertificateValidationCallback(System.Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { - bool isOk = true; - // If there are errors in the certificate chain, look at each error to determine the cause. - if (sslPolicyErrors != SslPolicyErrors.None) { - for (int i = 0; i < chain.ChainStatus.Length; i++) { - if (chain.ChainStatus[i].Status != X509ChainStatusFlags.RevocationStatusUnknown) { - chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain; - chain.ChainPolicy.RevocationMode = X509RevocationMode.Online; - chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0); - chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags; - bool chainIsValid = chain.Build((X509Certificate2)certificate); - if (!chainIsValid) { - isOk = false; - } - } - } - } - return isOk; - } -#endif } } From 21f3cd76614cd6ba53fe68b638e9e848553928ce Mon Sep 17 00:00:00 2001 From: David Rhodes Date: Tue, 9 May 2017 13:56:02 -0600 Subject: [PATCH 11/11] Pointing to master --- dependencies/mapbox-sdk-cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dependencies/mapbox-sdk-cs b/dependencies/mapbox-sdk-cs index 8c29eade5..a41e0a5d1 160000 --- a/dependencies/mapbox-sdk-cs +++ b/dependencies/mapbox-sdk-cs @@ -1 +1 @@ -Subproject commit 8c29eade5f20b77bf76f6abece242a2852466973 +Subproject commit a41e0a5d16030d022d1d407c535854ac47f84747