diff --git a/dependencies/mapbox-sdk-cs b/dependencies/mapbox-sdk-cs
index 4c004a746..a41e0a5d1 160000
--- a/dependencies/mapbox-sdk-cs
+++ b/dependencies/mapbox-sdk-cs
@@ -1 +1 @@
-Subproject commit 4c004a746e4c82770d99f59325209995d37339f4
+Subproject commit a41e0a5d16030d022d1d407c535854ac47f84747
diff --git a/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs b/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs
index 526762788..de664a471 100644
--- a/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs
+++ b/sdkproject/Assets/Mapbox/Core/Unity/MapboxAccess.cs
@@ -1,181 +1,150 @@
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;
-#if !NETFX_CORE
- using System.Security.Cryptography.X509Certificates;
-#endif
- 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 {
-
- private readonly string _accessPath = Path.Combine(Application.streamingAssetsPath, Constants.Path.TOKEN_FILE);
-
- static MapboxAccess _instance = new MapboxAccess();
-
-
- ///
- /// The singleton instance.
- ///
- public static MapboxAccess Instance {
- get {
- return _instance;
- }
- }
-
- MapboxAccess() {
-#if !NETFX_CORE
- 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() {
+ using UnityEngine;
+ using System.IO;
+ using System;
+ using System.Net;
+ using Mapbox.Geocoding;
+ using Mapbox.Directions;
+ using Mapbox.Platform;
+ using Mapbox.Unity.Utilities;
+
+ ///
+ /// 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);
+
+ static MapboxAccess _instance = new MapboxAccess();
+
+
+ ///
+ /// The singleton instance.
+ ///
+ public static MapboxAccess Instance {
+ get {
+ return _instance;
+ }
+ }
+
+ MapboxAccess() {
+ 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() {
-
- 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);
-#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;
- }
- }
+ }
+
+ ///
+ /// 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!");
+ }
#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;
- }
+ 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, 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;
+ }
+ }
+ }
}
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..44c1954be 100644
--- a/sdkproject/Assets/Mapbox/Core/Unity/Utilities/HTTPRequest.cs
+++ b/sdkproject/Assets/Mapbox/Core/Unity/Utilities/HTTPRequest.cs
@@ -4,58 +4,58 @@
//
//-----------------------------------------------------------------------
-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 = Response.FromWebResponse(this, _request, null);
+
+ _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