Merge branch 'master' into release-android-v0.1.0
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -29,6 +29,7 @@
|
||||
/src/shader/shaders_gl.cpp
|
||||
/src/shader/shaders_gles2.cpp
|
||||
/bin/style.bin.js
|
||||
/node_modules
|
||||
*~
|
||||
|
||||
/ios/benchmark/assets/tiles/mapbox.mapbox-streets-v6/
|
||||
|
||||
2
.mason
2
.mason
Submodule .mason updated: d8597d9445...36dc9282d7
14
.travis.yml
14
.travis.yml
@@ -25,10 +25,10 @@ matrix:
|
||||
sources: [ 'ubuntu-toolchain-r-test', 'llvm-toolchain-precise-3.5' ]
|
||||
packages: [ 'gdb', 'clang-3.5', 'libstdc++-4.9-dev', 'libstdc++6', 'libllvm3.4', 'xutils-dev', 'libxxf86vm-dev', 'x11proto-xf86vidmode-dev', 'mesa-utils' ]
|
||||
- os: osx
|
||||
osx_image: xcode6.4
|
||||
osx_image: xcode7
|
||||
env: FLAVOR=osx BUILDTYPE=Debug
|
||||
- os: osx
|
||||
osx_image: xcode6.4
|
||||
osx_image: xcode7
|
||||
env: FLAVOR=ios BUILDTYPE=Release
|
||||
- os: linux
|
||||
env: FLAVOR=android ANDROID_ABI=arm-v7 BUILDTYPE=Release
|
||||
@@ -59,7 +59,7 @@ matrix:
|
||||
apt:
|
||||
packages: [ 'lib32stdc++6' ]
|
||||
- os: linux
|
||||
env: FLAVOR=node CXX=clang++-3.5 BUILDTYPE=Release NODE_VERSION=iojs-v2
|
||||
env: FLAVOR=node CXX=clang++-3.5 BUILDTYPE=Release NODE_VERSION=iojs-v3
|
||||
addons:
|
||||
apt:
|
||||
sources: [ 'ubuntu-toolchain-r-test', 'llvm-toolchain-precise-3.5' ]
|
||||
@@ -77,15 +77,15 @@ matrix:
|
||||
sources: [ 'ubuntu-toolchain-r-test', 'llvm-toolchain-precise-3.5' ]
|
||||
packages: [ 'gdb', 'clang-3.5', 'libstdc++-4.9-dev', 'libstdc++6', 'libllvm3.4', 'xutils-dev', 'libxxf86vm-dev', 'x11proto-xf86vidmode-dev', 'mesa-utils' ]
|
||||
- os: osx
|
||||
osx_image: xcode6.4
|
||||
osx_image: xcode7
|
||||
compiler: clang
|
||||
env: FLAVOR=node NODE_VERSION=iojs-v2
|
||||
env: FLAVOR=node NODE_VERSION=iojs-v3
|
||||
- os: osx
|
||||
osx_image: xcode6.4
|
||||
osx_image: xcode7
|
||||
compiler: clang
|
||||
env: FLAVOR=node NODE_VERSION=0.12
|
||||
- os: osx
|
||||
osx_image: xcode6.4
|
||||
osx_image: xcode7
|
||||
compiler: clang
|
||||
env: FLAVOR=node NODE_VERSION=0.10
|
||||
|
||||
|
||||
27
CHANGELOG.md
27
CHANGELOG.md
@@ -1,5 +1,32 @@
|
||||
# Changelog
|
||||
|
||||
## iOS 2.1.2
|
||||
|
||||
- Built with Xcode 6.4 to not yet trigger Bitcode compatibility until Xcode 7 stabilizes. ([#2332](https://github.com/mapbox/mapbox-gl-native/issues/2332))
|
||||
|
||||
## iOS 2.1.1
|
||||
|
||||
- Fixes for Xcode 7 and Bitcode. ([#2238](https://github.com/mapbox/mapbox-gl-native/pull/2238))
|
||||
|
||||
## iOS 2.1.0
|
||||
|
||||
- A two-finger vertical swipe now tilts the map into perspective mode. ([#2116](https://github.com/mapbox/mapbox-gl-native/pull/2116))
|
||||
- A new `MGLMapCamera` API allows you to transition multiple viewpoint properties, including rotation and pitch, simultaneously with an optional custom duration and timing function. ([#2193](https://github.com/mapbox/mapbox-gl-native/pull/2193))
|
||||
- A new user tracking mode, `MGLUserTrackingModeFollowWithCourse`, has been added for indicating the current direction of travel. ([#2068](https://github.com/mapbox/mapbox-gl-native/pull/2068))
|
||||
- Version 8 (`v8`) of the [Mapbox GL style spec](https://www.mapbox.com/mapbox-gl-style-spec/) is now required. If you are using a custom `v7` style, it needs to be upgraded using [this migrator script](https://github.com/mapbox/mapbox-gl-style-spec/blob/mb-pages/migrations/v7.js). ([#2052](https://github.com/mapbox/mapbox-gl-native/pull/2052))
|
||||
- Applications built with Mapbox GL no longer crash when Location Services launches them in background mode. ([#1821](https://github.com/mapbox/mapbox-gl-native/pull/1821), [#1869](https://github.com/mapbox/mapbox-gl-native/pull/1869))
|
||||
- Fixed a crash when adding annotations to an `MGLMapView` inside `-viewDidLoad`. ([#1874](https://github.com/mapbox/mapbox-gl-native/pull/1874))
|
||||
- The user location annotation view now indicates the location reading’s accuracy and the device’s heading. ([#2010](https://github.com/mapbox/mapbox-gl-native/pull/2010))
|
||||
- Eliminated linker warnings and errors when building against the iOS 9.0 SDK in Xcode 7. ([#1962](https://github.com/mapbox/mapbox-gl-native/pull/1962))
|
||||
- Worked around a bug in the iOS 9.0 SDK that caused a crash on launch. ([#1958](https://github.com/mapbox/mapbox-gl-native/pull/1958))
|
||||
- User location tracking no longer sends `MGLMapView` into an invalid region on iOS 9. ([#1925](https://github.com/mapbox/mapbox-gl-native/pull/1925))
|
||||
- Eliminated console spew in the iOS demo application that was related to Mapbox Metrics HTTP requests. ([#1937](https://github.com/mapbox/mapbox-gl-native/issues/1937))
|
||||
- Implemented `-[MGLMapView showAnnotations:animated:]`. ([#2050](https://github.com/mapbox/mapbox-gl-native/pull/2050))
|
||||
- Fixed a crash adding a shape annotation with zero points. ([#2098](https://github.com/mapbox/mapbox-gl-native/pull/2098))
|
||||
- Debug mode now displays information useful for debugging the label collision algorithm. ([#1808](https://github.com/mapbox/mapbox-gl-native/pull/1808))
|
||||
- Minor style updates. ([#1910](https://github.com/mapbox/mapbox-gl-native/pull/1910))
|
||||
- The CocoaPods pod now contains a `README.md` file. ([#1886](https://github.com/mapbox/mapbox-gl-native/pull/1886))
|
||||
|
||||
## iOS 2.0.0
|
||||
|
||||
Repackaging 2.0.0-pre.1 as it contained no issues.
|
||||
|
||||
64
INSTALL.md
64
INSTALL.md
@@ -1,6 +1,6 @@
|
||||
# Install
|
||||
|
||||
This document describes the process for setting up Mapbox GL for development _on the framework itself_.
|
||||
This document describes the process for setting up Mapbox GL for development _on the framework itself_.
|
||||
|
||||
# Depends
|
||||
|
||||
@@ -29,7 +29,7 @@ Be sure to pull down all submodules first:
|
||||
|
||||
## OS X
|
||||
|
||||
This process gives you either a native OS X windowed app or a Linux desktop app with a map view for development purposes, built on an OS X host system.
|
||||
This process gives you either a native OS X windowed app or a Linux desktop app with a map view for development purposes, built on an OS X host system.
|
||||
|
||||
### Build
|
||||
|
||||
@@ -65,9 +65,9 @@ OS X 10.9+
|
||||
|
||||
## iOS (Test App)
|
||||
|
||||
This process gives you a native iOS app for simulator or device which compiles the source to GL within it for fastest turnaround time during development. Normal, production use of the library is via a precompiled binary linked into the app target.
|
||||
This process gives you a native iOS app for simulator or device which compiles the source to GL within it for fastest turnaround time during development. Normal, production use of the library is via a precompiled binary linked into the app target.
|
||||
|
||||
Developing for iOS implies an OS X host system.
|
||||
Developing for iOS implies an OS X host system.
|
||||
|
||||
### Build
|
||||
|
||||
@@ -85,13 +85,13 @@ You can run `make itest` to run the included integration tests. Requires `gem in
|
||||
- Double-tap to zoom in one level
|
||||
- Two-finger single-tap to zoom out one level
|
||||
- Double-tap, long-pressing the second, then pan up and down to "quick zoom" (iPhone only, meant for one-handed use)
|
||||
- Use the debug menu to add test annotations, reset position, and toggle debug info.
|
||||
- Use the debug menu to add test annotations, reset position, and toggle debug info.
|
||||
|
||||
## iOS (Your App)
|
||||
|
||||
**If you want a production version of this project, use [Mapbox Mobile](http://mapbox.com/mobile).**
|
||||
**If you want a production version of this project, use [Mapbox Mobile](http://mapbox.com/mobile).**
|
||||
|
||||
This section is for people contributing to Mapbox GL directly in the context of their own app.
|
||||
This section is for people contributing to Mapbox GL directly in the context of their own app.
|
||||
|
||||
### Build
|
||||
|
||||
@@ -103,44 +103,44 @@ This section is for people contributing to Mapbox GL directly in the context of
|
||||
cp appledoc /usr/local/bin
|
||||
cp -Rf Templates/ ~/.appledoc
|
||||
```
|
||||
|
||||
|
||||
1. Run `make ipackage`. The packaging script will produce the statically-linked `libMapbox.a`, `Mapbox.bundle` for resources, a `Headers` folder, and a `Docs` folder with HTML API documentation.
|
||||
|
||||
### Test
|
||||
|
||||
In the context of your own app, you can now either:
|
||||
In the context of your own app, you can now either:
|
||||
|
||||
#### CocoaPods
|
||||
|
||||
Currently, until [#1437](https://github.com/mapbox/mapbox-gl-native/issues/1437) is completed, to install a _development version_ of Mapbox GL using CocoaPods you will need to build it from source manually per above.
|
||||
Currently, until [#1437](https://github.com/mapbox/mapbox-gl-native/issues/1437) is completed, to install a _development version_ of Mapbox GL using CocoaPods you will need to build it from source manually per above.
|
||||
|
||||
1. Zip up the build product.
|
||||
1. Zip up the build product.
|
||||
|
||||
cd build/ios/pkg/static
|
||||
ZIP=mapbox-ios-sdk.zip
|
||||
rm -f ../${ZIP}
|
||||
zip -r ../${ZIP} *
|
||||
|
||||
1. Modify a custom `Mapbox-iOS-SDK.podspec` to download this zip file.
|
||||
1. Modify a custom `Mapbox-iOS-SDK.podspec` to download this zip file.
|
||||
|
||||
{...}
|
||||
|
||||
|
||||
m.source = {
|
||||
:http => "http://{...}/mapbox-ios-sdk.zip",
|
||||
:flatten => true
|
||||
}
|
||||
|
||||
|
||||
{...}
|
||||
|
||||
1. Update your app's `Podfile` to point to the `Mapbox-iOS-SDK.podspec`.
|
||||
1. Update your app's `Podfile` to point to the `Mapbox-iOS-SDK.podspec`.
|
||||
|
||||
pod 'Mapbox-iOS-SDK', :podspec => 'http://{...}/Mapbox-iOS-SDK.podspec'
|
||||
|
||||
1. Run `pod update` to grab the newly-built library.
|
||||
1. Run `pod update` to grab the newly-built library.
|
||||
|
||||
#### Binary
|
||||
|
||||
1. Built from source manually per above.
|
||||
1. Built from source manually per above.
|
||||
|
||||
1. Copy the contents of `build/ios/pkg/static` into your project. It should happen automatically, but ensure that:
|
||||
|
||||
@@ -173,7 +173,7 @@ iOS: 7.0+
|
||||
|
||||
We are using Ubuntu for development. While the software should work on other distributions as well, we are not providing explicit build instructions here.
|
||||
|
||||
This process gives you a Linux desktop app built on a Linux host system.
|
||||
This process gives you a Linux desktop app built on a Linux host system.
|
||||
|
||||
### Build
|
||||
|
||||
@@ -239,19 +239,19 @@ Install Oracle JDK 7 (requires license agreement) from http://www.oracle.com/tec
|
||||
|
||||
export JAVA_HOME="/dir/to/jdk1.7.0_71"
|
||||
|
||||
Install the [Android NDK Revision 10e](https://developer.android.com/tools/sdk/ndk/index.html).
|
||||
|
||||
export ANDROID_NDK_PATH="/dir/to/android-ndk-r10e"
|
||||
|
||||
Install the Android SDK. We recommend doing this by way of [Android Studio](https://developer.android.com/sdk/installing/studio.html).
|
||||
|
||||
export ANDROID_HOME="/dir/to/android-sdk-linux"
|
||||
|
||||
In the Android SDK Manager also select and install "Android Support Repository" and "Android Support Library" from "Extras":
|
||||
|
||||

|
||||
|
||||
Run:
|
||||
|
||||
make android
|
||||
|
||||
You can then open `android/java` in Android Studio via "Import Non-Android Studio Project".
|
||||
You can then open `android/java` in Android Studio via "Import project (Eclipse ADT, Gradle, etc.)".
|
||||
|
||||
### Build (OS X Host)
|
||||
|
||||
@@ -259,17 +259,19 @@ Install Oracle JDK 7+:
|
||||
|
||||
brew cask install java
|
||||
|
||||
Install the [Android NDK Revision 10e](https://developer.android.com/tools/sdk/ndk/index.html) for 64-bit OS X:
|
||||
Install the Android SDK:
|
||||
|
||||
brew install android-ndk
|
||||
brew install android-sdk
|
||||
|
||||
This will also install the dependency `android-sdk`.
|
||||
|
||||
Install [Android Studio](https://developer.android.com/sdk/installing/studio.html):
|
||||
Install Android Studio:
|
||||
|
||||
brew cask install android-studio
|
||||
android
|
||||
|
||||
In the Android SDK Manager also select and install "Android Support Repository" and "Android Support Library" from "Extras":
|
||||
|
||||

|
||||
|
||||
By default, the SDK will be installed to `/usr/local/opt/android-sdk`. If you open Android Studio at this point, you may get an error message telling you that it can't find a JVM, it's because you installed a custom Java VM from Oracle. Follow [these instructions](http://tools.android.com/recent/androidstudio1rc3_releasecandidate3released) to start Android Studio. You'll wind up setting these environment variables in your .bash_profile or similar:
|
||||
|
||||
echo "export ANDROID_HOME=`brew --prefix android-sdk`" >> .bash_profile
|
||||
@@ -283,7 +285,7 @@ Run:
|
||||
make android
|
||||
open -a Android\ Studio
|
||||
|
||||
You can then open `android/java` in Android Studio via "import project (Eclipse ADT, Gradle, etc.)".
|
||||
You can then open `android/java` in Android Studio via "Import project (Eclipse ADT, Gradle, etc.)".
|
||||
|
||||
### Setting up Android emulator
|
||||
|
||||
@@ -291,7 +293,7 @@ If you want to run the test app in the emulator, we recommend the x86 build beca
|
||||
|
||||
First ensure you have an `MAPBOX_ACCESS_TOKEN` environment variable set, as described below. Then, create an x86 build:
|
||||
|
||||
ANDROID_ABI=x86 make android
|
||||
make android-lib-x86
|
||||
|
||||
In Android Studio, create an x86 AVD (Android Virtual Device):
|
||||
|
||||
@@ -317,7 +319,7 @@ If your device does not show up, you have not set it up properly. Double check
|
||||
|
||||
### Distribution
|
||||
|
||||
Use the `Makefile` target `make apackage` in order to build JNI libraries for all supported ABI's for eventual distribution of the whole package.
|
||||
Use the `Makefile` target `make apackage` in order to build JNI libraries for all supported ABI's for eventual distribution of the whole package.
|
||||
|
||||
### Target
|
||||
|
||||
|
||||
4
Makefile
4
Makefile
@@ -130,8 +130,8 @@ clean: clear_sqlite_cache clear_xcode_cache
|
||||
-rm -rf ./ios/build
|
||||
-rm -rf ./test/build
|
||||
-rm -rf ./config/*.gypi
|
||||
-rm -rf ./android/java/build ./android/java/MapboxGLAndroidSDKTestApp/build ./android/java/MapboxGLAndroidSDKTestApp/build
|
||||
-rm -rf ./android/java/MapboxGLAndroidSDK/src/main/jniLibs ./android/java/MapboxGLAndroidSDK/src/main/assets
|
||||
-rm -rf ./android/java/build ./android/java/MapboxGLAndroidSDK/build ./android/java/MapboxGLAndroidSDKTestApp/build
|
||||
-rm -rf ./android/java/MapboxGLAndroidSDK/src/main/jniLibs ./android/java/MapboxGLAndroidSDK/src/main/obj.target ./android/java/MapboxGLAndroidSDK/src/main/assets
|
||||
-rm -f ./android/test/features.zip
|
||||
|
||||
distclean: clean
|
||||
|
||||
@@ -9,7 +9,7 @@ An OpenGL ES-based renderer for [Mapbox Vector Tiles](https://www.mapbox.com/blo
|
||||
If you want to use products _based on_ Mapbox GL, check out:
|
||||
|
||||
- [Mapbox Mobile](http://mapbox.com/mobile) — iOS and Android native development libraries for vector maps in apps
|
||||
- [`react-native-mapbox-gl`](https://github.com/mapbox/react-native-mapbox-gl`) — React Native library for vector maps in apps
|
||||
- [`react-native-mapbox-gl`](https://github.com/mapbox/react-native-mapbox-gl) — React Native library for vector maps in apps
|
||||
- [`qmapboxgl`](https://github.com/tmpsantos/qmapboxgl) — Qt library for vector map rendering
|
||||
|
||||
--
|
||||
|
||||
@@ -470,11 +470,11 @@ void JNICALL nativeUpdate(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) {
|
||||
nativeMapView->getMap().update(mbgl::Update::Repaint);
|
||||
}
|
||||
|
||||
void JNICALL nativeOnInvalidate(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) {
|
||||
mbgl::Log::Debug(mbgl::Event::JNI, "nativeOnInvalidate");
|
||||
void JNICALL nativeRenderSync(JNIEnv *env, jobject obj, jlong nativeMapViewPtr) {
|
||||
mbgl::Log::Debug(mbgl::Event::JNI, "nativeRenderSync");
|
||||
assert(nativeMapViewPtr != 0);
|
||||
NativeMapView *nativeMapView = reinterpret_cast<NativeMapView *>(nativeMapViewPtr);
|
||||
nativeMapView->onInvalidate();
|
||||
nativeMapView->renderSync();
|
||||
}
|
||||
|
||||
void JNICALL nativeViewResize(JNIEnv *env, jobject obj, jlong nativeMapViewPtr, jint width, jint height) {
|
||||
@@ -1625,7 +1625,7 @@ extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
|
||||
{"nativePause", "(J)V", reinterpret_cast<void *>(&nativePause)},
|
||||
{"nativeResume", "(J)V", reinterpret_cast<void *>(&nativeResume)},
|
||||
{"nativeUpdate", "(J)V", reinterpret_cast<void *>(&nativeUpdate)},
|
||||
{"nativeOnInvalidate", "(J)V", reinterpret_cast<void *>(&nativeOnInvalidate)},
|
||||
{"nativeRenderSync", "(J)V", reinterpret_cast<void *>(&nativeRenderSync)},
|
||||
{"nativeViewResize", "(JII)V",
|
||||
reinterpret_cast<void *>(static_cast<void JNICALL (
|
||||
*)(JNIEnv *, jobject, jlong, jint, jint)>(&nativeViewResize))},
|
||||
|
||||
@@ -78,6 +78,16 @@ NativeMapView::NativeMapView(JNIEnv *env, jobject obj_, float pixelRatio_, int a
|
||||
fileSource = std::make_unique<mbgl::DefaultFileSource>(fileCache.get());
|
||||
map = std::make_unique<mbgl::Map>(*this, *fileSource, MapMode::Continuous);
|
||||
|
||||
float zoomFactor = map->getMaxZoom() - map->getMinZoom() + 1;
|
||||
float cpuFactor = availableProcessors;
|
||||
float memoryFactor = static_cast<float>(totalMemory) / 1000.0f / 1000.0f / 1000.0f;
|
||||
float sizeFactor = (static_cast<float>(map->getWidth()) / mbgl::util::tileSize) *
|
||||
(static_cast<float>(map->getHeight()) / mbgl::util::tileSize);
|
||||
|
||||
size_t cacheSize = zoomFactor * cpuFactor * memoryFactor * sizeFactor * 0.5f;
|
||||
|
||||
map->setSourceTileCacheSize(cacheSize);
|
||||
|
||||
map->pause();
|
||||
}
|
||||
|
||||
@@ -148,8 +158,6 @@ void NativeMapView::deactivate() {
|
||||
void NativeMapView::invalidate() {
|
||||
mbgl::Log::Debug(mbgl::Event::Android, "NativeMapView::invalidate()");
|
||||
|
||||
clean.clear();
|
||||
|
||||
assert(vm != nullptr);
|
||||
assert(obj != nullptr);
|
||||
|
||||
@@ -169,7 +177,7 @@ void NativeMapView::beforeRender() {
|
||||
}
|
||||
|
||||
void NativeMapView::afterRender() {
|
||||
mbgl::Log::Debug(mbgl::Event::Android, "NativeMapView::swap");
|
||||
mbgl::Log::Debug(mbgl::Event::Android, "NativeMapView::afterRender");
|
||||
|
||||
if ((display != EGL_NO_DISPLAY) && (surface != EGL_NO_SURFACE)) {
|
||||
if (!eglSwapBuffers(display, surface)) {
|
||||
@@ -701,28 +709,15 @@ void NativeMapView::updateFps() {
|
||||
detach_jni_thread(vm, &env, detach);
|
||||
}
|
||||
|
||||
void NativeMapView::onInvalidate() {
|
||||
mbgl::Log::Debug(mbgl::Event::Android, "NativeMapView::onInvalidate()");
|
||||
void NativeMapView::renderSync() {
|
||||
mbgl::Log::Debug(mbgl::Event::Android, "NativeMapView::renderSync()");
|
||||
|
||||
if (map->isPaused()) {
|
||||
mbgl::Log::Debug(mbgl::Event::Android, "Not rendering as map is paused");
|
||||
return;
|
||||
}
|
||||
|
||||
const bool dirty = !clean.test_and_set();
|
||||
if (dirty) {
|
||||
float zoomFactor = map->getMaxZoom() - map->getMinZoom() + 1;
|
||||
float cpuFactor = availableProcessors;
|
||||
float memoryFactor = static_cast<float>(totalMemory) / 1000.0f / 1000.0f / 1000.0f;
|
||||
float sizeFactor = (static_cast<float>(map->getWidth()) / mbgl::util::tileSize) *
|
||||
(static_cast<float>(map->getHeight()) / mbgl::util::tileSize);
|
||||
|
||||
size_t cacheSize = zoomFactor * cpuFactor * memoryFactor * sizeFactor * 0.5f;
|
||||
|
||||
map->setSourceTileCacheSize(cacheSize);
|
||||
|
||||
map->renderSync();
|
||||
}
|
||||
map->renderSync();
|
||||
}
|
||||
|
||||
void NativeMapView::resizeView(int w, int h) {
|
||||
|
||||
4
android/java/.gitignore
vendored
4
android/java/.gitignore
vendored
@@ -10,6 +10,10 @@ build/
|
||||
*.so
|
||||
*.apk
|
||||
|
||||
# JNI
|
||||
MapboxGLAndroidSDK/src/main/jniLibs/
|
||||
MapboxGLAndroidSDK/src/main/obj.target/
|
||||
|
||||
# Lib assets
|
||||
MapboxGLAndroidSDK/src/main/assets/
|
||||
|
||||
|
||||
@@ -63,7 +63,7 @@ import com.mapzen.android.lost.api.LocationListener;
|
||||
import com.mapzen.android.lost.api.LocationRequest;
|
||||
import com.mapzen.android.lost.api.LocationServices;
|
||||
import com.mapzen.android.lost.api.LostApiClient;
|
||||
import com.squareup.okhttp.HttpUrl;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -138,6 +138,9 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
// Used to call JNI NativeMapView
|
||||
private NativeMapView mNativeMapView;
|
||||
|
||||
// Used to track rendering
|
||||
private Boolean mDirty = false;
|
||||
|
||||
// Used to handle DPI scaling
|
||||
private float mScreenDensity = 1.0f;
|
||||
|
||||
@@ -197,7 +200,7 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
// Used to manage Event Listeners
|
||||
private ArrayList<OnMapChangedListener> mOnMapChangedListener;
|
||||
|
||||
private enum MapChange {
|
||||
public enum MapChange {
|
||||
MapChangeNullChange(-1),
|
||||
MapChangeRegionWillChange(0),
|
||||
MapChangeRegionWillChangeAnimated(1),
|
||||
@@ -400,6 +403,12 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
.setSmallestDisplacement(1)
|
||||
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
|
||||
|
||||
// Setup User Location UI
|
||||
mGpsMarker = new ImageView(getContext());
|
||||
mGpsMarker.setImageResource(R.drawable.location_marker);
|
||||
mGpsMarker.setVisibility(View.INVISIBLE);
|
||||
addView(mGpsMarker);
|
||||
|
||||
// Setup Compass
|
||||
mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);
|
||||
mSensorAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
|
||||
@@ -411,6 +420,7 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
mCompassView.setContentDescription(getResources().getString(R.string.compassContentDescription));
|
||||
LayoutParams lp = new FrameLayout.LayoutParams((int)(48 * mScreenDensity), (int)(48 * mScreenDensity));
|
||||
mCompassView.setLayoutParams(lp);
|
||||
mCompassView.setVisibility(View.INVISIBLE);
|
||||
addView(mCompassView);
|
||||
mCompassView.setOnClickListener(new CompassOnClickListener());
|
||||
|
||||
@@ -883,7 +893,9 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
addOnMapChangedListener(new OnMapChangedListener() {
|
||||
@Override
|
||||
public void onMapChanged(MapChange change) {
|
||||
updateMap(change);
|
||||
if (change.equals(MapChange.MapChangeRegionWillChange) || change.equals(MapChange.MapChangeRegionWillChangeAnimated)) {
|
||||
deselectAnnotation();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -957,7 +969,7 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
|
||||
if (mIsMyLocationEnabled) {
|
||||
toggleGps(false);
|
||||
};
|
||||
}
|
||||
|
||||
mNativeMapView.pause();
|
||||
}
|
||||
@@ -1074,7 +1086,8 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
@Override
|
||||
public boolean onTouchEvent(@NonNull MotionEvent event) {
|
||||
// Check and ignore non touch or left clicks
|
||||
if ((android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) && (event.getButtonState() != 0) && (event.getButtonState() != MotionEvent.BUTTON_PRIMARY)) {
|
||||
|
||||
if ((event.getButtonState() != 0) && (event.getButtonState() != MotionEvent.BUTTON_PRIMARY)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1103,7 +1116,6 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
long tapInterval = event.getEventTime() - event.getDownTime();
|
||||
boolean isTap = tapInterval <= ViewConfiguration.getTapTimeout();
|
||||
boolean inProgress = mRotateGestureDetector.isInProgress() || mScaleGestureDetector.isInProgress();
|
||||
mNativeMapView.setGestureInProgress(false);
|
||||
|
||||
if (mTwoTap && isTap && !inProgress) {
|
||||
PointF focalPoint = TwoFingerGestureDetector.determineFocalPoint(event);
|
||||
@@ -1113,6 +1125,7 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
}
|
||||
|
||||
mTwoTap = false;
|
||||
mNativeMapView.setGestureInProgress(false);
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
@@ -1780,12 +1793,30 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
// Called when the map needs to be rerendered
|
||||
// Called via JNI from NativeMapView
|
||||
protected void onInvalidate() {
|
||||
post(new Runnable() {
|
||||
synchronized (mDirty) {
|
||||
if (!mDirty) {
|
||||
mDirty = true;
|
||||
postRender();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void postRender() {
|
||||
Runnable mRunnable = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
mNativeMapView.invalidate();
|
||||
updateCompass();
|
||||
updateGpsMarker();
|
||||
mNativeMapView.renderSync();
|
||||
mDirty = false;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
|
||||
postOnAnimation(mRunnable);
|
||||
} else {
|
||||
postDelayed(mRunnable, 1000 / 60);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1876,7 +1907,6 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
public final void setMyLocationEnabled (boolean enabled) {
|
||||
mIsMyLocationEnabled = enabled;
|
||||
toggleGps(enabled);
|
||||
updateMap(MapChange.MapChangeNullChange);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1898,18 +1928,20 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
mLocationClient.connect();
|
||||
updateLocation(LocationServices.FusedLocationApi.getLastLocation());
|
||||
LocationServices.FusedLocationApi.requestLocationUpdates(mLocationRequest, this);
|
||||
mSensorManager.registerListener(mCompassListener, mSensorAccelerometer, SensorManager.SENSOR_DELAY_UI);
|
||||
mSensorManager.registerListener(mCompassListener, mSensorMagneticField, SensorManager.SENSOR_DELAY_UI);
|
||||
//mSensorManager.registerListener(mCompassListener, mSensorAccelerometer, SensorManager.SENSOR_DELAY_UI);
|
||||
//mSensorManager.registerListener(mCompassListener, mSensorMagneticField, SensorManager.SENSOR_DELAY_UI);
|
||||
}
|
||||
} else {
|
||||
if (mLocationClient.isConnected()) {
|
||||
LocationServices.FusedLocationApi.removeLocationUpdates(this);
|
||||
mLocationClient.disconnect();
|
||||
mGpsLocation = null;
|
||||
mSensorManager.unregisterListener(mCompassListener, mSensorAccelerometer);
|
||||
mSensorManager.unregisterListener(mCompassListener, mSensorMagneticField);
|
||||
//mSensorManager.unregisterListener(mCompassListener, mSensorAccelerometer);
|
||||
//mSensorManager.unregisterListener(mCompassListener, mSensorMagneticField);
|
||||
}
|
||||
}
|
||||
|
||||
onInvalidate();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1931,18 +1963,8 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
* @param compassEnabled true to enable the compass; false to disable the compass.
|
||||
*/
|
||||
public void setCompassEnabled (boolean compassEnabled) {
|
||||
// Set value
|
||||
this.mIsCompassEnabled = compassEnabled;
|
||||
|
||||
// Toggle UI
|
||||
if (mIsCompassEnabled) {
|
||||
mCompassView.setVisibility(View.VISIBLE);
|
||||
} else {
|
||||
mCompassView.setVisibility(View.GONE);
|
||||
}
|
||||
|
||||
// Update Map
|
||||
updateMap(MapChange.MapChangeNullChange);
|
||||
onInvalidate();
|
||||
}
|
||||
|
||||
public void setCompassGravity(int gravity){
|
||||
@@ -2022,7 +2044,7 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
}
|
||||
}
|
||||
|
||||
updateMap(MapChange.MapChangeNullChange);
|
||||
onInvalidate();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -2088,7 +2110,7 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
private void updateLocation(Location location) {
|
||||
if (location != null) {
|
||||
mGpsLocation = location;
|
||||
updateMap(MapChange.MapChangeNullChange);
|
||||
updateGpsMarker();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2102,22 +2124,17 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
}
|
||||
|
||||
// Updates the UI to match the current map's position
|
||||
private void updateMap(MapChange change) {
|
||||
// Using direct access to mIsCompassEnabled instead of isCompassEnabled() for
|
||||
// small performance boost as this method is called rapidly.
|
||||
if (mIsCompassEnabled) {
|
||||
private void updateCompass() {
|
||||
if (isCompassEnabled()) {
|
||||
mCompassView.setVisibility(VISIBLE);
|
||||
rotateImageView(mCompassView, (float) getDirection());
|
||||
} else {
|
||||
mCompassView.setVisibility(INVISIBLE);
|
||||
}
|
||||
}
|
||||
|
||||
private void updateGpsMarker() {
|
||||
if (isMyLocationEnabled() && mGpsLocation != null) {
|
||||
if (mGpsMarker == null) {
|
||||
// Setup User Location UI
|
||||
// NOTE: mIsMyLocationEnabled == false to begin with
|
||||
mGpsMarker = new ImageView(getContext());
|
||||
mGpsMarker.setImageResource(R.drawable.location_marker);
|
||||
addView(mGpsMarker);
|
||||
}
|
||||
|
||||
mGpsMarker.setVisibility(View.VISIBLE);
|
||||
LatLng coordinate = new LatLng(mGpsLocation);
|
||||
PointF screenLocation = toScreenLocation(coordinate);
|
||||
@@ -2130,26 +2147,6 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
mGpsMarker.setLayoutParams(lp);
|
||||
rotateImageView(mGpsMarker, 0.0f);
|
||||
mGpsMarker.requestLayout();
|
||||
|
||||
// Update direction if tracking mode
|
||||
if(mUserLocationTrackingMode == UserLocationTrackingMode.FOLLOW_BEARING && mCompassValid){
|
||||
// TODO need to do proper filtering (see branch filter-compass) or else map will lock up because of all the compass events
|
||||
long t = new Date().getTime();
|
||||
if((t-t0)>1000){
|
||||
t0 = t;
|
||||
setDirection(-mCompassBearing, true);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
// TODO - Too much overhead on main thread. Needs to be refactored before it
|
||||
// can be re-enabled
|
||||
// Update map position if NOT in NONE mode
|
||||
if (mUserLocationTrackingMode != UserLocationTrackingMode.NONE) {
|
||||
setCenterCoordinate(new LatLng(mGpsLocation));
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
// Used For User Location Bearing UI
|
||||
if (mGpsLocation.hasBearing() || mCompassValid) {
|
||||
@@ -2169,13 +2166,28 @@ public class MapView extends FrameLayout implements LocationListener {
|
||||
mGpsMarker.setVisibility(View.INVISIBLE);
|
||||
}
|
||||
}
|
||||
|
||||
if (change.equals(MapChange.MapChangeRegionWillChange) || change.equals(MapChange.MapChangeRegionWillChangeAnimated)) {
|
||||
deselectAnnotation();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Old tracking code
|
||||
// Update direction if tracking mode
|
||||
/*if(mUserLocationTrackingMode == UserLocationTrackingMode.FOLLOW_BEARING && mCompassValid){
|
||||
// TODO need to do proper filtering (see branch filter-compass) or else map will lock up because of all the compass events
|
||||
long t = new Date().getTime();
|
||||
if((t-t0)>1000){
|
||||
t0 = t;
|
||||
setDirection(-mCompassBearing, true);
|
||||
}
|
||||
}*/
|
||||
|
||||
/*
|
||||
// TODO - Too much overhead on main thread. Needs to be refactored before it
|
||||
// can be re-enabled
|
||||
// Update map position if NOT in NONE mode
|
||||
if (mUserLocationTrackingMode != UserLocationTrackingMode.NONE) {
|
||||
setCenterCoordinate(new LatLng(mGpsLocation));
|
||||
}
|
||||
*/
|
||||
|
||||
private void selectAnnotation(Annotation annotation) {
|
||||
|
||||
if (annotation == null) {
|
||||
|
||||
@@ -96,8 +96,8 @@ class NativeMapView {
|
||||
nativeUpdate(mNativeMapViewPtr);
|
||||
}
|
||||
|
||||
public void invalidate() {
|
||||
nativeOnInvalidate(mNativeMapViewPtr);
|
||||
public void renderSync() {
|
||||
nativeRenderSync(mNativeMapViewPtr);
|
||||
}
|
||||
|
||||
public void resizeView(int width, int height) {
|
||||
@@ -475,7 +475,7 @@ class NativeMapView {
|
||||
|
||||
private native void nativeUpdate(long nativeMapViewPtr);
|
||||
|
||||
private native void nativeOnInvalidate(long nativeMapViewPtr);
|
||||
private native void nativeRenderSync(long nativeMapViewPtr);
|
||||
|
||||
private native void nativeViewResize(long nativeMapViewPtr, int width, int height);
|
||||
|
||||
|
||||
81
android/java/MapboxGLAndroidSDKTestApp/README.md
Normal file
81
android/java/MapboxGLAndroidSDKTestApp/README.md
Normal file
@@ -0,0 +1,81 @@
|
||||
# Mapbox GL Test App
|
||||
|
||||
## Testing
|
||||
|
||||
### Running Espresso tests on a device
|
||||
|
||||
This test project comes with all the required Android Testing Support Library dependencies
|
||||
in the Gradle file. Tests are under the `app/src/androidTest` folder.
|
||||
|
||||
Note that before running your tests, you might want to turn off animations on your test device.
|
||||
It's a known issue that leaving system animations turned on in a test device
|
||||
(window animation scale, transition animation scale, animator duration scale)
|
||||
might cause unexpected results, or may lead tests to fail.
|
||||
|
||||
To create a new run configuration:
|
||||
* Click on Run -> Edit Configurations...
|
||||
* Click on the plus sign and then on "Android Tests"
|
||||
* Give a name to the configuration, e.g. `TestAppTests`
|
||||
* Choose the `MapboxGLAndroidSDKTestApp` module
|
||||
* Choose `android.support.test.runner.AndroidJUnitRunner` as the instrumentation runner
|
||||
* Click OK to save the new configuration
|
||||
|
||||
You can now run this configuration from the main toolbar dropdown menu.
|
||||
|
||||
### Running Espresso tests on AWS Device Farm
|
||||
|
||||
On a terminal, within `mapbox-gl-native/android/java`,
|
||||
run the tests (`cC` stands for `connectedCheck`):
|
||||
|
||||
```
|
||||
$ ./gradlew cC -p MapboxGLAndroidSDKTestApp
|
||||
```
|
||||
|
||||
Then:
|
||||
* Go to your AWS Console and choose Device Farm.
|
||||
* Create a new project, e.g. `MapboxGLAndroidSDKTestApp`
|
||||
* On step 1, upload the APK in `mapbox-gl-native/android/java/MapboxGLAndroidSDKTestApp/build/outputs/apk/MapboxGLAndroidSDKTestApp-debug-unaligned.apk`
|
||||
* On step 2, choose Instrumentation, test filter is `com.mapbox.mapboxgl.testapp.MainActivityTest` and upload the APK in `mapbox-gl-native/android/java/MapboxGLAndroidSDKTestApp/build/outputs/apk/MapboxGLAndroidSDKTestApp-debug-androidTest-unaligned.apk`
|
||||
* On step 3, choose a device pool. E.g. Top Devices
|
||||
* On step 4, customize your device state (if needed)
|
||||
* Finally, confirm the configuration and run the tests.
|
||||
|
||||
On Step 2, you can also separate by commas different classes: `com.mapbox.mapboxgl.testapp.MainActivityTest,com.mapbox.mapboxgl.testapp.MainActivityScreenTest`
|
||||
|
||||
If you have no tests for your app, or want to test some random user behaviour,
|
||||
you can just choose "Built-in: Fuzz" in step 2.
|
||||
|
||||
### Running pure JUnit tests
|
||||
|
||||
These tests run on a local JVM on your development machine and they are extremely fast to run
|
||||
(as compared to Espresso). These tests are located under `src/test/java`. To run them you switch
|
||||
to the Unit Tests build variant, then right click the corresponding test class or method
|
||||
and select "Run ...".
|
||||
|
||||
You can also have a run configuration:
|
||||
* Click on Run -> Edit Configurations...
|
||||
* Click on "Junit Tests"
|
||||
* Give a name to the configuration, e.g. `JUnit tests`
|
||||
* As "Test Kind", choose "All in directory"
|
||||
* As folder, choose the following folder: `mapbox-gl-native/android/java/MapboxGLAndroidSDKTestApp/src/test/java`
|
||||
* Click OK to save the new configuration
|
||||
|
||||
You can also run the tests from the command line with:
|
||||
|
||||
```
|
||||
$ ./gradlew test --continue -p MapboxGLAndroidSDKTestApp
|
||||
```
|
||||
|
||||
### Running the UI/Application Exerciser Monkey
|
||||
|
||||
Similar to the "Built-in: Fuzz" test mentioned above, Android provides
|
||||
[Monkey](http://developer.android.com/tools/help/monkey.html),
|
||||
"a program that runs on your emulator or device and generates pseudo-random streams of user events
|
||||
such as clicks, touches, or gestures, as well as a number of system-level events."
|
||||
|
||||
To exercise Monkey on the test app, install the package on the device (e.g. via Android Studio)
|
||||
and then:
|
||||
|
||||
```
|
||||
$ adb shell monkey -p com.mapbox.mapboxgl.testapp -v 500
|
||||
```
|
||||
@@ -51,6 +51,9 @@ android {
|
||||
targetSdkVersion 23
|
||||
versionCode 4
|
||||
versionName "0.1.3"
|
||||
|
||||
// Specify AndroidJUnitRunner as the default test instrumentation runner
|
||||
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
@@ -61,6 +64,7 @@ android {
|
||||
packagingOptions {
|
||||
exclude 'META-INF/LICENSE.txt'
|
||||
exclude 'META-INF/NOTICE.txt'
|
||||
exclude 'LICENSE.txt'
|
||||
}
|
||||
|
||||
lintOptions {
|
||||
@@ -76,6 +80,14 @@ android {
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
|
||||
splits {
|
||||
abi {
|
||||
enable true
|
||||
reset()
|
||||
include 'armeabi', 'armeabi-v7a', 'x86', 'mips'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
@@ -86,9 +98,16 @@ dependencies {
|
||||
compile 'com.android.support:support-v4:23.0.1'
|
||||
compile 'com.android.support:appcompat-v7:23.0.1'
|
||||
compile 'com.android.support:design:23.0.1'
|
||||
compile('com.crashlytics.sdk.android:crashlytics:2.5.1@aar') {
|
||||
compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') {
|
||||
transitive = true;
|
||||
}
|
||||
|
||||
// Testing dependencies
|
||||
testCompile 'junit:junit:4.12'
|
||||
testCompile 'org.mockito:mockito-core:1.+'
|
||||
androidTestCompile 'com.android.support.test:runner:0.4'
|
||||
androidTestCompile 'com.android.support.test:rules:0.4'
|
||||
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
|
||||
}
|
||||
|
||||
checkstyle {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.mapbox.mapboxgl.testapp;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.support.test.InstrumentationRegistry;
|
||||
import android.test.ActivityInstrumentationTestCase2;
|
||||
|
||||
import com.mapbox.mapboxgl.testapp.utils.ScreenshotUtil;
|
||||
|
||||
import org.junit.Before;
|
||||
|
||||
import static android.support.test.espresso.Espresso.onView;
|
||||
import static android.support.test.espresso.assertion.ViewAssertions.matches;
|
||||
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
|
||||
import static android.support.test.espresso.matcher.ViewMatchers.withId;
|
||||
|
||||
/**
|
||||
* Base Espresso class for all tests, helps working with ActivityInstrumentationTestCase2
|
||||
*/
|
||||
public class BaseTest {
|
||||
|
||||
/*
|
||||
* Shortcuts for common UI tests
|
||||
*/
|
||||
|
||||
protected void checkViewIsDisplayed(int id) {
|
||||
onView(withId(id))
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
/*
|
||||
* Screenshots logic
|
||||
*/
|
||||
|
||||
protected void takeNamedScreenshot(final Activity activity, final String name) {
|
||||
|
||||
// Screenshots need to be taken on the UI thread
|
||||
activity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ScreenshotUtil.take(activity, name);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.mapbox.mapboxgl.testapp;
|
||||
|
||||
import android.support.test.rule.ActivityTestRule;
|
||||
import android.support.test.runner.AndroidJUnit4;
|
||||
import android.test.suitebuilder.annotation.LargeTest;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import static android.support.test.espresso.Espresso.onView;
|
||||
import static android.support.test.espresso.action.ViewActions.click;
|
||||
import static android.support.test.espresso.action.ViewActions.doubleClick;
|
||||
import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription;
|
||||
import static android.support.test.espresso.matcher.ViewMatchers.withId;
|
||||
import static android.support.test.espresso.matcher.ViewMatchers.withText;
|
||||
|
||||
/**
|
||||
* Tests on MainActivity with screenshots
|
||||
*/
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
@LargeTest
|
||||
public class MainActivityScreenTest extends BaseTest {
|
||||
|
||||
private final static String HOME_BUTTON_STRING = "Navigate up";
|
||||
|
||||
@Rule
|
||||
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
|
||||
MainActivity.class);
|
||||
|
||||
private MainActivity mActivity = null;
|
||||
|
||||
@Before
|
||||
public void setActivity() {
|
||||
mActivity = mActivityRule.getActivity();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSanity() {
|
||||
checkViewIsDisplayed(R.id.mainMapView);
|
||||
}
|
||||
|
||||
/*
|
||||
* Take a screenshot of Mapbox Streets to monitor #1649
|
||||
*/
|
||||
|
||||
@Test
|
||||
public void testMapboxStreetsBlackAndWhite() {
|
||||
// Click home and switch to Mapbox streets
|
||||
onView(withContentDescription(HOME_BUTTON_STRING))
|
||||
.perform(click());
|
||||
onView(withText(R.string.styleMapboxStreets))
|
||||
.perform(click());
|
||||
|
||||
// Zoom in
|
||||
onView(withId(R.id.mainMapView))
|
||||
.perform(doubleClick());
|
||||
onView(withId(R.id.mainMapView))
|
||||
.perform(doubleClick());
|
||||
|
||||
// Standard screenshot
|
||||
takeNamedScreenshot(mActivity, "testMapboxStreetsBlackAndWhite");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
package com.mapbox.mapboxgl.testapp;
|
||||
|
||||
import android.support.test.rule.ActivityTestRule;
|
||||
import android.support.test.runner.AndroidJUnit4;
|
||||
import android.test.suitebuilder.annotation.LargeTest;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import static android.support.test.espresso.Espresso.onView;
|
||||
import static android.support.test.espresso.action.ViewActions.click;
|
||||
import static android.support.test.espresso.action.ViewActions.doubleClick;
|
||||
import static android.support.test.espresso.action.ViewActions.longClick;
|
||||
import static android.support.test.espresso.action.ViewActions.swipeDown;
|
||||
import static android.support.test.espresso.action.ViewActions.swipeLeft;
|
||||
import static android.support.test.espresso.action.ViewActions.swipeRight;
|
||||
import static android.support.test.espresso.action.ViewActions.swipeUp;
|
||||
import static android.support.test.espresso.assertion.ViewAssertions.matches;
|
||||
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
|
||||
import static android.support.test.espresso.matcher.ViewMatchers.withContentDescription;
|
||||
import static android.support.test.espresso.matcher.ViewMatchers.withId;
|
||||
import static android.support.test.espresso.matcher.ViewMatchers.withText;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
/**
|
||||
* Tests on MainActivity
|
||||
*/
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
@LargeTest
|
||||
public class MainActivityTest extends BaseTest {
|
||||
|
||||
private final static String HOME_BUTTON_STRING = "Navigate up";
|
||||
|
||||
@Rule
|
||||
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
|
||||
MainActivity.class);
|
||||
|
||||
private MainActivity mActivity = null;
|
||||
|
||||
@Before
|
||||
public void setActivity() {
|
||||
mActivity = mActivityRule.getActivity();
|
||||
}
|
||||
|
||||
/*
|
||||
* Note that we need to keep the `test` prefix if we want to be able to run these
|
||||
* tests on AWS Device Farm, annotations are not enough:
|
||||
* https://github.com/awslabs/aws-device-farm-sample-app-for-android/issues/5#issuecomment-138258444
|
||||
*/
|
||||
|
||||
@Test
|
||||
public void testSanity() {
|
||||
onView(withId(R.id.mainMapView))
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
/*
|
||||
* Check UI ids are visible
|
||||
*/
|
||||
|
||||
@Test
|
||||
public void testDrawerLayoutIsDisplayed() {
|
||||
onView(withId(R.id.drawer_layout))
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToolbarIsDisplayed() {
|
||||
onView(withId(R.id.toolbar))
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testContentFrameIsDisplayed() {
|
||||
onView(withId(R.id.content_frame))
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testViewFpsIsDisplayed() {
|
||||
// By default, R.id.view_fps is not displayed
|
||||
onView(withId(R.id.view_fps))
|
||||
.check(matches(not(isDisplayed())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLocationFABIsDisplayed() {
|
||||
onView(withId(R.id.locationFAB))
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNavViewIsNotDisplayed() {
|
||||
// By default, nav_view not displayed
|
||||
onView(withId(R.id.nav_view))
|
||||
.check(matches(not(isDisplayed())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNavViewIsDisplayed() {
|
||||
// However, it's displayed when we click the home icon
|
||||
onView(withContentDescription(HOME_BUTTON_STRING))
|
||||
.perform(click());
|
||||
onView(withId(R.id.nav_view))
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
/*
|
||||
* Some more tests on the map view (clicks, gestures)
|
||||
*/
|
||||
|
||||
@Test
|
||||
public void testClickMap() {
|
||||
onView(withId(R.id.mainMapView))
|
||||
.perform(click())
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDoubleClickMap() {
|
||||
onView(withId(R.id.mainMapView))
|
||||
.perform(doubleClick())
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLongClickMap() {
|
||||
onView(withId(R.id.mainMapView))
|
||||
.perform(longClick())
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSwipeLeftMap() {
|
||||
onView(withId(R.id.mainMapView))
|
||||
.perform(swipeLeft())
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSwipeRightMap() {
|
||||
onView(withId(R.id.mainMapView))
|
||||
.perform(swipeRight())
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSwipeDownMap() {
|
||||
onView(withId(R.id.mainMapView))
|
||||
.perform(swipeDown())
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSwipeUpMap() {
|
||||
onView(withId(R.id.mainMapView))
|
||||
.perform(swipeUp())
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
/*
|
||||
* Test the main drawer options
|
||||
*/
|
||||
|
||||
@Test
|
||||
public void testNavViewActionDebug() {
|
||||
onView(withContentDescription(HOME_BUTTON_STRING))
|
||||
.perform(click());
|
||||
onView(withText(R.string.action_debug))
|
||||
.perform(click());
|
||||
|
||||
// Clicking the item closes the drawer
|
||||
onView(withId(R.id.nav_view))
|
||||
.check(matches(not(isDisplayed())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNavViewActionPointAnnotations() {
|
||||
onView(withContentDescription(HOME_BUTTON_STRING))
|
||||
.perform(click());
|
||||
onView(withText(R.string.action_point_annotations))
|
||||
.perform(click());
|
||||
|
||||
// Clicking the item closes the drawer
|
||||
onView(withId(R.id.nav_view))
|
||||
.check(matches(not(isDisplayed())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNavViewActionCompass() {
|
||||
onView(withContentDescription(HOME_BUTTON_STRING))
|
||||
.perform(click());
|
||||
onView(withText(R.string.action_compass))
|
||||
.perform(click());
|
||||
|
||||
// Clicking the item closes the drawer
|
||||
onView(withId(R.id.nav_view))
|
||||
.check(matches(not(isDisplayed())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNavViewStyleMapboxStreets() {
|
||||
onView(withContentDescription(HOME_BUTTON_STRING))
|
||||
.perform(click());
|
||||
onView(withText(R.string.styleMapboxStreets))
|
||||
.perform(click());
|
||||
|
||||
// Clicking the item closes the drawer
|
||||
onView(withId(R.id.nav_view))
|
||||
.check(matches(not(isDisplayed())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNavViewStyleEmerald() {
|
||||
onView(withContentDescription(HOME_BUTTON_STRING))
|
||||
.perform(click());
|
||||
onView(withText(R.string.styleEmerald))
|
||||
.perform(click());
|
||||
|
||||
// Clicking the item closes the drawer
|
||||
onView(withId(R.id.nav_view))
|
||||
.check(matches(not(isDisplayed())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNavViewStyleLight() {
|
||||
onView(withContentDescription(HOME_BUTTON_STRING))
|
||||
.perform(click());
|
||||
onView(withText(R.string.styleLight))
|
||||
.perform(click());
|
||||
|
||||
// Clicking the item closes the drawer
|
||||
onView(withId(R.id.nav_view))
|
||||
.check(matches(not(isDisplayed())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNavViewStyleDark() {
|
||||
onView(withContentDescription(HOME_BUTTON_STRING))
|
||||
.perform(click());
|
||||
onView(withText(R.string.styleDark))
|
||||
.perform(click());
|
||||
|
||||
// Clicking the item closes the drawer
|
||||
onView(withId(R.id.nav_view))
|
||||
.check(matches(not(isDisplayed())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNavViewStyleSatellite() {
|
||||
onView(withContentDescription(HOME_BUTTON_STRING))
|
||||
.perform(click());
|
||||
onView(withText(R.string.styleSatellite))
|
||||
.perform(click());
|
||||
|
||||
// Clicking the item closes the drawer
|
||||
onView(withId(R.id.nav_view))
|
||||
.check(matches(not(isDisplayed())));
|
||||
}
|
||||
|
||||
/*
|
||||
* We can also check the map inner elements are visible
|
||||
*/
|
||||
|
||||
@Test
|
||||
public void testMapIconContentDescription() {
|
||||
// Mapbox logo
|
||||
onView(withContentDescription(mActivity.getResources()
|
||||
.getString(R.string.mapboxIconContentDescription)))
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapCompassContentDescription() {
|
||||
// Map compass
|
||||
onView(withContentDescription(mActivity.getResources()
|
||||
.getString(R.string.compassContentDescription)))
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMapAttributionsIconContentDescription() {
|
||||
// Attribution icon
|
||||
onView(withContentDescription(mActivity.getResources()
|
||||
.getString(R.string.attributionsIconContentDescription)))
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.mapbox.mapboxgl.testapp;
|
||||
|
||||
import android.support.test.rule.ActivityTestRule;
|
||||
import android.support.test.runner.AndroidJUnit4;
|
||||
import android.test.suitebuilder.annotation.LargeTest;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
import static android.support.test.espresso.Espresso.onView;
|
||||
import static android.support.test.espresso.assertion.ViewAssertions.matches;
|
||||
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
|
||||
import static android.support.test.espresso.matcher.ViewMatchers.withId;
|
||||
|
||||
/**
|
||||
* Tests on SecondMapActivity.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4.class)
|
||||
@LargeTest
|
||||
public class SecondMapActivityTest extends BaseTest {
|
||||
|
||||
@Rule
|
||||
public ActivityTestRule<SecondMapActivity> mActivityRule = new ActivityTestRule<>(
|
||||
SecondMapActivity.class);
|
||||
|
||||
private SecondMapActivity mActivity = null;
|
||||
|
||||
@Before
|
||||
public void setActivity() {
|
||||
mActivity = mActivityRule.getActivity();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSanity() {
|
||||
onView(withId(R.id.secondMapView))
|
||||
.check(matches(isDisplayed()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.mapbox.mapboxgl.testapp.utils;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.Canvas;
|
||||
import android.os.Environment;
|
||||
import android.util.Log;
|
||||
import android.view.TextureView;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* The built-in Fuzz Suite on AWS Device Farm takes screenshots after every test. However,
|
||||
* this doesn't happen with Espresso unless we manually do it. This class fixes it.
|
||||
*/
|
||||
public class ScreenshotUtil {
|
||||
|
||||
private static final String LOG_TAG = ScreenshotUtil.class.getName();
|
||||
|
||||
// Where to store the files. This path is required by AWS Device Farm:
|
||||
// http://docs.aws.amazon.com/devicefarm/latest/developerguide/test-types-android-instrumentation.html#test-types-android-instrumentation-screenshots
|
||||
private static final String SCREENSHOT_FOLDER = "test-screenshots";
|
||||
|
||||
// Image type and quality
|
||||
private static final String DEFAULT_IMAGE_EXTENSION = ".png";
|
||||
private static final Bitmap.CompressFormat DEFAULT_IMAGE_FORMAT = Bitmap.CompressFormat.PNG;
|
||||
private static final int DEFAULT_IMAGE_QUALITY = 100;
|
||||
|
||||
public static void take(Activity activity, String testName) {
|
||||
|
||||
// Check if storage is available
|
||||
if (!isExternalStorageWritable()) {
|
||||
Log.d(LOG_TAG, "External storage is not available.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Get a bitmap from the activity root view. When the drawing cache is enabled,
|
||||
// the next call to getDrawingCache() will draw the view in a bitmap.
|
||||
View rootView = activity.getWindow().getDecorView().getRootView();
|
||||
rootView.setDrawingCacheEnabled(true);
|
||||
Bitmap bitmap = Bitmap.createBitmap(rootView.getDrawingCache());
|
||||
rootView.setDrawingCacheEnabled(false);
|
||||
|
||||
// Add the SurfaceView bit (see getAllTextureViews() below)
|
||||
List<TextureView> tilingViews = getAllTextureViews(rootView);
|
||||
if (tilingViews.size() > 0) {
|
||||
Canvas canvas = new Canvas(bitmap);
|
||||
for (TextureView TextureView : tilingViews) {
|
||||
Bitmap b = TextureView.getBitmap(TextureView.getWidth(), TextureView.getHeight());
|
||||
int[] location = new int[2];
|
||||
TextureView.getLocationInWindow(location);
|
||||
int[] location2 = new int[2];
|
||||
TextureView.getLocationOnScreen(location2);
|
||||
canvas.drawBitmap(b, location[0], location[1], null);
|
||||
}
|
||||
}
|
||||
|
||||
// Save the bitmap in external storage
|
||||
String uniqueAbsolutePath = getUniqueAbsolutePath(testName);
|
||||
File outputFile = new File(uniqueAbsolutePath);
|
||||
OutputStream outputStream = null;
|
||||
try {
|
||||
outputStream = new FileOutputStream(outputFile);
|
||||
bitmap.compress(DEFAULT_IMAGE_FORMAT, DEFAULT_IMAGE_QUALITY, outputStream);
|
||||
outputStream.flush();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (outputStream != null) {
|
||||
try {
|
||||
outputStream.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* The classic way of taking a screenshot (above) doesn't work with TextureView, this fixes it:
|
||||
* http://stackoverflow.com/questions/19704060/screen-capture-textureview-is-black-using-drawingcache
|
||||
*/
|
||||
|
||||
public static List<TextureView> getAllTextureViews(View view)
|
||||
{
|
||||
List<TextureView> tilingViews = new ArrayList<TextureView>();
|
||||
if (view instanceof TextureView) {
|
||||
tilingViews.add((TextureView)view);
|
||||
} else if(view instanceof ViewGroup) {
|
||||
ViewGroup viewGroup = (ViewGroup)view;
|
||||
for (int i = 0; i < viewGroup.getChildCount(); i++) {
|
||||
tilingViews.addAll(getAllTextureViews(viewGroup.getChildAt(i)));
|
||||
}
|
||||
}
|
||||
|
||||
return tilingViews;
|
||||
}
|
||||
|
||||
/*
|
||||
* Utils
|
||||
*/
|
||||
|
||||
public static boolean isExternalStorageWritable() {
|
||||
// Checks if external storage is available for read and write
|
||||
String state = Environment.getExternalStorageState();
|
||||
return Environment.MEDIA_MOUNTED.equals(state);
|
||||
}
|
||||
|
||||
private static String getUniqueAbsolutePath(String testName) {
|
||||
// A screenshot after every test vs. manual tests
|
||||
String filename = UUID.randomUUID().toString() + DEFAULT_IMAGE_EXTENSION;
|
||||
if (testName != null && !testName.isEmpty()) {
|
||||
filename = testName + DEFAULT_IMAGE_EXTENSION;
|
||||
}
|
||||
|
||||
String externalPath = Environment.getExternalStorageDirectory().toString();
|
||||
String path = externalPath + File.separator + SCREENSHOT_FOLDER + File.separator + filename;
|
||||
Log.d(LOG_TAG, "Screenshot path: " + path);
|
||||
return path;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<activity android:name=".SecondMapActivity" android:label="@string/activity_second"/>
|
||||
<meta-data
|
||||
android:name="io.fabric.ApiKey"
|
||||
android:value="9724157045ff7d083492c6d9ae03e60e8609d461" />
|
||||
@@ -25,4 +26,5 @@
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
|
||||
</manifest>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.mapbox.mapboxgl.testapp;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.PointF;
|
||||
@@ -284,6 +285,10 @@ public class MainActivity extends AppCompatActivity {
|
||||
menuItem.setChecked(mMapView.isCompassEnabled());
|
||||
return true;
|
||||
|
||||
case R.id.action_second_map_activity:
|
||||
startActivity(new Intent(getApplicationContext(), SecondMapActivity.class));
|
||||
return true;
|
||||
|
||||
/*
|
||||
case R.id.followNone:
|
||||
mMapView.setUserLocationTrackingMode(MapView.UserLocationTrackingMode.NONE);
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.mapbox.mapboxgl.testapp;
|
||||
|
||||
import android.os.Bundle;
|
||||
import android.support.v7.app.AppCompatActivity;
|
||||
import android.support.v7.widget.Toolbar;
|
||||
import android.util.Log;
|
||||
import android.view.MenuItem;
|
||||
import com.mapbox.mapboxgl.views.MapView;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
|
||||
public class SecondMapActivity extends AppCompatActivity {
|
||||
|
||||
private static final String TAG = "SecondMapActivity";
|
||||
|
||||
private MapView mMapView;
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
setContentView(R.layout.activity_second);
|
||||
|
||||
Toolbar toolbar = (Toolbar) findViewById(R.id.secondToolBar);
|
||||
setSupportActionBar(toolbar);
|
||||
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
|
||||
getSupportActionBar().setDisplayShowHomeEnabled(true);
|
||||
|
||||
mMapView = (MapView) findViewById(R.id.secondMapView);
|
||||
// Load the access token
|
||||
try {
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.token)));
|
||||
String line = reader.readLine();
|
||||
mMapView.setAccessToken(line);
|
||||
} catch (IOException e) {
|
||||
Log.e(TAG, "Error loading access token from token.txt: " + e.toString());
|
||||
}
|
||||
|
||||
mMapView.onCreate(savedInstanceState);
|
||||
|
||||
mMapView.setStyleUrl(getString(R.string.styleURLEmerald));
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch onStart() to all fragments. Ensure any created loaders are
|
||||
* now started.
|
||||
*/
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
mMapView.onStart();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStop() {
|
||||
super.onStop();
|
||||
mMapView.onStop();
|
||||
}
|
||||
|
||||
// Called when our app goes into the background
|
||||
@Override
|
||||
public void onPause() {
|
||||
super.onPause();
|
||||
|
||||
mMapView.onPause();
|
||||
}
|
||||
|
||||
// Called when our app comes into the foreground
|
||||
@Override
|
||||
public void onResume() {
|
||||
super.onResume();
|
||||
|
||||
mMapView.onResume();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDestroy() {
|
||||
super.onDestroy();
|
||||
mMapView.onDestroy();
|
||||
}
|
||||
|
||||
// Called when the system is running low on memory
|
||||
@Override
|
||||
public void onLowMemory() {
|
||||
super.onLowMemory();
|
||||
|
||||
mMapView.onLowMemory();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onOptionsItemSelected(MenuItem item) {
|
||||
switch (item.getItemId()) {
|
||||
case android.R.id.home:
|
||||
onBackPressed();
|
||||
return true;
|
||||
default:
|
||||
return super.onOptionsItemSelected(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 237 B |
Binary file not shown.
|
After Width: | Height: | Size: 155 B |
Binary file not shown.
|
After Width: | Height: | Size: 228 B |
Binary file not shown.
|
After Width: | Height: | Size: 315 B |
Binary file not shown.
|
After Width: | Height: | Size: 408 B |
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:orientation="vertical"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent">
|
||||
|
||||
<android.support.v7.widget.Toolbar
|
||||
android:id="@+id/secondToolBar"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@color/primary"
|
||||
android:minHeight="?attr/actionBarSize"
|
||||
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
|
||||
|
||||
<com.mapbox.mapboxgl.views.MapView
|
||||
android:id="@+id/secondMapView"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
/>
|
||||
|
||||
</LinearLayout>
|
||||
@@ -19,18 +19,24 @@
|
||||
android:checkable="true"
|
||||
/>
|
||||
|
||||
<!--
|
||||
<group android:id="@+id/locationFollowModesSeparator"/>
|
||||
<item android:id="@+id/action_second_map_activity"
|
||||
android:icon="@drawable/ic_looks_two_white_24dp"
|
||||
android:title="@string/action_second_map_activity"
|
||||
android:checkable="false"
|
||||
/>
|
||||
|
||||
<group android:id="@+id/locationFollowModes" android:checkableBehavior="single">
|
||||
<item android:id="@+id/followNone"
|
||||
android:title="@string/action_location_none"/>
|
||||
<item android:id="@+id/followFollow"
|
||||
android:title="@string/action_location_follow"/>
|
||||
<item android:id="@+id/followBearing"
|
||||
android:title="@string/action_location_bearing"/>
|
||||
</group>
|
||||
-->
|
||||
<!--
|
||||
<group android:id="@+id/locationFollowModesSeparator"/>
|
||||
|
||||
<group android:id="@+id/locationFollowModes" android:checkableBehavior="single">
|
||||
<item android:id="@+id/followNone"
|
||||
android:title="@string/action_location_none"/>
|
||||
<item android:id="@+id/followFollow"
|
||||
android:title="@string/action_location_follow"/>
|
||||
<item android:id="@+id/followBearing"
|
||||
android:title="@string/action_location_bearing"/>
|
||||
</group>
|
||||
-->
|
||||
|
||||
<group android:id="@+id/stylesSeparator"/>
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
<string name="app_name">Mapbox GL</string>
|
||||
|
||||
<string name="activity_second">Second Activity</string>
|
||||
|
||||
<string name="action_gps">Toggle GPS location</string>
|
||||
<string name="action_location_none">Disable tracking</string>
|
||||
<string name="action_location_follow">Use follow tracking mode</string>
|
||||
@@ -10,6 +12,7 @@
|
||||
<string name="action_compass">Toggle compass</string>
|
||||
<string name="action_debug">Toggle debug mode</string>
|
||||
<string name="action_point_annotations">Toggle point annotations</string>
|
||||
<string name="action_second_map_activity">Launch 2nd Map</string>
|
||||
|
||||
<string name="label_fps">FPS:</string>
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import com.mapbox.mapboxgl.geometry.BoundingBox;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class BoundingBoxTest {
|
||||
|
||||
@Test
|
||||
public void testSanity() {
|
||||
BoundingBox boundingBox = new BoundingBox(0.0, 0.0, 0.0, 0.0);
|
||||
assertNotNull("boundingBox should not be null", boundingBox);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import com.mapbox.mapboxgl.geometry.CoordinateRegion;
|
||||
import com.mapbox.mapboxgl.geometry.CoordinateSpan;
|
||||
import com.mapbox.mapboxgl.geometry.LatLng;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class CoordinateRegionTest {
|
||||
|
||||
@Test
|
||||
public void testSanity() {
|
||||
LatLng center = new LatLng(1.2, 3.4, 5.6);
|
||||
CoordinateSpan span = new CoordinateSpan(9.8, 7.6);
|
||||
CoordinateRegion coordinateRegion = new CoordinateRegion(center, span);
|
||||
assertNotNull("coordinateRegion should not be null", coordinateRegion);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCenterConstructor() {
|
||||
LatLng center = new LatLng(1.2, 3.4, 5.6);
|
||||
CoordinateSpan span = new CoordinateSpan(9.8, 7.6);
|
||||
CoordinateRegion coordinateRegion = new CoordinateRegion(center, span);
|
||||
assertEquals("center should match", coordinateRegion.getCenter(), center);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSpanConstructor() {
|
||||
LatLng center = new LatLng(1.2, 3.4, 5.6);
|
||||
CoordinateSpan span = new CoordinateSpan(9.8, 7.6);
|
||||
CoordinateRegion coordinateRegion = new CoordinateRegion(center, span);
|
||||
assertEquals("span should match", coordinateRegion.getSpan(), span);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCenterMethod() {
|
||||
LatLng center = new LatLng(1.2, 3.4, 5.6);
|
||||
CoordinateSpan span = new CoordinateSpan(9.8, 7.6);
|
||||
CoordinateRegion coordinateRegion = new CoordinateRegion(null, span);
|
||||
coordinateRegion.setCenter(center);
|
||||
assertEquals("center should match", coordinateRegion.getCenter(), center);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSpanMethod() {
|
||||
LatLng center = new LatLng(1.2, 3.4, 5.6);
|
||||
CoordinateSpan span = new CoordinateSpan(9.8, 7.6);
|
||||
CoordinateRegion coordinateRegion = new CoordinateRegion(center, null);
|
||||
coordinateRegion.setSpan(span);
|
||||
assertEquals("span should match", coordinateRegion.getSpan(), span);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import com.mapbox.mapboxgl.geometry.CoordinateSpan;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class CoordinateSpanTest {
|
||||
|
||||
private static final double DELTA = 1e-15;
|
||||
|
||||
@Test
|
||||
public void testSanity() {
|
||||
CoordinateSpan coordinateSpan = new CoordinateSpan(0.0, 0.0);
|
||||
assertNotNull("coordinateSpan should not be null", coordinateSpan);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLatitudeConstructor() {
|
||||
double latitude = 1.23;
|
||||
CoordinateSpan coordinateSpan = new CoordinateSpan(latitude, 0.0);
|
||||
assertEquals("latitude in constructor", coordinateSpan.getLatitudeSpan(), latitude, DELTA);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLongitudeConstructor() {
|
||||
double longitude = 1.23;
|
||||
CoordinateSpan coordinateSpan = new CoordinateSpan(0.0, longitude);
|
||||
assertEquals("latitude in constructor", coordinateSpan.getLongitudeSpan(), longitude, DELTA);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLatitudeMethod() {
|
||||
double latitude = 1.23;
|
||||
CoordinateSpan coordinateSpan = new CoordinateSpan(0.0, 0.0);
|
||||
coordinateSpan.setLatitudeSpan(latitude);
|
||||
assertEquals("latitude in constructor", coordinateSpan.getLatitudeSpan(), latitude, DELTA);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLongitudeMethod() {
|
||||
double longitude = 1.23;
|
||||
CoordinateSpan coordinateSpan = new CoordinateSpan(0.0, 0.0);
|
||||
coordinateSpan.setLongitudeSpan(longitude);
|
||||
assertEquals("latitude in constructor", coordinateSpan.getLongitudeSpan(), longitude, DELTA);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import android.location.Location;
|
||||
|
||||
import com.mapbox.mapboxgl.geometry.LatLng;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class LatLngTest {
|
||||
|
||||
private static final double DELTA = 1e-15;
|
||||
|
||||
@Test
|
||||
public void testSanity() {
|
||||
LatLng latLng = new LatLng(0.0, 0.0);
|
||||
assertNotNull("latLng should not be null", latLng);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLatitudeConstructor() {
|
||||
double latitude = 1.2;
|
||||
LatLng latLng = new LatLng(latitude, 3.4);
|
||||
assertEquals("latitude should match", latLng.getLatitude(), latitude, DELTA);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLongitudeConstructor() {
|
||||
double longitude = 3.4;
|
||||
LatLng latLng = new LatLng(1.2, longitude);
|
||||
assertEquals("longitude should match", latLng.getLongitude(), longitude, DELTA);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAltitudeConstructor() {
|
||||
LatLng latLng1 = new LatLng(1.2, 3.4);
|
||||
assertEquals("altitude default value", latLng1.getAltitude(), 0.0, DELTA);
|
||||
|
||||
double altitude = 5.6;
|
||||
LatLng latLng2 = new LatLng(1.2, 3.4, altitude);
|
||||
assertEquals("altitude default value", latLng2.getAltitude(), altitude, DELTA);
|
||||
}
|
||||
|
||||
/*
|
||||
* A sample test where Mockito is necessary
|
||||
*/
|
||||
|
||||
@Test
|
||||
public void testLocationProvider() {
|
||||
double latitude = 1.2;
|
||||
double longitude = 3.4;
|
||||
double altitude = 5.6;
|
||||
|
||||
// Mock the location class
|
||||
Location locationMocked = mock(Location.class);
|
||||
when(locationMocked.getLatitude()).thenReturn(latitude);
|
||||
when(locationMocked.getLongitude()).thenReturn(longitude);
|
||||
when(locationMocked.getAltitude()).thenReturn(altitude);
|
||||
|
||||
// Test the constructor
|
||||
LatLng latLng = new LatLng(locationMocked);
|
||||
assertEquals("latitude should match", latLng.getLatitude(), latitude, DELTA);
|
||||
assertEquals("longitude should match", latLng.getLongitude(), longitude, DELTA);
|
||||
assertEquals("altitude should match", latLng.getAltitude(), altitude, DELTA);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashCode() {
|
||||
double latitude = 1.2;
|
||||
double longitude = 3.4;
|
||||
double altitude = 5.6;
|
||||
LatLng latLng = new LatLng(latitude, longitude, altitude);
|
||||
assertEquals("hash code should match", latLng.hashCode(), -151519232);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToString() {
|
||||
double latitude = 1.2;
|
||||
double longitude = 3.4;
|
||||
double altitude = 5.6;
|
||||
LatLng latLng = new LatLng(latitude, longitude, altitude);
|
||||
assertEquals("string should match",
|
||||
latLng.toString(),
|
||||
"LatLng [longitude=3.4, latitude=1.2, altitude=5.6]");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDistanceTo() {
|
||||
LatLng latLng1 = new LatLng(0.0, 0.0);
|
||||
LatLng latLng2 = new LatLng(1.0, 1.0);
|
||||
assertEquals("distances should match",
|
||||
latLng1.distanceTo(latLng2),
|
||||
157425.53710839353, DELTA);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import com.mapbox.mapboxgl.geometry.LatLngZoom;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class LatLngZoomTest {
|
||||
|
||||
@Test
|
||||
public void testSanity() {
|
||||
LatLngZoom latLngZoom = new LatLngZoom(0.0, 0.0, 0.0);
|
||||
assertNotNull("latLngZoom should not be null", latLngZoom);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import com.mapbox.mapboxgl.geometry.ProjectedMeters;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class ProjectedMetersTest {
|
||||
|
||||
@Test
|
||||
public void testSanity() {
|
||||
ProjectedMeters projectedMeters = new ProjectedMeters(0.0, 0.0);
|
||||
assertNotNull("projectedMeters should not be null", projectedMeters);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -79,6 +79,12 @@
|
||||
],
|
||||
'destination': '<(pwd)/../android/java/MapboxGLAndroidSDK/src/main/assets'
|
||||
},
|
||||
{
|
||||
'files': [
|
||||
'<(PRODUCT_DIR)/obj.target'
|
||||
],
|
||||
'destination': '<(pwd)/../android/java/MapboxGLAndroidSDK/src/main'
|
||||
},
|
||||
],
|
||||
|
||||
'actions': [
|
||||
|
||||
@@ -9,13 +9,17 @@
|
||||
#include <mbgl/storage/default_file_source.hpp>
|
||||
#include <mbgl/storage/sqlite_cache.hpp>
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma GCC diagnostic push
|
||||
#ifndef __clang__
|
||||
#ifdef __clang__
|
||||
#pragma clang diagnostic ignored "-Wunused-local-typedefs"
|
||||
#else
|
||||
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
|
||||
#pragma GCC diagnostic ignored "-Wshadow"
|
||||
#endif
|
||||
#include <boost/program_options.hpp>
|
||||
#pragma GCC diagnostic pop
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
namespace po = boost::program_options;
|
||||
|
||||
|
||||
@@ -25,8 +25,6 @@
|
||||
'../include/mbgl/ios/MGLMapView.h',
|
||||
'../include/mbgl/ios/MGLMapView+IBAdditions.h',
|
||||
'../platform/ios/MGLMapView.mm',
|
||||
'../platform/ios/MGLFileCache.h',
|
||||
'../platform/ios/MGLFileCache.mm',
|
||||
'../include/mbgl/ios/MGLAccountManager.h',
|
||||
'../platform/ios/MGLAccountManager_Private.h',
|
||||
'../platform/ios/MGLAccountManager.m',
|
||||
|
||||
@@ -50,7 +50,7 @@ public:
|
||||
void enableFps(bool enable);
|
||||
void updateFps();
|
||||
|
||||
void onInvalidate();
|
||||
void renderSync();
|
||||
|
||||
void resizeView(int width, int height);
|
||||
void resizeFramebuffer(int width, int height);
|
||||
@@ -93,8 +93,6 @@ private:
|
||||
std::shared_ptr<mbgl::SQLiteCache> fileCache;
|
||||
std::unique_ptr<mbgl::DefaultFileSource> fileSource;
|
||||
std::unique_ptr<mbgl::Map> map;
|
||||
|
||||
std::atomic_flag clean = ATOMIC_FLAG_INIT;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#import "MGLTypes.h"
|
||||
|
||||
#import <CoreLocation/CoreLocation.h>
|
||||
#import <CoreGraphics/CGBase.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@@ -82,4 +83,14 @@ NS_INLINE NSString *MGLStringFromCoordinateBounds(MGLCoordinateBounds bounds) {
|
||||
bounds.ne.latitude, bounds.ne.longitude];
|
||||
}
|
||||
|
||||
NS_INLINE CGFloat MGLRadiansFromDegrees(CLLocationDegrees degrees)
|
||||
{
|
||||
return (CGFloat)(degrees * M_PI) / 180;
|
||||
}
|
||||
|
||||
NS_INLINE CLLocationDegrees MGLDegreesFromRadians(CGFloat radians)
|
||||
{
|
||||
return radians * 180 / M_PI;
|
||||
}
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
@@ -9,7 +9,7 @@ NS_ASSUME_NONNULL_BEGIN
|
||||
/** The `MGLPolyline` class represents a shape consisting of one or more points that define connecting line segments. The points are connected end-to-end in the order they are provided. The first and last points are not connected to each other. */
|
||||
@interface MGLPolyline : MGLMultiPoint <MGLOverlay>
|
||||
|
||||
/** Creates and returns an `MGLPolygon` object from the specified set of coordinates.
|
||||
/** Creates and returns an `MGLPolyline` object from the specified set of coordinates.
|
||||
* @param coords The array of coordinates defining the shape. The data in this array is copied to the new object.
|
||||
* @param count The number of items in the _`coords`_ array.
|
||||
* @return A new polyline object. */
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Pod::Spec.new do |m|
|
||||
|
||||
m.name = 'Mapbox-iOS-SDK'
|
||||
m.version = '2.0.0-symbols'
|
||||
m.version = '2.1.2-symbols'
|
||||
|
||||
m.summary = 'Open source vector map solution for iOS with full styling capabilities.'
|
||||
m.description = 'Open source OpenGL-based vector map solution for iOS with full styling capabilities and Cocoa bindings.'
|
||||
|
||||
@@ -31,9 +31,9 @@ static NSUInteger const kStyleVersion = 8;
|
||||
if (self == [MBXViewController class])
|
||||
{
|
||||
[[NSUserDefaults standardUserDefaults] registerDefaults:@{
|
||||
@"userTrackingMode": @(MGLUserTrackingModeNone),
|
||||
@"showsUserLocation": @NO,
|
||||
@"debug": @NO,
|
||||
@"MBXUserTrackingMode": @(MGLUserTrackingModeNone),
|
||||
@"MBXShowsUserLocation": @NO,
|
||||
@"MBXDebug": @NO,
|
||||
}];
|
||||
}
|
||||
}
|
||||
@@ -83,13 +83,6 @@ static NSUInteger const kStyleVersion = 8;
|
||||
action:@selector(locateUser)];
|
||||
|
||||
[self restoreState:nil];
|
||||
|
||||
if ( ! settings->showsUserLocation)
|
||||
{
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
|
||||
self.mapView.showsUserLocation = YES;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
- (void)saveState:(__unused NSNotification *)notification
|
||||
@@ -98,10 +91,10 @@ static NSUInteger const kStyleVersion = 8;
|
||||
{
|
||||
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
|
||||
NSData *archivedCamera = [NSKeyedArchiver archivedDataWithRootObject:self.mapView.camera];
|
||||
[defaults setObject:archivedCamera forKey:@"camera"];
|
||||
[defaults setInteger:self.mapView.userTrackingMode forKey:@"userTrackingMode"];
|
||||
[defaults setBool:self.mapView.showsUserLocation forKey:@"showsUserLocation"];
|
||||
[defaults setBool:self.mapView.debugActive forKey:@"debug"];
|
||||
[defaults setObject:archivedCamera forKey:@"MBXCamera"];
|
||||
[defaults setInteger:self.mapView.userTrackingMode forKey:@"MBXUserTrackingMode"];
|
||||
[defaults setBool:self.mapView.showsUserLocation forKey:@"MBXShowsUserLocation"];
|
||||
[defaults setBool:self.mapView.debugActive forKey:@"MBXDebug"];
|
||||
[defaults synchronize];
|
||||
}
|
||||
}
|
||||
@@ -110,21 +103,21 @@ static NSUInteger const kStyleVersion = 8;
|
||||
{
|
||||
if (self.mapView) {
|
||||
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
|
||||
NSData *archivedCamera = [defaults objectForKey:@"camera"];
|
||||
NSData *archivedCamera = [defaults objectForKey:@"MBXCamera"];
|
||||
MGLMapCamera *camera = archivedCamera ? [NSKeyedUnarchiver unarchiveObjectWithData:archivedCamera] : nil;
|
||||
if (camera)
|
||||
{
|
||||
self.mapView.camera = camera;
|
||||
}
|
||||
NSInteger uncheckedTrackingMode = [defaults integerForKey:@"userTrackingMode"];
|
||||
NSInteger uncheckedTrackingMode = [defaults integerForKey:@"MBXUserTrackingMode"];
|
||||
if (uncheckedTrackingMode >= 0 &&
|
||||
(NSUInteger)uncheckedTrackingMode >= MGLUserTrackingModeNone &&
|
||||
(NSUInteger)uncheckedTrackingMode <= MGLUserTrackingModeFollowWithCourse)
|
||||
{
|
||||
self.mapView.userTrackingMode = (MGLUserTrackingMode)uncheckedTrackingMode;
|
||||
}
|
||||
self.mapView.showsUserLocation = [defaults boolForKey:@"showsUserLocation"];
|
||||
self.mapView.debugActive = [defaults boolForKey:@"debug"];
|
||||
self.mapView.showsUserLocation = [defaults boolForKey:@"MBXShowsUserLocation"];
|
||||
self.mapView.debugActive = [defaults boolForKey:@"MBXDebug"];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,5 +60,7 @@
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>NSLocationAlwaysUsageDescription</key>
|
||||
<string>The map will ALWAYS display the user's location.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -12,13 +12,17 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma GCC diagnostic push
|
||||
#ifndef __clang__
|
||||
#ifdef __clang__
|
||||
#pragma clang diagnostic ignored "-Wunused-local-typedefs"
|
||||
#else
|
||||
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
|
||||
#pragma GCC diagnostic ignored "-Wshadow"
|
||||
#endif
|
||||
#include <boost/program_options.hpp>
|
||||
#pragma GCC diagnostic pop
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
#include <iostream>
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mapbox-gl-native",
|
||||
"version": "2.0.0-pre.3",
|
||||
"version": "2.0.0-pre.7",
|
||||
"description": "Renders map tiles with Mapbox GL",
|
||||
"keywords": [
|
||||
"mapbox",
|
||||
@@ -18,7 +18,7 @@
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"nan": "^1.9.0",
|
||||
"nan": "^2.0.9",
|
||||
"node-pre-gyp": "^0.6.9"
|
||||
},
|
||||
"bundledDependencies": [
|
||||
@@ -26,7 +26,7 @@
|
||||
],
|
||||
"devDependencies": {
|
||||
"aws-sdk": "^2.1.47",
|
||||
"mapbox-gl-test-suite": "git+https://github.com/mapbox/mapbox-gl-test-suite.git#6cfd7eb20de77018a7f10770f56df9ce1f8a76ac",
|
||||
"mapbox-gl-test-suite": "git+https://github.com/mapbox/mapbox-gl-test-suite.git#592540ebf822fd2e3cfdebbfabce92c1f5ef5b10",
|
||||
"request": "^2.61.0",
|
||||
"tape": "^4.2.0"
|
||||
},
|
||||
|
||||
@@ -202,7 +202,7 @@ void HeadlessView::clearBuffers() {
|
||||
}
|
||||
|
||||
if (fboColor) {
|
||||
MBGL_CHECK_ERROR(glDeleteTextures(1, &fboColor));
|
||||
MBGL_CHECK_ERROR(glDeleteRenderbuffersEXT(1, &fboColor));
|
||||
fboColor = 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
#import "MGLTypes.h"
|
||||
|
||||
#include <mbgl/storage/sqlite_cache.hpp>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface MGLFileCache : NSObject
|
||||
|
||||
+ (mbgl::SQLiteCache *)obtainSharedCacheWithObject:(NSObject *)object;
|
||||
+ (void)releaseSharedCacheForObject:(NSObject *)object;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -1,83 +0,0 @@
|
||||
#import "MGLFileCache.h"
|
||||
|
||||
@interface MGLFileCache ()
|
||||
|
||||
@property (nonatomic) MGLFileCache *sharedInstance;
|
||||
@property (nonatomic) mbgl::SQLiteCache *sharedCache;
|
||||
@property (nonatomic) NSHashTable *retainers;
|
||||
|
||||
@end
|
||||
|
||||
@implementation MGLFileCache
|
||||
|
||||
const std::string &defaultCacheDatabasePath() {
|
||||
static const std::string path = []() -> std::string {
|
||||
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
|
||||
if ([paths count] == 0) {
|
||||
// Disable the cache if we don't have a location to write.
|
||||
return "";
|
||||
}
|
||||
|
||||
NSString *libraryDirectory = [paths objectAtIndex:0];
|
||||
return [[libraryDirectory stringByAppendingPathComponent:@"cache.db"] UTF8String];
|
||||
}();
|
||||
return path;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_retainers = [NSHashTable weakObjectsHashTable];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (instancetype)sharedInstance {
|
||||
static dispatch_once_t onceToken;
|
||||
static MGLFileCache *_sharedInstance;
|
||||
dispatch_once(&onceToken, ^{
|
||||
_sharedInstance = [[self alloc] init];
|
||||
});
|
||||
return _sharedInstance;
|
||||
}
|
||||
|
||||
- (void)teardown {
|
||||
if (self.sharedCache) {
|
||||
delete self.sharedCache;
|
||||
self.sharedCache = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)dealloc {
|
||||
[self.retainers removeAllObjects];
|
||||
[self teardown];
|
||||
}
|
||||
|
||||
+ (mbgl::SQLiteCache *)obtainSharedCacheWithObject:(NSObject *)object {
|
||||
return [[MGLFileCache sharedInstance] obtainSharedCacheWithObject:object];
|
||||
}
|
||||
|
||||
- (mbgl::SQLiteCache *)obtainSharedCacheWithObject:(NSObject *)object {
|
||||
assert([[NSThread currentThread] isMainThread]);
|
||||
if (!self.sharedCache) {
|
||||
self.sharedCache = new mbgl::SQLiteCache(defaultCacheDatabasePath());
|
||||
}
|
||||
[self.retainers addObject:object];
|
||||
return self.sharedCache;
|
||||
}
|
||||
|
||||
+ (void)releaseSharedCacheForObject:(NSObject *)object {
|
||||
return [[MGLFileCache sharedInstance] releaseSharedCacheForObject:object];
|
||||
}
|
||||
|
||||
- (void)releaseSharedCacheForObject:(NSObject *)object {
|
||||
assert([[NSThread currentThread] isMainThread]);
|
||||
if ([self.retainers containsObject:object]) {
|
||||
[self.retainers removeObject:object];
|
||||
}
|
||||
if ([self.retainers count] == 0) {
|
||||
[self teardown];
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -13,6 +13,7 @@
|
||||
#include <mbgl/annotation/sprite_image.hpp>
|
||||
#include <mbgl/platform/platform.hpp>
|
||||
#include <mbgl/platform/darwin/reachability.h>
|
||||
#include <mbgl/storage/sqlite_cache.hpp>
|
||||
#include <mbgl/storage/default_file_source.hpp>
|
||||
#include <mbgl/storage/network_status.hpp>
|
||||
#include <mbgl/util/geo.hpp>
|
||||
@@ -28,7 +29,6 @@
|
||||
#import "NSException+MGLAdditions.h"
|
||||
#import "MGLUserLocationAnnotationView.h"
|
||||
#import "MGLUserLocation_Private.h"
|
||||
#import "MGLFileCache.h"
|
||||
#import "MGLAccountManager_Private.h"
|
||||
#import "MGLMapboxEvents.h"
|
||||
|
||||
@@ -60,16 +60,6 @@ static NSURL *MGLURLForBundledStyleNamed(NSString *styleName)
|
||||
return [NSURL URLWithString:[NSString stringWithFormat:@"asset://styles/%@.json", styleName]];
|
||||
}
|
||||
|
||||
CGFloat MGLRadiansFromDegrees(CLLocationDegrees degrees)
|
||||
{
|
||||
return degrees * M_PI / 180;
|
||||
}
|
||||
|
||||
CLLocationDegrees MGLDegreesFromRadians(CGFloat radians)
|
||||
{
|
||||
return radians * 180 / M_PI;
|
||||
}
|
||||
|
||||
mbgl::util::UnitBezier MGLUnitBezierForMediaTimingFunction(CAMediaTimingFunction *function)
|
||||
{
|
||||
if ( ! function)
|
||||
@@ -122,12 +112,14 @@ mbgl::util::UnitBezier MGLUnitBezierForMediaTimingFunction(CAMediaTimingFunction
|
||||
{
|
||||
mbgl::Map *_mbglMap;
|
||||
MBGLView *_mbglView;
|
||||
std::shared_ptr<mbgl::SQLiteCache> _mbglFileCache;
|
||||
mbgl::DefaultFileSource *_mbglFileSource;
|
||||
BOOL _isWaitingForRedundantReachableNotification;
|
||||
|
||||
|
||||
NS_MUTABLE_ARRAY_OF(NSURL *) *_bundledStyleURLs;
|
||||
|
||||
BOOL _isWaitingForRedundantReachableNotification;
|
||||
BOOL _isTargetingInterfaceBuilder;
|
||||
|
||||
CLLocationDegrees _pendingLatitude;
|
||||
CLLocationDegrees _pendingLongitude;
|
||||
}
|
||||
@@ -235,14 +227,24 @@ std::chrono::steady_clock::duration secondsAsDuration(float duration)
|
||||
self.backgroundColor = [UIColor clearColor];
|
||||
self.clipsToBounds = YES;
|
||||
|
||||
// setup mbgl map
|
||||
//
|
||||
// setup mbgl view
|
||||
const float scaleFactor = [UIScreen instancesRespondToSelector:@selector(nativeScale)] ? [[UIScreen mainScreen] nativeScale] : [[UIScreen mainScreen] scale];
|
||||
_mbglView = new MBGLView(self, scaleFactor);
|
||||
_mbglFileSource = new mbgl::DefaultFileSource([MGLFileCache obtainSharedCacheWithObject:self]);
|
||||
|
||||
// Start paused
|
||||
// setup mbgl cache & file source
|
||||
NSString *fileCachePath = @"";
|
||||
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
|
||||
if ([paths count] != 0) {
|
||||
NSString *libraryDirectory = [paths objectAtIndex:0];
|
||||
fileCachePath = [libraryDirectory stringByAppendingPathComponent:@"cache.db"];
|
||||
}
|
||||
_mbglFileCache = mbgl::SharedSQLiteCache::get([fileCachePath UTF8String]);
|
||||
_mbglFileSource = new mbgl::DefaultFileSource(_mbglFileCache.get());
|
||||
|
||||
// setup mbgl map
|
||||
_mbglMap = new mbgl::Map(*_mbglView, *_mbglFileSource, mbgl::MapMode::Continuous);
|
||||
|
||||
// start paused if in IB
|
||||
if (_isTargetingInterfaceBuilder || background) {
|
||||
self.dormant = YES;
|
||||
_mbglMap->pause();
|
||||
@@ -368,7 +370,8 @@ std::chrono::steady_clock::duration secondsAsDuration(float duration)
|
||||
{
|
||||
_quickZoom = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleQuickZoomGesture:)];
|
||||
_quickZoom.numberOfTapsRequired = 1;
|
||||
_quickZoom.minimumPressDuration = 0.25;
|
||||
_quickZoom.minimumPressDuration = 0;
|
||||
[_quickZoom requireGestureRecognizerToFail:doubleTap];
|
||||
[self addGestureRecognizer:_quickZoom];
|
||||
}
|
||||
|
||||
@@ -475,8 +478,6 @@ std::chrono::steady_clock::duration secondsAsDuration(float duration)
|
||||
_mbglFileSource = nullptr;
|
||||
}
|
||||
|
||||
[MGLFileCache releaseSharedCacheForObject:self];
|
||||
|
||||
if (_mbglView)
|
||||
{
|
||||
delete _mbglView;
|
||||
@@ -1336,9 +1337,9 @@ std::chrono::steady_clock::duration secondsAsDuration(float duration)
|
||||
}
|
||||
else if (quickZoom.state == UIGestureRecognizerStateChanged)
|
||||
{
|
||||
CGFloat distance = self.quickZoomStart - [quickZoom locationInView:quickZoom.view].y;
|
||||
CGFloat distance = [quickZoom locationInView:quickZoom.view].y - self.quickZoomStart;
|
||||
|
||||
CGFloat newZoom = log2f(self.scale) + (distance / 100);
|
||||
CGFloat newZoom = log2f(self.scale) + (distance / 75);
|
||||
|
||||
if (newZoom < _mbglMap->getMinZoom()) return;
|
||||
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
const CGFloat MGLUserLocationAnnotationDotSize = 22.0;
|
||||
const CGFloat MGLUserLocationAnnotationHaloSize = 115.0;
|
||||
|
||||
const CGFloat MGLUserLocationAnnotationPuckSize = 45.0;
|
||||
const CGFloat MGLUserLocationAnnotationArrowSize = MGLUserLocationAnnotationPuckSize * 0.6;
|
||||
|
||||
@interface MGLUserLocationAnnotationView ()
|
||||
|
||||
@property (nonatomic, readwrite) CALayer *haloLayer;
|
||||
@@ -18,15 +21,21 @@ const CGFloat MGLUserLocationAnnotationHaloSize = 115.0;
|
||||
|
||||
@implementation MGLUserLocationAnnotationView
|
||||
{
|
||||
BOOL _puckModeActivated;
|
||||
|
||||
CALayer *_puckDot;
|
||||
CAShapeLayer *_puckArrow;
|
||||
|
||||
CALayer *_headingIndicatorLayer;
|
||||
CAShapeLayer *_headingIndicatorMaskLayer;
|
||||
CALayer *_accuracyRingLayer;
|
||||
CALayer *_dotBorderLayer;
|
||||
CALayer *_dotLayer;
|
||||
|
||||
|
||||
double _oldHeadingAccuracy;
|
||||
CLLocationAccuracy _oldHorizontalAccuracy;
|
||||
double _oldZoom;
|
||||
double _oldPitch;
|
||||
}
|
||||
|
||||
- (instancetype)initWithFrame:(CGRect)frame
|
||||
@@ -37,7 +46,9 @@ const CGFloat MGLUserLocationAnnotationHaloSize = 115.0;
|
||||
|
||||
- (instancetype)initInMapView:(MGLMapView *)mapView
|
||||
{
|
||||
if (self = [super initWithFrame:CGRectMake(0, 0, MGLUserLocationAnnotationDotSize, MGLUserLocationAnnotationDotSize)])
|
||||
CGFloat frameSize = (mapView.userTrackingMode == MGLUserTrackingModeFollowWithCourse) ? MGLUserLocationAnnotationPuckSize : MGLUserLocationAnnotationDotSize;
|
||||
|
||||
if (self = [super initWithFrame:CGRectMake(0, 0, frameSize, frameSize)])
|
||||
{
|
||||
self.annotation = [[MGLUserLocation alloc] initWithMapView:mapView];
|
||||
_mapView = mapView;
|
||||
@@ -55,189 +66,336 @@ const CGFloat MGLUserLocationAnnotationHaloSize = 115.0;
|
||||
|
||||
- (void)setTintColor:(UIColor *)tintColor
|
||||
{
|
||||
if (_accuracyRingLayer)
|
||||
if (_puckModeActivated)
|
||||
{
|
||||
_accuracyRingLayer.backgroundColor = [tintColor CGColor];
|
||||
_puckArrow.fillColor = [tintColor CGColor];
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_accuracyRingLayer)
|
||||
{
|
||||
_accuracyRingLayer.backgroundColor = [tintColor CGColor];
|
||||
}
|
||||
|
||||
_haloLayer.backgroundColor = [tintColor CGColor];
|
||||
_dotLayer.backgroundColor = [tintColor CGColor];
|
||||
|
||||
_headingIndicatorLayer.contents = (__bridge id)[[self headingIndicatorTintedGradientImage] CGImage];
|
||||
}
|
||||
|
||||
_haloLayer.backgroundColor = [tintColor CGColor];
|
||||
_dotLayer.backgroundColor = [tintColor CGColor];
|
||||
|
||||
_headingIndicatorLayer.contents = (__bridge id)[[self headingIndicatorTintedGradientImage] CGImage];
|
||||
}
|
||||
|
||||
- (void)setupLayers
|
||||
{
|
||||
if (CLLocationCoordinate2DIsValid(self.annotation.coordinate))
|
||||
{
|
||||
// update heading indicator
|
||||
//
|
||||
if (_headingIndicatorLayer)
|
||||
{
|
||||
_headingIndicatorLayer.hidden = !(_mapView.userTrackingMode == MGLUserTrackingModeFollowWithHeading ||
|
||||
_mapView.userTrackingMode == MGLUserTrackingModeFollowWithCourse);
|
||||
|
||||
if (_oldHeadingAccuracy != self.annotation.heading.headingAccuracy)
|
||||
{
|
||||
// recalculate the clipping mask based on updated accuracy
|
||||
_headingIndicatorMaskLayer.path = [[self headingIndicatorClippingMask] CGPath];
|
||||
(_mapView.userTrackingMode == MGLUserTrackingModeFollowWithCourse) ? [self drawPuck] : [self drawDot];
|
||||
[self updatePitch];
|
||||
}
|
||||
}
|
||||
|
||||
_oldHeadingAccuracy = self.annotation.heading.headingAccuracy;
|
||||
}
|
||||
}
|
||||
|
||||
// heading indicator (tinted, semi-circle)
|
||||
//
|
||||
if ( ! _headingIndicatorLayer && self.annotation.heading.headingAccuracy)
|
||||
- (void)updatePitch
|
||||
{
|
||||
if (self.mapView.camera.pitch != _oldPitch)
|
||||
{
|
||||
CATransform3D t = CATransform3DRotate(CATransform3DIdentity, MGLRadiansFromDegrees(self.mapView.camera.pitch), 1.0, 0, 0);
|
||||
self.layer.sublayerTransform = t;
|
||||
|
||||
[self updateFaux3DEffect];
|
||||
|
||||
_oldPitch = self.mapView.camera.pitch;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)updateFaux3DEffect
|
||||
{
|
||||
CGFloat pitch = MGLRadiansFromDegrees(self.mapView.camera.pitch);
|
||||
|
||||
if (_puckDot)
|
||||
{
|
||||
_puckDot.shadowOffset = CGSizeMake(0, fmaxf(pitch * 10.f, 1.f));
|
||||
_puckDot.shadowRadius = fmaxf(pitch * 5.f, 0.75f);
|
||||
}
|
||||
|
||||
if (_dotBorderLayer)
|
||||
{
|
||||
_dotBorderLayer.shadowOffset = CGSizeMake(0.f, pitch * 10.f);
|
||||
_dotBorderLayer.shadowRadius = fmaxf(pitch * 5.f, 3.f);
|
||||
}
|
||||
|
||||
if (_dotLayer)
|
||||
{
|
||||
_dotLayer.zPosition = pitch * 2.f;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)drawPuck
|
||||
{
|
||||
if ( ! _puckModeActivated)
|
||||
{
|
||||
self.layer.sublayers = nil;
|
||||
|
||||
_headingIndicatorLayer = nil;
|
||||
_headingIndicatorMaskLayer = nil;
|
||||
_accuracyRingLayer = nil;
|
||||
_haloLayer = nil;
|
||||
_dotBorderLayer = nil;
|
||||
_dotLayer = nil;
|
||||
}
|
||||
|
||||
// background dot (white with black shadow)
|
||||
//
|
||||
if ( ! _puckDot)
|
||||
{
|
||||
_puckDot = [self circleLayerWithSize:MGLUserLocationAnnotationPuckSize];
|
||||
_puckDot.backgroundColor = [[UIColor whiteColor] CGColor];
|
||||
_puckDot.shadowColor = [[UIColor blackColor] CGColor];
|
||||
_puckDot.shadowOpacity = 0.25;
|
||||
|
||||
if (self.mapView.camera.pitch)
|
||||
{
|
||||
CGFloat headingIndicatorSize = MGLUserLocationAnnotationHaloSize;
|
||||
|
||||
_headingIndicatorLayer = [CALayer layer];
|
||||
_headingIndicatorLayer.bounds = CGRectMake(0, 0, headingIndicatorSize, headingIndicatorSize);
|
||||
_headingIndicatorLayer.position = CGPointMake(super.bounds.size.width / 2.0, super.bounds.size.height / 2.0);
|
||||
_headingIndicatorLayer.contents = (__bridge id)[[self headingIndicatorTintedGradientImage] CGImage];
|
||||
_headingIndicatorLayer.contentsGravity = kCAGravityBottom;
|
||||
_headingIndicatorLayer.contentsScale = [UIScreen mainScreen].scale;
|
||||
_headingIndicatorLayer.opacity = 0.4;
|
||||
_headingIndicatorLayer.shouldRasterize = YES;
|
||||
_headingIndicatorLayer.rasterizationScale = [UIScreen mainScreen].scale;
|
||||
_headingIndicatorLayer.drawsAsynchronously = YES;
|
||||
|
||||
[self.layer insertSublayer:_headingIndicatorLayer below:_dotBorderLayer];
|
||||
[self updateFaux3DEffect];
|
||||
}
|
||||
|
||||
// heading indicator accuracy mask (fan-shaped)
|
||||
//
|
||||
if ( ! _headingIndicatorMaskLayer && self.annotation.heading.headingAccuracy)
|
||||
else
|
||||
{
|
||||
_headingIndicatorMaskLayer = [CAShapeLayer layer];
|
||||
_headingIndicatorMaskLayer.frame = _headingIndicatorLayer.bounds;
|
||||
_puckDot.shadowOffset = CGSizeMake(0, 1);
|
||||
_puckDot.shadowRadius = 0.75;
|
||||
}
|
||||
|
||||
[self.layer addSublayer:_puckDot];
|
||||
}
|
||||
|
||||
// arrow
|
||||
//
|
||||
if ( ! _puckArrow)
|
||||
{
|
||||
_puckArrow = [CAShapeLayer layer];
|
||||
_puckArrow.path = [[self puckArrow] CGPath];
|
||||
_puckArrow.fillColor = [_mapView.tintColor CGColor];
|
||||
_puckArrow.bounds = CGRectMake(0, 0, MGLUserLocationAnnotationArrowSize, MGLUserLocationAnnotationArrowSize);
|
||||
_puckArrow.position = CGPointMake(super.bounds.size.width / 2.0, super.bounds.size.height / 2.0);
|
||||
_puckArrow.shouldRasterize = YES;
|
||||
_puckArrow.rasterizationScale = [UIScreen mainScreen].scale;
|
||||
_puckArrow.drawsAsynchronously = YES;
|
||||
|
||||
[self.layer addSublayer:_puckArrow];
|
||||
}
|
||||
|
||||
if ( ! _puckModeActivated)
|
||||
{
|
||||
_puckModeActivated = YES;
|
||||
|
||||
[self updateFaux3DEffect];
|
||||
}
|
||||
}
|
||||
|
||||
- (UIBezierPath *)puckArrow
|
||||
{
|
||||
CGFloat max = MGLUserLocationAnnotationArrowSize;
|
||||
|
||||
UIBezierPath *bezierPath = UIBezierPath.bezierPath;
|
||||
[bezierPath moveToPoint: CGPointMake(max * 0.5, 0)];
|
||||
[bezierPath addLineToPoint: CGPointMake(max * 0.1, max)];
|
||||
[bezierPath addLineToPoint: CGPointMake(max * 0.5, max * 0.65)];
|
||||
[bezierPath addLineToPoint: CGPointMake(max * 0.9, max)];
|
||||
[bezierPath addLineToPoint: CGPointMake(max * 0.5, 0)];
|
||||
[bezierPath closePath];
|
||||
|
||||
return bezierPath;
|
||||
}
|
||||
|
||||
- (void)drawDot
|
||||
{
|
||||
if (_puckModeActivated)
|
||||
{
|
||||
self.layer.sublayers = nil;
|
||||
|
||||
_puckDot = nil;
|
||||
_puckArrow = nil;
|
||||
}
|
||||
|
||||
// update heading indicator
|
||||
//
|
||||
if (_headingIndicatorLayer)
|
||||
{
|
||||
_headingIndicatorLayer.hidden = !(_mapView.userTrackingMode == MGLUserTrackingModeFollowWithHeading ||
|
||||
_mapView.userTrackingMode == MGLUserTrackingModeFollowWithCourse);
|
||||
|
||||
if (_oldHeadingAccuracy != self.annotation.heading.headingAccuracy)
|
||||
{
|
||||
// recalculate the clipping mask based on updated accuracy
|
||||
_headingIndicatorMaskLayer.path = [[self headingIndicatorClippingMask] CGPath];
|
||||
|
||||
// apply the mask to the halo-radius-sized gradient layer
|
||||
_headingIndicatorLayer.mask = _headingIndicatorMaskLayer;
|
||||
|
||||
_oldHeadingAccuracy = self.annotation.heading.headingAccuracy;
|
||||
}
|
||||
}
|
||||
|
||||
// heading indicator (tinted, semi-circle)
|
||||
//
|
||||
if ( ! _headingIndicatorLayer && self.annotation.heading.headingAccuracy)
|
||||
{
|
||||
CGFloat headingIndicatorSize = MGLUserLocationAnnotationHaloSize;
|
||||
|
||||
_headingIndicatorLayer = [CALayer layer];
|
||||
_headingIndicatorLayer.bounds = CGRectMake(0, 0, headingIndicatorSize, headingIndicatorSize);
|
||||
_headingIndicatorLayer.position = CGPointMake(super.bounds.size.width / 2.0, super.bounds.size.height / 2.0);
|
||||
_headingIndicatorLayer.contents = (__bridge id)[[self headingIndicatorTintedGradientImage] CGImage];
|
||||
_headingIndicatorLayer.contentsGravity = kCAGravityBottom;
|
||||
_headingIndicatorLayer.contentsScale = [UIScreen mainScreen].scale;
|
||||
_headingIndicatorLayer.opacity = 0.4;
|
||||
_headingIndicatorLayer.shouldRasterize = YES;
|
||||
_headingIndicatorLayer.rasterizationScale = [UIScreen mainScreen].scale;
|
||||
_headingIndicatorLayer.drawsAsynchronously = YES;
|
||||
|
||||
[self.layer insertSublayer:_headingIndicatorLayer below:_dotBorderLayer];
|
||||
}
|
||||
|
||||
// heading indicator accuracy mask (fan-shaped)
|
||||
//
|
||||
if ( ! _headingIndicatorMaskLayer && self.annotation.heading.headingAccuracy)
|
||||
{
|
||||
_headingIndicatorMaskLayer = [CAShapeLayer layer];
|
||||
_headingIndicatorMaskLayer.frame = _headingIndicatorLayer.bounds;
|
||||
_headingIndicatorMaskLayer.path = [[self headingIndicatorClippingMask] CGPath];
|
||||
|
||||
// apply the mask to the halo-radius-sized gradient layer
|
||||
_headingIndicatorLayer.mask = _headingIndicatorMaskLayer;
|
||||
|
||||
_oldHeadingAccuracy = self.annotation.heading.headingAccuracy;
|
||||
}
|
||||
|
||||
// update accuracy ring (if zoom or horizontal accuracy have changed)
|
||||
//
|
||||
if (_accuracyRingLayer && (_oldZoom != self.mapView.zoomLevel || _oldHorizontalAccuracy != self.annotation.location.horizontalAccuracy))
|
||||
{
|
||||
CGFloat accuracyRingSize = [self calculateAccuracyRingSize];
|
||||
|
||||
// update accuracy ring (if zoom or horizontal accuracy have changed)
|
||||
//
|
||||
if (_accuracyRingLayer && (_oldZoom != self.mapView.zoomLevel || _oldHorizontalAccuracy != self.annotation.location.horizontalAccuracy))
|
||||
// only show the accuracy ring if it won't be obscured by the location dot
|
||||
if (accuracyRingSize > MGLUserLocationAnnotationDotSize + 15)
|
||||
{
|
||||
CGFloat accuracyRingSize = [self calculateAccuracyRingSize];
|
||||
|
||||
// only show the accuracy ring if it won't be obscured by the location dot
|
||||
if (accuracyRingSize > MGLUserLocationAnnotationDotSize + 15)
|
||||
{
|
||||
_accuracyRingLayer.hidden = NO;
|
||||
_accuracyRingLayer.bounds = CGRectMake(0, 0, accuracyRingSize, accuracyRingSize);
|
||||
_accuracyRingLayer.cornerRadius = accuracyRingSize / 2;
|
||||
|
||||
// match the halo to the accuracy ring
|
||||
_haloLayer.bounds = _accuracyRingLayer.bounds;
|
||||
_haloLayer.cornerRadius = _accuracyRingLayer.cornerRadius;
|
||||
_haloLayer.shouldRasterize = NO;
|
||||
}
|
||||
else
|
||||
{
|
||||
_accuracyRingLayer.hidden = YES;
|
||||
|
||||
_haloLayer.bounds = CGRectMake(0, 0, MGLUserLocationAnnotationHaloSize, MGLUserLocationAnnotationHaloSize);
|
||||
_haloLayer.cornerRadius = MGLUserLocationAnnotationHaloSize / 2.0;
|
||||
_haloLayer.shouldRasterize = YES;
|
||||
_haloLayer.rasterizationScale = [UIScreen mainScreen].scale;
|
||||
}
|
||||
|
||||
// store accuracy and zoom so we're not redrawing unchanged location updates
|
||||
_oldHorizontalAccuracy = self.annotation.location.horizontalAccuracy;
|
||||
_oldZoom = self.mapView.zoomLevel;
|
||||
_accuracyRingLayer.hidden = NO;
|
||||
_accuracyRingLayer.bounds = CGRectMake(0, 0, accuracyRingSize, accuracyRingSize);
|
||||
_accuracyRingLayer.cornerRadius = accuracyRingSize / 2;
|
||||
|
||||
// match the halo to the accuracy ring
|
||||
_haloLayer.bounds = _accuracyRingLayer.bounds;
|
||||
_haloLayer.cornerRadius = _accuracyRingLayer.cornerRadius;
|
||||
_haloLayer.shouldRasterize = NO;
|
||||
}
|
||||
|
||||
// accuracy ring (circular, tinted, mostly-transparent)
|
||||
//
|
||||
if ( ! _accuracyRingLayer && self.annotation.location.horizontalAccuracy)
|
||||
else
|
||||
{
|
||||
CGFloat accuracyRingSize = [self calculateAccuracyRingSize];
|
||||
_accuracyRingLayer = [self circleLayerWithSize:accuracyRingSize];
|
||||
_accuracyRingLayer.backgroundColor = [_mapView.tintColor CGColor];
|
||||
_accuracyRingLayer.opacity = 0.1;
|
||||
_accuracyRingLayer.shouldRasterize = NO;
|
||||
_accuracyRingLayer.allowsGroupOpacity = NO;
|
||||
|
||||
[self.layer addSublayer:_accuracyRingLayer];
|
||||
_accuracyRingLayer.hidden = YES;
|
||||
|
||||
_haloLayer.bounds = CGRectMake(0, 0, MGLUserLocationAnnotationHaloSize, MGLUserLocationAnnotationHaloSize);
|
||||
_haloLayer.cornerRadius = MGLUserLocationAnnotationHaloSize / 2.0;
|
||||
_haloLayer.shouldRasterize = YES;
|
||||
_haloLayer.rasterizationScale = [UIScreen mainScreen].scale;
|
||||
}
|
||||
|
||||
// store accuracy and zoom so we're not redrawing unchanged location updates
|
||||
_oldHorizontalAccuracy = self.annotation.location.horizontalAccuracy;
|
||||
_oldZoom = self.mapView.zoomLevel;
|
||||
}
|
||||
|
||||
// accuracy ring (circular, tinted, mostly-transparent)
|
||||
//
|
||||
if ( ! _accuracyRingLayer && self.annotation.location.horizontalAccuracy)
|
||||
{
|
||||
CGFloat accuracyRingSize = [self calculateAccuracyRingSize];
|
||||
_accuracyRingLayer = [self circleLayerWithSize:accuracyRingSize];
|
||||
_accuracyRingLayer.backgroundColor = [_mapView.tintColor CGColor];
|
||||
_accuracyRingLayer.opacity = 0.1;
|
||||
_accuracyRingLayer.shouldRasterize = NO;
|
||||
_accuracyRingLayer.allowsGroupOpacity = NO;
|
||||
|
||||
// expanding sonar-like pulse (circular, tinted, fades out)
|
||||
//
|
||||
if ( ! _haloLayer)
|
||||
[self.layer addSublayer:_accuracyRingLayer];
|
||||
}
|
||||
|
||||
// expanding sonar-like pulse (circular, tinted, fades out)
|
||||
//
|
||||
if ( ! _haloLayer)
|
||||
{
|
||||
_haloLayer = [self circleLayerWithSize:MGLUserLocationAnnotationHaloSize];
|
||||
_haloLayer.backgroundColor = [_mapView.tintColor CGColor];
|
||||
_haloLayer.allowsGroupOpacity = NO;
|
||||
_haloLayer.zPosition = -0.1f;
|
||||
|
||||
// set defaults for the animations
|
||||
CAAnimationGroup *animationGroup = [self loopingAnimationGroupWithDuration:3.0];
|
||||
|
||||
// scale out radially with initial acceleration
|
||||
CAKeyframeAnimation *boundsAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale.xy"];
|
||||
boundsAnimation.values = @[@0, @0.35, @1];
|
||||
boundsAnimation.keyTimes = @[@0, @0.2, @1];
|
||||
|
||||
// go transparent as scaled out, start semi-opaque
|
||||
CAKeyframeAnimation *opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
|
||||
opacityAnimation.values = @[@0.4, @0.4, @0];
|
||||
opacityAnimation.keyTimes = @[@0, @0.2, @1];
|
||||
|
||||
animationGroup.animations = @[boundsAnimation, opacityAnimation];
|
||||
|
||||
[_haloLayer addAnimation:animationGroup forKey:@"animateTransformAndOpacity"];
|
||||
|
||||
[self.layer addSublayer:_haloLayer];
|
||||
}
|
||||
|
||||
// background dot (white with black shadow)
|
||||
//
|
||||
if ( ! _dotBorderLayer)
|
||||
{
|
||||
_dotBorderLayer = [self circleLayerWithSize:MGLUserLocationAnnotationDotSize];
|
||||
_dotBorderLayer.backgroundColor = [[UIColor whiteColor] CGColor];
|
||||
_dotBorderLayer.shadowColor = [[UIColor blackColor] CGColor];
|
||||
_dotBorderLayer.shadowOpacity = 0.25;
|
||||
|
||||
if (self.mapView.camera.pitch)
|
||||
{
|
||||
_haloLayer = [self circleLayerWithSize:MGLUserLocationAnnotationHaloSize];
|
||||
_haloLayer.backgroundColor = [_mapView.tintColor CGColor];
|
||||
_haloLayer.allowsGroupOpacity = NO;
|
||||
|
||||
// set defaults for the animations
|
||||
CAAnimationGroup *animationGroup = [self loopingAnimationGroupWithDuration:3.0];
|
||||
|
||||
// scale out radially with initial acceleration
|
||||
CAKeyframeAnimation *boundsAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale.xy"];
|
||||
boundsAnimation.values = @[@0, @0.35, @1];
|
||||
boundsAnimation.keyTimes = @[@0, @0.2, @1];
|
||||
|
||||
// go transparent as scaled out, start semi-opaque
|
||||
CAKeyframeAnimation *opacityAnimation = [CAKeyframeAnimation animationWithKeyPath:@"opacity"];
|
||||
opacityAnimation.values = @[@0.4, @0.4, @0];
|
||||
opacityAnimation.keyTimes = @[@0, @0.2, @1];
|
||||
|
||||
animationGroup.animations = @[boundsAnimation, opacityAnimation];
|
||||
|
||||
[_haloLayer addAnimation:animationGroup forKey:@"animateTransformAndOpacity"];
|
||||
|
||||
[self.layer addSublayer:_haloLayer];
|
||||
[self updateFaux3DEffect];
|
||||
}
|
||||
|
||||
// background dot (white with black shadow)
|
||||
//
|
||||
if ( ! _dotBorderLayer)
|
||||
else
|
||||
{
|
||||
_dotBorderLayer = [self circleLayerWithSize:MGLUserLocationAnnotationDotSize];
|
||||
_dotBorderLayer.backgroundColor = [[UIColor whiteColor] CGColor];
|
||||
_dotBorderLayer.shadowColor = [[UIColor blackColor] CGColor];
|
||||
_dotBorderLayer.shadowOffset = CGSizeMake(0, 0);
|
||||
_dotBorderLayer.shadowRadius = 3;
|
||||
_dotBorderLayer.shadowOpacity = 0.25;
|
||||
|
||||
[self.layer addSublayer:_dotBorderLayer];
|
||||
}
|
||||
|
||||
// inner dot (pulsing, tinted)
|
||||
//
|
||||
if ( ! _dotLayer)
|
||||
{
|
||||
_dotLayer = [self circleLayerWithSize:MGLUserLocationAnnotationDotSize * 0.75];
|
||||
_dotLayer.backgroundColor = [_mapView.tintColor CGColor];
|
||||
_dotLayer.shouldRasterize = NO;
|
||||
|
||||
// set defaults for the animations
|
||||
CAAnimationGroup *animationGroup = [self loopingAnimationGroupWithDuration:1.5];
|
||||
animationGroup.autoreverses = YES;
|
||||
animationGroup.fillMode = kCAFillModeBoth;
|
||||
|
||||
// scale the dot up and down
|
||||
CABasicAnimation *pulseAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.xy"];
|
||||
pulseAnimation.fromValue = @0.8;
|
||||
pulseAnimation.toValue = @1;
|
||||
|
||||
// fade opacity in and out, subtly
|
||||
CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
|
||||
opacityAnimation.fromValue = @0.8;
|
||||
opacityAnimation.toValue = @1;
|
||||
|
||||
animationGroup.animations = @[pulseAnimation, opacityAnimation];
|
||||
|
||||
[_dotLayer addAnimation:animationGroup forKey:@"animateTransformAndOpacity"];
|
||||
|
||||
[self.layer addSublayer:_dotLayer];
|
||||
}
|
||||
|
||||
[self.layer addSublayer:_dotBorderLayer];
|
||||
}
|
||||
|
||||
// inner dot (pulsing, tinted)
|
||||
//
|
||||
if ( ! _dotLayer)
|
||||
{
|
||||
_dotLayer = [self circleLayerWithSize:MGLUserLocationAnnotationDotSize * 0.75];
|
||||
_dotLayer.backgroundColor = [_mapView.tintColor CGColor];
|
||||
_dotLayer.shouldRasterize = NO;
|
||||
|
||||
// set defaults for the animations
|
||||
CAAnimationGroup *animationGroup = [self loopingAnimationGroupWithDuration:1.5];
|
||||
animationGroup.autoreverses = YES;
|
||||
animationGroup.fillMode = kCAFillModeBoth;
|
||||
|
||||
// scale the dot up and down
|
||||
CABasicAnimation *pulseAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale.xy"];
|
||||
pulseAnimation.fromValue = @0.8;
|
||||
pulseAnimation.toValue = @1;
|
||||
|
||||
// fade opacity in and out, subtly
|
||||
CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
|
||||
opacityAnimation.fromValue = @0.8;
|
||||
opacityAnimation.toValue = @1;
|
||||
|
||||
animationGroup.animations = @[pulseAnimation, opacityAnimation];
|
||||
|
||||
[_dotLayer addAnimation:animationGroup forKey:@"animateTransformAndOpacity"];
|
||||
|
||||
[self.layer addSublayer:_dotLayer];
|
||||
}
|
||||
|
||||
if (_puckModeActivated)
|
||||
{
|
||||
_puckModeActivated = NO;
|
||||
|
||||
[self updateFaux3DEffect];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,7 +408,7 @@ const CGFloat MGLUserLocationAnnotationHaloSize = 115.0;
|
||||
circleLayer.shouldRasterize = YES;
|
||||
circleLayer.rasterizationScale = [UIScreen mainScreen].scale;
|
||||
circleLayer.drawsAsynchronously = YES;
|
||||
|
||||
|
||||
return circleLayer;
|
||||
}
|
||||
|
||||
@@ -261,7 +419,7 @@ const CGFloat MGLUserLocationAnnotationHaloSize = 115.0;
|
||||
animationGroup.repeatCount = INFINITY;
|
||||
animationGroup.removedOnCompletion = NO;
|
||||
animationGroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
|
||||
|
||||
|
||||
return animationGroup;
|
||||
}
|
||||
|
||||
@@ -269,65 +427,65 @@ const CGFloat MGLUserLocationAnnotationHaloSize = 115.0;
|
||||
{
|
||||
CGFloat latRadians = self.annotation.coordinate.latitude * M_PI / 180.0f;
|
||||
CGFloat pixelRadius = self.annotation.location.horizontalAccuracy / cos(latRadians) / [self.mapView metersPerPixelAtLatitude:self.annotation.coordinate.latitude];
|
||||
|
||||
|
||||
return pixelRadius * 2;
|
||||
}
|
||||
|
||||
- (UIImage *)headingIndicatorTintedGradientImage
|
||||
{
|
||||
UIImage *image;
|
||||
|
||||
|
||||
CGFloat haloRadius = MGLUserLocationAnnotationHaloSize / 2.0;
|
||||
|
||||
|
||||
UIGraphicsBeginImageContextWithOptions(CGSizeMake(MGLUserLocationAnnotationHaloSize, haloRadius), NO, 0);
|
||||
|
||||
|
||||
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
|
||||
CGContextRef context = UIGraphicsGetCurrentContext();
|
||||
|
||||
|
||||
// gradient from the tint color to no-alpha tint color
|
||||
CGFloat gradientLocations[] = {0.0, 1.0};
|
||||
CGGradientRef gradient = CGGradientCreateWithColors(
|
||||
colorSpace, (__bridge CFArrayRef)@[(id)[_mapView.tintColor CGColor],
|
||||
(id)[[_mapView.tintColor colorWithAlphaComponent:0] CGColor]], gradientLocations);
|
||||
|
||||
colorSpace, (__bridge CFArrayRef)@[(id)[_mapView.tintColor CGColor],
|
||||
(id)[[_mapView.tintColor colorWithAlphaComponent:0] CGColor]], gradientLocations);
|
||||
|
||||
// draw the gradient from the center point to the edge (full halo radius)
|
||||
CGPoint centerPoint = CGPointMake(haloRadius, haloRadius);
|
||||
CGContextDrawRadialGradient(context, gradient,
|
||||
centerPoint, 0.0,
|
||||
centerPoint, haloRadius,
|
||||
nil);
|
||||
|
||||
|
||||
image = UIGraphicsGetImageFromCurrentImageContext();
|
||||
UIGraphicsEndImageContext();
|
||||
|
||||
|
||||
CGGradientRelease(gradient);
|
||||
CGColorSpaceRelease(colorSpace);
|
||||
|
||||
|
||||
return image;
|
||||
}
|
||||
|
||||
- (UIBezierPath *)headingIndicatorClippingMask
|
||||
{
|
||||
CGFloat accuracy = self.annotation.heading.headingAccuracy;
|
||||
|
||||
|
||||
// size the mask using exagerated accuracy, but keep within a good display range
|
||||
CGFloat clippingDegrees = 90 - (accuracy * 1.5);
|
||||
clippingDegrees = fmin(clippingDegrees, 55);
|
||||
clippingDegrees = fmax(clippingDegrees, 10);
|
||||
|
||||
|
||||
CGRect ovalRect = CGRectMake(0, 0, MGLUserLocationAnnotationHaloSize, MGLUserLocationAnnotationHaloSize);
|
||||
UIBezierPath *ovalPath = UIBezierPath.bezierPath;
|
||||
|
||||
|
||||
// clip the oval to ± incoming accuracy degrees (converted to radians), from the top
|
||||
[ovalPath addArcWithCenter:CGPointMake(CGRectGetMidX(ovalRect), CGRectGetMidY(ovalRect))
|
||||
radius:CGRectGetWidth(ovalRect) / 2.0
|
||||
startAngle:(-180 + clippingDegrees) * M_PI / 180
|
||||
endAngle:-clippingDegrees * M_PI / 180
|
||||
clockwise:YES];
|
||||
|
||||
|
||||
[ovalPath addLineToPoint:CGPointMake(CGRectGetMidX(ovalRect), CGRectGetMidY(ovalRect))];
|
||||
[ovalPath closePath];
|
||||
|
||||
|
||||
return ovalPath;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
# 2.0.0
|
||||
|
||||
- Integrates Node.js bindings into core mapbox-gl-native project.
|
||||
- Integrates Node.js bindings into core mapbox-gl-native project. ([#2179](https://github.com/mapbox/mapbox-gl-native/pull/2179))
|
||||
- Requires an options object argument to `new mbgl.Map()`
|
||||
(with required `request` and optional `cancel` methods),
|
||||
drops `mbgl.FileSource`.
|
||||
drops `mbgl.FileSource`. ([mapbox/node-mapbox-gl-native#143](https://github.com/mapbox/node-mapbox-gl-native/pull/143))
|
||||
- Changes `request` semantics to pass a second, callback argument instead
|
||||
of needing to call `req.respond`. ([#2299](https://github.com/mapbox/mapbox-gl-native/pull/2299))
|
||||
- Requires numerical `ratio` in `mbgl.Map` options argument.
|
||||
Map pixel ratio is now immutable and can no longer be set with
|
||||
render options.
|
||||
render options. ([`a8d9b92`](https://github.com/mapbox/mapbox-gl-native/commit/a8d9b921d71a91d7f8eff82e5a584aaab8b7d1c6), [#1799](https://github.com/mapbox/mapbox-gl-native/pull/1799))
|
||||
- `map.render` now returns a raw image buffer instead of an object with
|
||||
`width`, `height` and `pixels` properties. ([#2262](https://github.com/mapbox/mapbox-gl-native/pull/2262))
|
||||
- Adds support for rendering v8 styles.
|
||||
- No longer load resources before a render request is made.
|
||||
- No longer loads resources before a render request is made. ([`55d25a8`](https://github.com/mapbox/mapbox-gl-native/commit/55d25a80a77c06ef5e66acc0d8518867b03fe8a4))
|
||||
- Adds io.js v3.x support. ([#2261](https://github.com/mapbox/mapbox-gl-native/pull/2261))
|
||||
|
||||
# 1.1.3
|
||||
|
||||
|
||||
@@ -92,22 +92,22 @@ The `kind` is an enum and defined in [`mbgl.Resource`](https://github.com/mapbox
|
||||
|
||||
It has no significance for anything but serves as a hint to your implemention as to what sort of resource to expect. E.g., your implementation could choose caching strategies based on the expected file type.
|
||||
|
||||
THe `request` implementation should pass uncompressed data to `req.respond`. If you are downloading assets from a source that applies gzip transport encoding, the implementation must decompress the results before passing them on.
|
||||
The `request` implementation should pass uncompressed data to `callback`. If you are downloading assets from a source that applies gzip transport encoding, the implementation must decompress the results before passing them on.
|
||||
|
||||
A sample implementation that reads files from disk would look like the following:
|
||||
|
||||
```js
|
||||
var map = new mbgl.Map({
|
||||
request: function(req) {
|
||||
request: function(req, callback) {
|
||||
fs.readFile(path.join('base/path', req.url), function(err, data) {
|
||||
req.respond(err, { data: data });
|
||||
callback(err, { data: data });
|
||||
});
|
||||
},
|
||||
ratio: 1.0
|
||||
});
|
||||
```
|
||||
|
||||
This is a very barebones implementation and you'll probably want a better implementation. E.g. it passes the url verbatim to the file system, but you'd want add some logic that normalizes `http` URLs. You'll notice that once your implementation has obtained the requested file, you have to deliver it to the requestee by calling `req.respond()`, which takes either an error object or `null` and an object with several settings:
|
||||
This is a very barebones implementation and you'll probably want a better implementation. E.g. it passes the url verbatim to the file system, but you'd want add some logic that normalizes `http` URLs. You'll notice that once your implementation has obtained the requested file, you have to deliver it to the requestee by calling `callback()`, which takes either an error object or `null` and an object with several settings:
|
||||
|
||||
```js
|
||||
{
|
||||
@@ -125,14 +125,14 @@ var mbgl = require('mapbox-gl-native');
|
||||
var request = require('request');
|
||||
|
||||
var map = new mbgl.Map({
|
||||
request: function(req) {
|
||||
request: function(req, callback) {
|
||||
request({
|
||||
url: req.url,
|
||||
encoding: null,
|
||||
gzip: true
|
||||
}, function (err, res, body) {
|
||||
if (err) {
|
||||
req.respond(err);
|
||||
callback(err);
|
||||
} else if (res.statusCode == 200) {
|
||||
var response = {};
|
||||
|
||||
@@ -142,9 +142,9 @@ var map = new mbgl.Map({
|
||||
|
||||
response.data = body;
|
||||
|
||||
req.respond(null, response);
|
||||
callback(null, response);
|
||||
} else {
|
||||
req.respond(new Error(JSON.parse(body).message));
|
||||
callback(new Error(JSON.parse(body).message));
|
||||
}
|
||||
});
|
||||
},
|
||||
@@ -164,7 +164,7 @@ var request = require('request');
|
||||
var url = require('url');
|
||||
|
||||
var map = new mbgl.Map({
|
||||
request: function(req) {
|
||||
request: function(req, callback) {
|
||||
var opts = {
|
||||
url: req.url,
|
||||
encoding: null,
|
||||
@@ -177,7 +177,7 @@ var map = new mbgl.Map({
|
||||
|
||||
request(opts, function (err, res, body) {
|
||||
if (err) {
|
||||
req.respond(err);
|
||||
callback(err);
|
||||
} else if (res.statusCode == 200) {
|
||||
var response = {};
|
||||
|
||||
@@ -187,9 +187,9 @@ var map = new mbgl.Map({
|
||||
|
||||
response.data = body;
|
||||
|
||||
req.respond(null, response);
|
||||
callback(null, response);
|
||||
} else {
|
||||
req.respond(new Error(JSON.parse(body).message));
|
||||
callback(new Error(JSON.parse(body).message));
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@ struct NodeFileSource::Action {
|
||||
mbgl::Resource const resource;
|
||||
};
|
||||
|
||||
NodeFileSource::NodeFileSource(v8::Handle<v8::Object> options_) :
|
||||
NodeFileSource::NodeFileSource(v8::Local<v8::Object> options_) :
|
||||
queue(new Queue(uv_default_loop(), [this](Action &action) {
|
||||
if (action.type == Action::Add) {
|
||||
processAdd(action.resource);
|
||||
@@ -20,7 +20,7 @@ NodeFileSource::NodeFileSource(v8::Handle<v8::Object> options_) :
|
||||
}
|
||||
}))
|
||||
{
|
||||
NanAssignPersistent(options, options_->ToObject());
|
||||
options.Reset(options_);
|
||||
|
||||
// Make sure that the queue doesn't block the loop from exiting.
|
||||
queue->unref();
|
||||
@@ -30,7 +30,7 @@ NodeFileSource::~NodeFileSource() {
|
||||
queue->stop();
|
||||
queue = nullptr;
|
||||
|
||||
NanDisposePersistent(options);
|
||||
options.Reset();
|
||||
}
|
||||
|
||||
mbgl::Request* NodeFileSource::request(const mbgl::Resource& resource, uv_loop_t* loop, Callback callback) {
|
||||
@@ -68,44 +68,33 @@ void NodeFileSource::cancel(mbgl::Request* req) {
|
||||
}
|
||||
|
||||
void NodeFileSource::processAdd(const mbgl::Resource& resource) {
|
||||
NanScope();
|
||||
Nan::HandleScope scope;
|
||||
|
||||
// Make sure the loop stays alive as long as request is pending.
|
||||
if (pending.empty()) {
|
||||
queue->ref();
|
||||
}
|
||||
|
||||
auto requestHandle = NanNew<v8::Object>(NodeRequest::Create(this, resource));
|
||||
auto requestHandle = NodeRequest::Create(this, resource)->ToObject();
|
||||
pending.emplace(resource, requestHandle);
|
||||
|
||||
v8::Persistent<v8::Object> requestPersistent;
|
||||
NanAssignPersistent(requestPersistent, requestHandle);
|
||||
pending.emplace(resource, std::move(requestPersistent));
|
||||
auto callback = Nan::GetFunction(Nan::New<v8::FunctionTemplate>(NodeRequest::Respond, requestHandle)).ToLocalChecked();
|
||||
callback->SetName(Nan::New("respond").ToLocalChecked());
|
||||
|
||||
#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
|
||||
auto requestFunction = v8::Local<v8::Object>::New(v8::Isolate::GetCurrent(), options)->Get(NanNew("request")).As<v8::Function>();
|
||||
#else
|
||||
auto requestFunction = options->Get(NanNew("request")).As<v8::Function>();
|
||||
#endif
|
||||
|
||||
v8::Local<v8::Value> argv[] = { requestHandle };
|
||||
NanMakeCallback(NanGetCurrentContext()->Global(), requestFunction, 1, argv);
|
||||
v8::Local<v8::Value> argv[] = { requestHandle, callback };
|
||||
Nan::MakeCallback(Nan::New(options), "request", 2, argv);
|
||||
}
|
||||
|
||||
void NodeFileSource::processCancel(const mbgl::Resource& resource) {
|
||||
NanScope();
|
||||
Nan::HandleScope scope;
|
||||
|
||||
auto it = pending.find(resource);
|
||||
if (it == pending.end()) {
|
||||
// The response callback was already fired. There is no point in calling the cancelation
|
||||
// callback because the request is already completed.
|
||||
} else {
|
||||
#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
|
||||
auto requestHandle = v8::Local<v8::Object>::New(v8::Isolate::GetCurrent(), it->second);
|
||||
v8::Local<v8::Object> requestHandle = Nan::New(it->second);
|
||||
it->second.Reset();
|
||||
#else
|
||||
auto requestHandle = NanNew<v8::Object>(it->second);
|
||||
NanDisposePersistent(it->second);
|
||||
#endif
|
||||
pending.erase(it);
|
||||
|
||||
// Make sure the the loop can exit when there are no pending requests.
|
||||
@@ -113,20 +102,13 @@ void NodeFileSource::processCancel(const mbgl::Resource& resource) {
|
||||
queue->unref();
|
||||
}
|
||||
|
||||
#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
|
||||
auto optionsObject = v8::Local<v8::Object>::New(v8::Isolate::GetCurrent(), options);
|
||||
if (optionsObject->Has(NanNew("cancel"))) {
|
||||
auto cancelFunction = optionsObject->Get(NanNew("cancel")).As<v8::Function>();
|
||||
#else
|
||||
if (options->Has(NanNew("cancel"))) {
|
||||
auto cancelFunction = options->Get(NanNew("cancel")).As<v8::Function>();
|
||||
#endif
|
||||
if (Nan::Has(Nan::New(options), Nan::New("cancel").ToLocalChecked()).FromJust()) {
|
||||
v8::Local<v8::Value> argv[] = { requestHandle };
|
||||
NanMakeCallback(NanGetCurrentContext()->Global(), cancelFunction, 1, argv);
|
||||
Nan::MakeCallback(Nan::New(options), "cancel", 1, argv);
|
||||
}
|
||||
|
||||
// Set the request handle in the request wrapper handle to null
|
||||
node::ObjectWrap::Unwrap<NodeRequest>(requestHandle)->cancel();
|
||||
Nan::ObjectWrap::Unwrap<NodeRequest>(requestHandle)->cancel();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,11 +116,7 @@ void NodeFileSource::notify(const mbgl::Resource& resource, const std::shared_pt
|
||||
// First, remove the request, since it might be destructed at any point now.
|
||||
auto it = pending.find(resource);
|
||||
if (it != pending.end()) {
|
||||
#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
|
||||
it->second.Reset();
|
||||
#else
|
||||
NanDisposePersistent(it->second);
|
||||
#endif
|
||||
pending.erase(it);
|
||||
|
||||
// Make sure the the loop can exit when there are no pending requests.
|
||||
|
||||
@@ -5,8 +5,6 @@
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
#pragma GCC diagnostic ignored "-Wshadow"
|
||||
#include <node.h>
|
||||
#include <node_version.h>
|
||||
#include <nan.h>
|
||||
#pragma GCC diagnostic pop
|
||||
|
||||
@@ -20,7 +18,7 @@ namespace util { template <typename T> class AsyncQueue; }
|
||||
|
||||
class NodeFileSource : public mbgl::FileSource {
|
||||
public:
|
||||
NodeFileSource(v8::Handle<v8::Object>);
|
||||
NodeFileSource(v8::Local<v8::Object>);
|
||||
~NodeFileSource();
|
||||
|
||||
mbgl::Request* request(const mbgl::Resource&, uv_loop_t*, Callback);
|
||||
@@ -36,14 +34,10 @@ private:
|
||||
void processAdd(const mbgl::Resource&);
|
||||
void processCancel(const mbgl::Resource&);
|
||||
|
||||
v8::Persistent<v8::Object> options;
|
||||
Nan::Persistent<v8::Object> options;
|
||||
|
||||
private:
|
||||
#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION)
|
||||
std::unordered_map<mbgl::Resource, v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object>>, mbgl::Resource::Hash> pending;
|
||||
#else
|
||||
std::unordered_map<mbgl::Resource, v8::Persistent<v8::Object>, mbgl::Resource::Hash> pending;
|
||||
#endif
|
||||
std::unordered_map<mbgl::Resource, Nan::Persistent<v8::Object>, mbgl::Resource::Hash> pending;
|
||||
|
||||
// The observers list will hold pointers to all the requests waiting
|
||||
// for a particular resource. The access must be guarded by a mutex
|
||||
|
||||
@@ -16,27 +16,35 @@ struct NodeLogObserver::LogMessage {
|
||||
text(text_) {}
|
||||
};
|
||||
|
||||
NodeLogObserver::NodeLogObserver(v8::Handle<v8::Object> target)
|
||||
NodeLogObserver::NodeLogObserver(v8::Local<v8::Object> target)
|
||||
: queue(new Queue(uv_default_loop(), [this](LogMessage &message) {
|
||||
NanScope();
|
||||
Nan::HandleScope scope;
|
||||
|
||||
auto msg = Nan::New<v8::Object>();
|
||||
|
||||
Nan::Set(msg, Nan::New("class").ToLocalChecked(),
|
||||
Nan::New(mbgl::EventClass(message.event).c_str()).ToLocalChecked());
|
||||
|
||||
Nan::Set(msg, Nan::New("severity").ToLocalChecked(),
|
||||
Nan::New(mbgl::EventSeverityClass(message.severity).c_str()).ToLocalChecked());
|
||||
|
||||
auto msg = NanNew<v8::Object>();
|
||||
msg->Set(NanNew("class"), NanNew(mbgl::EventClass(message.event).c_str()));
|
||||
msg->Set(NanNew("severity"), NanNew(mbgl::EventSeverityClass(message.severity).c_str()));
|
||||
if (message.code != -1) {
|
||||
msg->Set(NanNew("code"), NanNew<v8::Number>(message.code));
|
||||
}
|
||||
if (!message.text.empty()) {
|
||||
msg->Set(NanNew("text"), NanNew(message.text));
|
||||
Nan::Set(msg, Nan::New("code").ToLocalChecked(),
|
||||
Nan::New<v8::Number>(message.code));
|
||||
}
|
||||
|
||||
v8::Local<v8::Value> argv[] = { NanNew("message"), msg };
|
||||
auto handle = NanNew<v8::Object>(module);
|
||||
auto emit = handle->Get(NanNew("emit"))->ToObject();
|
||||
emit->CallAsFunction(handle, 2, argv);
|
||||
if (!message.text.empty()) {
|
||||
Nan::Set(msg, Nan::New("text").ToLocalChecked(),
|
||||
Nan::New(message.text).ToLocalChecked());
|
||||
}
|
||||
|
||||
v8::Local<v8::Value> argv[] = { Nan::New("message").ToLocalChecked(), msg };
|
||||
auto handle = Nan::New<v8::Object>(module);
|
||||
auto emit = Nan::Get(handle, Nan::New("emit").ToLocalChecked()).ToLocalChecked()->ToObject();
|
||||
Nan::CallAsFunction(emit, handle, 2, argv);
|
||||
})) {
|
||||
NanScope();
|
||||
NanAssignPersistent(module, target);
|
||||
Nan::HandleScope scope;
|
||||
module.Reset(target);
|
||||
|
||||
// Don't keep the event loop alive.
|
||||
queue->unref();
|
||||
@@ -44,6 +52,7 @@ NodeLogObserver::NodeLogObserver(v8::Handle<v8::Object> target)
|
||||
|
||||
NodeLogObserver::~NodeLogObserver() {
|
||||
queue->stop();
|
||||
module.Reset();
|
||||
}
|
||||
|
||||
bool NodeLogObserver::onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string &text) {
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
#pragma GCC diagnostic ignored "-Wshadow"
|
||||
#include <node.h>
|
||||
#include <nan.h>
|
||||
#pragma GCC diagnostic pop
|
||||
|
||||
@@ -15,14 +14,14 @@ namespace util { template <typename T> class AsyncQueue; }
|
||||
|
||||
class NodeLogObserver : public mbgl::Log::Observer {
|
||||
public:
|
||||
NodeLogObserver(v8::Handle<v8::Object> target);
|
||||
NodeLogObserver(v8::Local<v8::Object> target);
|
||||
~NodeLogObserver();
|
||||
|
||||
// Log::Observer implementation
|
||||
virtual bool onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string &msg) override;
|
||||
|
||||
private:
|
||||
v8::Persistent<v8::Object> module;
|
||||
Nan::Persistent<v8::Object> module;
|
||||
|
||||
struct LogMessage;
|
||||
using Queue = util::AsyncQueue<LogMessage>;
|
||||
|
||||
@@ -21,7 +21,7 @@ struct NodeMap::RenderOptions {
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Static Node Methods
|
||||
|
||||
v8::Persistent<v8::FunctionTemplate> NodeMap::constructorTemplate;
|
||||
Nan::Persistent<v8::Function> NodeMap::constructor;
|
||||
|
||||
static std::shared_ptr<mbgl::HeadlessDisplay> sharedDisplay() {
|
||||
static auto display = std::make_shared<mbgl::HeadlessDisplay>();
|
||||
@@ -32,127 +32,137 @@ const static char* releasedMessage() {
|
||||
return "Map resources have already been released";
|
||||
}
|
||||
|
||||
void NodeMap::Init(v8::Handle<v8::Object> target) {
|
||||
NanScope();
|
||||
NAN_MODULE_INIT(NodeMap::Init) {
|
||||
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
|
||||
|
||||
v8::Local<v8::FunctionTemplate> t = NanNew<v8::FunctionTemplate>(New);
|
||||
tpl->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
tpl->SetClassName(Nan::New("Map").ToLocalChecked());
|
||||
|
||||
t->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
t->SetClassName(NanNew("Map"));
|
||||
Nan::SetPrototypeMethod(tpl, "load", Load);
|
||||
Nan::SetPrototypeMethod(tpl, "render", Render);
|
||||
Nan::SetPrototypeMethod(tpl, "release", Release);
|
||||
|
||||
NODE_SET_PROTOTYPE_METHOD(t, "load", Load);
|
||||
NODE_SET_PROTOTYPE_METHOD(t, "render", Render);
|
||||
NODE_SET_PROTOTYPE_METHOD(t, "release", Release);
|
||||
|
||||
NanAssignPersistent(constructorTemplate, t);
|
||||
|
||||
target->Set(NanNew("Map"), t->GetFunction());
|
||||
constructor.Reset(tpl->GetFunction());
|
||||
Nan::Set(target, Nan::New("Map").ToLocalChecked(), tpl->GetFunction());
|
||||
|
||||
// Initialize display connection on module load.
|
||||
sharedDisplay();
|
||||
}
|
||||
|
||||
NAN_METHOD(NodeMap::New) {
|
||||
NanScope();
|
||||
|
||||
if (!args.IsConstructCall()) {
|
||||
return NanThrowTypeError("Use the new operator to create new Map objects");
|
||||
if (!info.IsConstructCall()) {
|
||||
return Nan::ThrowTypeError("Use the new operator to create new Map objects");
|
||||
}
|
||||
|
||||
if (args.Length() < 1 || !args[0]->IsObject()) {
|
||||
return NanThrowTypeError("Requires an options object as first argument");
|
||||
if (info.Length() < 1 || !info[0]->IsObject()) {
|
||||
return Nan::ThrowTypeError("Requires an options object as first argument");
|
||||
}
|
||||
|
||||
auto options = args[0]->ToObject();
|
||||
auto options = info[0]->ToObject();
|
||||
|
||||
// Check that 'request', 'cancel' and 'ratio' are defined.
|
||||
if (!options->Has(NanNew("request")) || !options->Get(NanNew("request"))->IsFunction()) {
|
||||
return NanThrowError("Options object must have a 'request' method");
|
||||
}
|
||||
if (options->Has(NanNew("cancel")) && !options->Get(NanNew("cancel"))->IsFunction()) {
|
||||
return NanThrowError("Options object 'cancel' property must be a function");
|
||||
if (!Nan::Has(options, Nan::New("request").ToLocalChecked()).FromJust()
|
||||
|| !Nan::Get(options, Nan::New("request").ToLocalChecked()).ToLocalChecked()->IsFunction()) {
|
||||
return Nan::ThrowError("Options object must have a 'request' method");
|
||||
}
|
||||
|
||||
if (!options->Has(NanNew("ratio")) || !options->Get(NanNew("ratio"))->IsNumber()) {
|
||||
return NanThrowError("Options object must have a numerical 'ratio' property");
|
||||
if ( Nan::Has(options, Nan::New("cancel").ToLocalChecked()).FromJust()
|
||||
&& !Nan::Get(options, Nan::New("cancel").ToLocalChecked()).ToLocalChecked()->IsFunction()) {
|
||||
return Nan::ThrowError("Options object 'cancel' property must be a function");
|
||||
}
|
||||
|
||||
if (!Nan::Has(options, Nan::New("ratio").ToLocalChecked()).FromJust()
|
||||
|| !Nan::Get(options, Nan::New("ratio").ToLocalChecked()).ToLocalChecked()->IsNumber()) {
|
||||
return Nan::ThrowError("Options object must have a numerical 'ratio' property");
|
||||
}
|
||||
|
||||
try {
|
||||
auto nodeMap = new NodeMap(options);
|
||||
nodeMap->Wrap(args.This());
|
||||
nodeMap->Wrap(info.This());
|
||||
} catch(std::exception &ex) {
|
||||
return NanThrowError(ex.what());
|
||||
return Nan::ThrowError(ex.what());
|
||||
}
|
||||
|
||||
NanReturnValue(args.This());
|
||||
info.GetReturnValue().Set(info.This());
|
||||
}
|
||||
|
||||
const std::string StringifyStyle(v8::Handle<v8::Value> styleHandle) {
|
||||
NanScope();
|
||||
const std::string StringifyStyle(v8::Local<v8::Value> styleHandle) {
|
||||
Nan::HandleScope scope;
|
||||
|
||||
auto JSON = NanGetCurrentContext()->Global()->Get(NanNew("JSON"))->ToObject();
|
||||
auto stringify = v8::Handle<v8::Function>::Cast(JSON->Get(NanNew("stringify")));
|
||||
v8::Local<v8::Object> JSON = Nan::Get(
|
||||
Nan::GetCurrentContext()->Global(),
|
||||
Nan::New("JSON").ToLocalChecked()).ToLocalChecked()->ToObject();
|
||||
|
||||
return *NanUtf8String(stringify->Call(JSON, 1, &styleHandle));
|
||||
return *Nan::Utf8String(Nan::MakeCallback(JSON, "stringify", 1, &styleHandle));
|
||||
}
|
||||
|
||||
NAN_METHOD(NodeMap::Load) {
|
||||
NanScope();
|
||||
auto nodeMap = Nan::ObjectWrap::Unwrap<NodeMap>(info.Holder());
|
||||
|
||||
auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());
|
||||
|
||||
if (!nodeMap->isValid()) return NanThrowError(releasedMessage());
|
||||
if (!nodeMap->isValid()) return Nan::ThrowError(releasedMessage());
|
||||
|
||||
// Reset the flag as this could be the second time
|
||||
// we are calling this (being the previous successful).
|
||||
nodeMap->loaded = false;
|
||||
|
||||
if (args.Length() < 1) {
|
||||
return NanThrowError("Requires a map style as first argument");
|
||||
if (info.Length() < 1) {
|
||||
return Nan::ThrowError("Requires a map style as first argument");
|
||||
}
|
||||
|
||||
std::string style;
|
||||
|
||||
if (args[0]->IsObject()) {
|
||||
style = StringifyStyle(args[0]);
|
||||
} else if (args[0]->IsString()) {
|
||||
style = *NanUtf8String(args[0]);
|
||||
if (info[0]->IsObject()) {
|
||||
style = StringifyStyle(info[0]);
|
||||
} else if (info[0]->IsString()) {
|
||||
style = *Nan::Utf8String(info[0]);
|
||||
} else {
|
||||
return NanThrowTypeError("First argument must be a string or object");
|
||||
return Nan::ThrowTypeError("First argument must be a string or object");
|
||||
}
|
||||
|
||||
try {
|
||||
nodeMap->map->setStyleJSON(style, ".");
|
||||
} catch (const std::exception &ex) {
|
||||
return NanThrowError(ex.what());
|
||||
return Nan::ThrowError(ex.what());
|
||||
}
|
||||
|
||||
nodeMap->loaded = true;
|
||||
|
||||
NanReturnUndefined();
|
||||
info.GetReturnValue().SetUndefined();
|
||||
}
|
||||
|
||||
std::unique_ptr<NodeMap::RenderOptions> NodeMap::ParseOptions(v8::Local<v8::Object> obj) {
|
||||
NanScope();
|
||||
Nan::HandleScope scope;
|
||||
|
||||
auto options = std::make_unique<RenderOptions>();
|
||||
|
||||
if (obj->Has(NanNew("zoom"))) { options->zoom = obj->Get(NanNew("zoom"))->NumberValue(); }
|
||||
if (obj->Has(NanNew("bearing"))) { options->bearing = obj->Get(NanNew("bearing"))->NumberValue(); }
|
||||
if (obj->Has(NanNew("center"))) {
|
||||
auto center = obj->Get(NanNew("center")).As<v8::Array>();
|
||||
if (center->Length() > 0) { options->latitude = center->Get(0)->NumberValue(); }
|
||||
if (center->Length() > 1) { options->longitude = center->Get(1)->NumberValue(); }
|
||||
if (Nan::Has(obj, Nan::New("zoom").ToLocalChecked()).FromJust()) {
|
||||
options->zoom = Nan::Get(obj, Nan::New("zoom").ToLocalChecked()).ToLocalChecked()->NumberValue();
|
||||
}
|
||||
if (obj->Has(NanNew("width"))) { options->width = obj->Get(NanNew("width"))->IntegerValue(); }
|
||||
if (obj->Has(NanNew("height"))) { options->height = obj->Get(NanNew("height"))->IntegerValue(); }
|
||||
|
||||
if (obj->Has(NanNew("classes"))) {
|
||||
auto classes = obj->Get(NanNew("classes"))->ToObject().As<v8::Array>();
|
||||
if (Nan::Has(obj, Nan::New("bearing").ToLocalChecked()).FromJust()) {
|
||||
options->bearing = Nan::Get(obj, Nan::New("bearing").ToLocalChecked()).ToLocalChecked()->NumberValue();
|
||||
}
|
||||
|
||||
if (Nan::Has(obj, Nan::New("center").ToLocalChecked()).FromJust()) {
|
||||
auto center = Nan::Get(obj, Nan::New("center").ToLocalChecked()).ToLocalChecked().As<v8::Array>();
|
||||
if (center->Length() > 0) { options->latitude = Nan::Get(center, 0).ToLocalChecked()->NumberValue(); }
|
||||
if (center->Length() > 1) { options->longitude = Nan::Get(center, 1).ToLocalChecked()->NumberValue(); }
|
||||
}
|
||||
|
||||
if (Nan::Has(obj, Nan::New("width").ToLocalChecked()).FromJust()) {
|
||||
options->width = Nan::Get(obj, Nan::New("width").ToLocalChecked()).ToLocalChecked()->IntegerValue();
|
||||
}
|
||||
|
||||
if (Nan::Has(obj, Nan::New("height").ToLocalChecked()).FromJust()) {
|
||||
options->height = Nan::Get(obj, Nan::New("height").ToLocalChecked()).ToLocalChecked()->IntegerValue();
|
||||
}
|
||||
|
||||
if (Nan::Has(obj, Nan::New("classes").ToLocalChecked()).FromJust()) {
|
||||
auto classes = Nan::Get(obj, Nan::New("classes").ToLocalChecked()).ToLocalChecked()->ToObject().As<v8::Array>();
|
||||
const int length = classes->Length();
|
||||
options->classes.reserve(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
options->classes.push_back(std::string { *NanUtf8String(classes->Get(i)->ToString()) });
|
||||
options->classes.push_back(std::string { *Nan::Utf8String(Nan::Get(classes, i).ToLocalChecked()->ToString()) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,37 +170,39 @@ std::unique_ptr<NodeMap::RenderOptions> NodeMap::ParseOptions(v8::Local<v8::Obje
|
||||
}
|
||||
|
||||
NAN_METHOD(NodeMap::Render) {
|
||||
NanScope();
|
||||
auto nodeMap = Nan::ObjectWrap::Unwrap<NodeMap>(info.Holder());
|
||||
|
||||
auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());
|
||||
if (!nodeMap->isValid()) return Nan::ThrowError(releasedMessage());
|
||||
|
||||
if (!nodeMap->isValid()) return NanThrowError(releasedMessage());
|
||||
|
||||
if (args.Length() <= 0 || !args[0]->IsObject()) {
|
||||
return NanThrowTypeError("First argument must be an options object");
|
||||
if (info.Length() <= 0 || !info[0]->IsObject()) {
|
||||
return Nan::ThrowTypeError("First argument must be an options object");
|
||||
}
|
||||
|
||||
if (args.Length() <= 1 || !args[1]->IsFunction()) {
|
||||
return NanThrowTypeError("Second argument must be a callback function");
|
||||
if (info.Length() <= 1 || !info[1]->IsFunction()) {
|
||||
return Nan::ThrowTypeError("Second argument must be a callback function");
|
||||
}
|
||||
|
||||
if (!nodeMap->isLoaded()) {
|
||||
return NanThrowTypeError("Style is not loaded");
|
||||
return Nan::ThrowTypeError("Style is not loaded");
|
||||
}
|
||||
|
||||
auto options = ParseOptions(args[0]->ToObject());
|
||||
if (nodeMap->callback) {
|
||||
return Nan::ThrowError("Map is currently rendering an image");
|
||||
}
|
||||
|
||||
auto options = ParseOptions(info[0]->ToObject());
|
||||
|
||||
assert(!nodeMap->callback);
|
||||
assert(!nodeMap->image);
|
||||
nodeMap->callback = std::unique_ptr<NanCallback>(new NanCallback(args[1].As<v8::Function>()));
|
||||
nodeMap->callback = std::make_unique<Nan::Callback>(info[1].As<v8::Function>());
|
||||
|
||||
try {
|
||||
nodeMap->startRender(std::move(options));
|
||||
} catch (mbgl::util::Exception &ex) {
|
||||
return NanThrowError(ex.what());
|
||||
return Nan::ThrowError(ex.what());
|
||||
}
|
||||
|
||||
NanReturnUndefined();
|
||||
info.GetReturnValue().SetUndefined();
|
||||
}
|
||||
|
||||
void NodeMap::startRender(std::unique_ptr<NodeMap::RenderOptions> options) {
|
||||
@@ -221,7 +233,7 @@ void NodeMap::startRender(std::unique_ptr<NodeMap::RenderOptions> options) {
|
||||
}
|
||||
|
||||
void NodeMap::renderFinished() {
|
||||
NanScope();
|
||||
Nan::HandleScope scope;
|
||||
|
||||
// We're done with this render call, so we're unrefing so that the loop could close.
|
||||
uv_unref(reinterpret_cast<uv_handle_t *>(async));
|
||||
@@ -249,7 +261,7 @@ void NodeMap::renderFinished() {
|
||||
}
|
||||
|
||||
v8::Local<v8::Value> argv[] = {
|
||||
NanError(errorMessage.c_str())
|
||||
Nan::Error(errorMessage.c_str())
|
||||
};
|
||||
|
||||
// This must be empty to be prepared for the next render call.
|
||||
@@ -258,7 +270,7 @@ void NodeMap::renderFinished() {
|
||||
|
||||
cb->Call(1, argv);
|
||||
} else if (img) {
|
||||
v8::Local<v8::Object> pixels = NanNewBufferHandle(
|
||||
v8::Local<v8::Object> pixels = Nan::NewBuffer(
|
||||
reinterpret_cast<char *>(img->pixels.get()),
|
||||
size_t(img->width) * size_t(img->height) * sizeof(mbgl::StillImage::Pixel),
|
||||
|
||||
@@ -267,36 +279,34 @@ void NodeMap::renderFinished() {
|
||||
delete reinterpret_cast<const mbgl::StillImage *>(hint);
|
||||
},
|
||||
const_cast<mbgl::StillImage *>(img.get())
|
||||
);
|
||||
).ToLocalChecked();
|
||||
img.release();
|
||||
|
||||
v8::Local<v8::Value> argv[] = {
|
||||
NanNull(),
|
||||
pixels,
|
||||
Nan::Null(),
|
||||
pixels
|
||||
};
|
||||
cb->Call(2, argv);
|
||||
} else {
|
||||
v8::Local<v8::Value> argv[] = {
|
||||
NanError("Didn't get an image")
|
||||
Nan::Error("Didn't get an image")
|
||||
};
|
||||
cb->Call(1, argv);
|
||||
}
|
||||
}
|
||||
|
||||
NAN_METHOD(NodeMap::Release) {
|
||||
NanScope();
|
||||
auto nodeMap = Nan::ObjectWrap::Unwrap<NodeMap>(info.Holder());
|
||||
|
||||
auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());
|
||||
|
||||
if (!nodeMap->isValid()) return NanThrowError(releasedMessage());
|
||||
if (!nodeMap->isValid()) return Nan::ThrowError(releasedMessage());
|
||||
|
||||
try {
|
||||
nodeMap->release();
|
||||
} catch (const std::exception &ex) {
|
||||
return NanThrowError(ex.what());
|
||||
return Nan::ThrowError(ex.what());
|
||||
}
|
||||
|
||||
NanReturnUndefined();
|
||||
info.GetReturnValue().SetUndefined();
|
||||
}
|
||||
|
||||
void NodeMap::release() {
|
||||
@@ -315,8 +325,11 @@ void NodeMap::release() {
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Instance
|
||||
|
||||
NodeMap::NodeMap(v8::Handle<v8::Object> options) :
|
||||
view(sharedDisplay(), options->Get(NanNew("ratio"))->NumberValue()),
|
||||
NodeMap::NodeMap(v8::Local<v8::Object> options) :
|
||||
view(sharedDisplay(), [&] {
|
||||
Nan::HandleScope scope;
|
||||
return Nan::Get(options, Nan::New("ratio").ToLocalChecked()).ToLocalChecked()->NumberValue();
|
||||
}()),
|
||||
fs(options),
|
||||
map(std::make_unique<mbgl::Map>(view, fs, mbgl::MapMode::Still)),
|
||||
async(new uv_async_t) {
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
#pragma GCC diagnostic ignored "-Wshadow"
|
||||
#include <node.h>
|
||||
#include <nan.h>
|
||||
#pragma GCC diagnostic pop
|
||||
|
||||
@@ -16,14 +15,13 @@
|
||||
|
||||
namespace node_mbgl {
|
||||
|
||||
class NodeMap : public node::ObjectWrap {
|
||||
class NodeMap : public Nan::ObjectWrap {
|
||||
public:
|
||||
struct RenderOptions;
|
||||
class RenderWorker;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Static Node Methods
|
||||
public:
|
||||
static void Init(v8::Handle<v8::Object> target);
|
||||
static NAN_MODULE_INIT(Init);
|
||||
|
||||
static NAN_METHOD(New);
|
||||
static NAN_METHOD(Load);
|
||||
static NAN_METHOD(Render);
|
||||
@@ -37,24 +35,20 @@ public:
|
||||
inline bool isLoaded() { return loaded; }
|
||||
inline bool isValid() { return valid; }
|
||||
|
||||
static std::unique_ptr<NodeMap::RenderOptions> ParseOptions(v8::Local<v8::Object> obj);
|
||||
static std::unique_ptr<NodeMap::RenderOptions> ParseOptions(v8::Local<v8::Object>);
|
||||
static Nan::Persistent<v8::Function> constructor;
|
||||
|
||||
static v8::Persistent<v8::FunctionTemplate> constructorTemplate;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Instance
|
||||
private:
|
||||
NodeMap(v8::Handle<v8::Object>);
|
||||
NodeMap(v8::Local<v8::Object>);
|
||||
~NodeMap();
|
||||
|
||||
private:
|
||||
mbgl::HeadlessView view;
|
||||
NodeFileSource fs;
|
||||
std::unique_ptr<mbgl::Map> map;
|
||||
|
||||
std::exception_ptr error;
|
||||
std::unique_ptr<const mbgl::StillImage> image;
|
||||
std::unique_ptr<NanCallback> callback;
|
||||
std::unique_ptr<Nan::Callback> callback;
|
||||
|
||||
// Async for delivering the notifications of render completion.
|
||||
uv_async_t *async;
|
||||
|
||||
@@ -9,30 +9,57 @@
|
||||
#include "node_log.hpp"
|
||||
#include "node_request.hpp"
|
||||
|
||||
void RegisterModule(v8::Handle<v8::Object> exports) {
|
||||
NanScope();
|
||||
|
||||
node_mbgl::NodeMap::Init(exports);
|
||||
node_mbgl::NodeRequest::Init(exports);
|
||||
NAN_MODULE_INIT(RegisterModule) {
|
||||
node_mbgl::NodeMap::Init(target);
|
||||
node_mbgl::NodeRequest::Init(target);
|
||||
|
||||
// Exports Resource constants.
|
||||
auto ConstantProperty = static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete);
|
||||
auto resource = NanNew<v8::Object>();
|
||||
resource->ForceSet(NanNew("Unknown"), NanNew(mbgl::Resource::Unknown), ConstantProperty);
|
||||
resource->ForceSet(NanNew("Style"), NanNew(mbgl::Resource::Style), ConstantProperty);
|
||||
resource->ForceSet(NanNew("Source"), NanNew(mbgl::Resource::Source), ConstantProperty);
|
||||
resource->ForceSet(NanNew("Tile"), NanNew(mbgl::Resource::Tile), ConstantProperty);
|
||||
resource->ForceSet(NanNew("Glyphs"), NanNew(mbgl::Resource::Glyphs), ConstantProperty);
|
||||
resource->ForceSet(NanNew("SpriteImage"), NanNew(mbgl::Resource::SpriteImage), ConstantProperty);
|
||||
resource->ForceSet(NanNew("SpriteJSON"), NanNew(mbgl::Resource::SpriteJSON), ConstantProperty);
|
||||
exports->ForceSet(NanNew("Resource"), resource, ConstantProperty);
|
||||
v8::Local<v8::Object> resource = Nan::New<v8::Object>();
|
||||
|
||||
// Make the exported object inerhit from process.EventEmitter
|
||||
auto process = NanGetCurrentContext()->Global()->Get(NanNew("process"))->ToObject();
|
||||
auto EventEmitter = process->Get(NanNew("EventEmitter"))->ToObject();
|
||||
exports->SetPrototype(EventEmitter->Get(NanNew("prototype")));
|
||||
Nan::Set(resource,
|
||||
Nan::New("Unknown").ToLocalChecked(),
|
||||
Nan::New(mbgl::Resource::Unknown));
|
||||
|
||||
mbgl::Log::setObserver(std::make_unique<node_mbgl::NodeLogObserver>(exports));
|
||||
Nan::Set(resource,
|
||||
Nan::New("Style").ToLocalChecked(),
|
||||
Nan::New(mbgl::Resource::Style));
|
||||
|
||||
Nan::Set(resource,
|
||||
Nan::New("Source").ToLocalChecked(),
|
||||
Nan::New(mbgl::Resource::Source));
|
||||
|
||||
Nan::Set(resource,
|
||||
Nan::New("Tile").ToLocalChecked(),
|
||||
Nan::New(mbgl::Resource::Tile));
|
||||
|
||||
Nan::Set(resource,
|
||||
Nan::New("Glyphs").ToLocalChecked(),
|
||||
Nan::New(mbgl::Resource::Glyphs));
|
||||
|
||||
Nan::Set(resource,
|
||||
Nan::New("SpriteImage").ToLocalChecked(),
|
||||
Nan::New(mbgl::Resource::SpriteImage));
|
||||
|
||||
Nan::Set(resource,
|
||||
Nan::New("SpriteJSON").ToLocalChecked(),
|
||||
Nan::New(mbgl::Resource::SpriteJSON));
|
||||
|
||||
Nan::Set(target,
|
||||
Nan::New("Resource").ToLocalChecked(),
|
||||
resource);
|
||||
|
||||
// Make the exported object inherit from process.EventEmitter
|
||||
v8::Local<v8::Object> process = Nan::Get(
|
||||
Nan::GetCurrentContext()->Global(),
|
||||
Nan::New("process").ToLocalChecked()).ToLocalChecked()->ToObject();
|
||||
|
||||
v8::Local<v8::Object> EventEmitter = Nan::Get(process,
|
||||
Nan::New("EventEmitter").ToLocalChecked()).ToLocalChecked()->ToObject();
|
||||
|
||||
Nan::SetPrototype(target,
|
||||
Nan::Get(EventEmitter, Nan::New("prototype").ToLocalChecked()).ToLocalChecked());
|
||||
|
||||
mbgl::Log::setObserver(std::make_unique<node_mbgl::NodeLogObserver>(target->ToObject()));
|
||||
}
|
||||
|
||||
NODE_MODULE(mapbox_gl_native, RegisterModule)
|
||||
|
||||
@@ -11,112 +11,109 @@ namespace node_mbgl {
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Static Node Methods
|
||||
|
||||
v8::Persistent<v8::FunctionTemplate> NodeRequest::constructorTemplate;
|
||||
Nan::Persistent<v8::Function> NodeRequest::constructor;
|
||||
|
||||
void NodeRequest::Init(v8::Handle<v8::Object> target) {
|
||||
NanScope();
|
||||
NAN_MODULE_INIT(NodeRequest::Init) {
|
||||
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
|
||||
|
||||
v8::Local<v8::FunctionTemplate> t = NanNew<v8::FunctionTemplate>(New);
|
||||
tpl->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
tpl->SetClassName(Nan::New("Request").ToLocalChecked());
|
||||
|
||||
t->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
t->SetClassName(NanNew("Request"));
|
||||
|
||||
NODE_SET_PROTOTYPE_METHOD(t, "respond", Respond);
|
||||
|
||||
NanAssignPersistent(constructorTemplate, t);
|
||||
|
||||
target->Set(NanNew("Request"), t->GetFunction());
|
||||
constructor.Reset(tpl->GetFunction());
|
||||
Nan::Set(target, Nan::New("Request").ToLocalChecked(), tpl->GetFunction());
|
||||
}
|
||||
|
||||
NAN_METHOD(NodeRequest::New) {
|
||||
NanScope();
|
||||
|
||||
// Extract the pointer from the first argument
|
||||
if (args.Length() < 2 || !args[0]->IsExternal() || !args[1]->IsExternal()) {
|
||||
return NanThrowTypeError("Cannot create Request objects explicitly");
|
||||
if (info.Length() < 2 || !info[0]->IsExternal() || !info[1]->IsExternal()) {
|
||||
return Nan::ThrowTypeError("Cannot create Request objects explicitly");
|
||||
}
|
||||
|
||||
auto source = reinterpret_cast<NodeFileSource*>(args[0].As<v8::External>()->Value());
|
||||
auto resource = reinterpret_cast<mbgl::Resource*>(args[1].As<v8::External>()->Value());
|
||||
auto source = reinterpret_cast<NodeFileSource*>(info[0].As<v8::External>()->Value());
|
||||
auto resource = reinterpret_cast<mbgl::Resource*>(info[1].As<v8::External>()->Value());
|
||||
auto req = new NodeRequest(source, *resource);
|
||||
req->Wrap(args.This());
|
||||
req->Wrap(info.This());
|
||||
|
||||
NanReturnValue(args.This());
|
||||
info.GetReturnValue().Set(info.This());
|
||||
}
|
||||
|
||||
v8::Handle<v8::Object> NodeRequest::Create(NodeFileSource* source, const mbgl::Resource& resource) {
|
||||
NanEscapableScope();
|
||||
Nan::EscapableHandleScope scope;
|
||||
|
||||
v8::Local<v8::Value> argv[] = { NanNew<v8::External>(const_cast<NodeFileSource*>(source)),
|
||||
NanNew<v8::External>(const_cast<mbgl::Resource*>(&resource)) };
|
||||
auto instance = NanNew<v8::FunctionTemplate>(constructorTemplate)->GetFunction()->NewInstance(2, argv);
|
||||
v8::Local<v8::Value> argv[] = {
|
||||
Nan::New<v8::External>(const_cast<NodeFileSource*>(source)),
|
||||
Nan::New<v8::External>(const_cast<mbgl::Resource*>(&resource))
|
||||
};
|
||||
auto instance = Nan::New(constructor)->NewInstance(2, argv);
|
||||
|
||||
instance->ForceSet(NanNew("url"), NanNew(resource.url), v8::ReadOnly);
|
||||
instance->ForceSet(NanNew("kind"), NanNew<v8::Integer>(int(resource.kind)), v8::ReadOnly);
|
||||
Nan::Set(instance, Nan::New("url").ToLocalChecked(), Nan::New(resource.url).ToLocalChecked());
|
||||
Nan::Set(instance, Nan::New("kind").ToLocalChecked(), Nan::New<v8::Integer>(int(resource.kind)));
|
||||
|
||||
return NanEscapeScope(instance);
|
||||
return scope.Escape(instance);
|
||||
}
|
||||
|
||||
NAN_METHOD(NodeRequest::Respond) {
|
||||
auto nodeRequest = ObjectWrap::Unwrap<NodeRequest>(args.Holder());
|
||||
auto nodeRequest = Nan::ObjectWrap::Unwrap<NodeRequest>(info.Data().As<v8::Object>());
|
||||
|
||||
// Request has already been responded to, or was canceled, fail silently.
|
||||
if (!nodeRequest->resource) NanReturnUndefined();
|
||||
if (!nodeRequest->resource) {
|
||||
return info.GetReturnValue().SetUndefined();
|
||||
}
|
||||
|
||||
auto source = nodeRequest->source;
|
||||
auto resource = std::move(nodeRequest->resource);
|
||||
|
||||
if (args.Length() < 1) {
|
||||
return NanThrowTypeError("First argument must be an error object");
|
||||
} else if (args[0]->BooleanValue()) {
|
||||
if (info.Length() < 1) {
|
||||
return Nan::ThrowTypeError("First argument must be an error object");
|
||||
} else if (info[0]->BooleanValue()) {
|
||||
auto response = std::make_shared<mbgl::Response>();
|
||||
|
||||
response->status = mbgl::Response::Error;
|
||||
|
||||
// Store the error string.
|
||||
const NanUtf8String message { args[0]->ToString() };
|
||||
const Nan::Utf8String message { info[0]->ToString() };
|
||||
response->message = std::string { *message, size_t(message.length()) };
|
||||
|
||||
source->notify(*resource, response);
|
||||
} else if (args.Length() < 2 || !args[1]->IsObject()) {
|
||||
return NanThrowTypeError("Second argument must be a response object");
|
||||
} else if (info.Length() < 2 || !info[1]->IsObject()) {
|
||||
return Nan::ThrowTypeError("Second argument must be a response object");
|
||||
} else {
|
||||
auto response = std::make_shared<mbgl::Response>();
|
||||
auto res = args[1]->ToObject();
|
||||
auto res = info[1]->ToObject();
|
||||
|
||||
response->status = mbgl::Response::Successful;
|
||||
|
||||
if (res->Has(NanNew("modified"))) {
|
||||
const double modified = res->Get(NanNew("modified"))->ToNumber()->Value();
|
||||
if (Nan::Has(res, Nan::New("modified").ToLocalChecked()).FromJust()) {
|
||||
const double modified = Nan::Get(res, Nan::New("modified").ToLocalChecked()).ToLocalChecked()->ToNumber()->Value();
|
||||
if (!std::isnan(modified)) {
|
||||
response->modified = modified / 1000; // JS timestamps are milliseconds
|
||||
}
|
||||
}
|
||||
|
||||
if (res->Has(NanNew("expires"))) {
|
||||
const double expires = res->Get(NanNew("expires"))->ToNumber()->Value();
|
||||
if (Nan::Has(res, Nan::New("expires").ToLocalChecked()).FromJust()) {
|
||||
const double expires = Nan::Get(res, Nan::New("expires").ToLocalChecked()).ToLocalChecked()->ToNumber()->Value();
|
||||
if (!std::isnan(expires)) {
|
||||
response->expires = expires / 1000; // JS timestamps are milliseconds
|
||||
}
|
||||
}
|
||||
|
||||
if (res->Has(NanNew("etag"))) {
|
||||
auto etagHandle = res->Get(NanNew("etag"));
|
||||
if (Nan::Has(res, Nan::New("etag").ToLocalChecked()).FromJust()) {
|
||||
auto etagHandle = Nan::Get(res, Nan::New("etag").ToLocalChecked()).ToLocalChecked();
|
||||
if (etagHandle->BooleanValue()) {
|
||||
const NanUtf8String etag { etagHandle->ToString() };
|
||||
const Nan::Utf8String etag { etagHandle->ToString() };
|
||||
response->etag = std::string { *etag, size_t(etag.length()) };
|
||||
}
|
||||
}
|
||||
|
||||
if (res->Has(NanNew("data"))) {
|
||||
auto dataHandle = res->Get(NanNew("data"));
|
||||
if (Nan::Has(res, Nan::New("data").ToLocalChecked()).FromJust()) {
|
||||
auto dataHandle = Nan::Get(res, Nan::New("data").ToLocalChecked()).ToLocalChecked();
|
||||
if (node::Buffer::HasInstance(dataHandle)) {
|
||||
response->data = std::string {
|
||||
node::Buffer::Data(dataHandle),
|
||||
node::Buffer::Length(dataHandle)
|
||||
};
|
||||
} else {
|
||||
return NanThrowTypeError("Response data must be a Buffer");
|
||||
return Nan::ThrowTypeError("Response data must be a Buffer");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,7 +121,7 @@ NAN_METHOD(NodeRequest::Respond) {
|
||||
source->notify(*resource, response);
|
||||
}
|
||||
|
||||
NanReturnUndefined();
|
||||
info.GetReturnValue().SetUndefined();
|
||||
}
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
#pragma GCC diagnostic ignored "-Wshadow"
|
||||
#include <node.h>
|
||||
#include <nan.h>
|
||||
#pragma GCC diagnostic pop
|
||||
|
||||
@@ -15,21 +14,16 @@ namespace node_mbgl {
|
||||
|
||||
class NodeFileSource;
|
||||
|
||||
class NodeRequest : public node::ObjectWrap {
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Static Node Methods
|
||||
class NodeRequest : public Nan::ObjectWrap {
|
||||
public:
|
||||
static void Init(v8::Handle<v8::Object> target);
|
||||
static NAN_MODULE_INIT(Init);
|
||||
|
||||
static NAN_METHOD(New);
|
||||
static NAN_METHOD(Respond);
|
||||
|
||||
static v8::Handle<v8::Object> Create(NodeFileSource*, const mbgl::Resource&);
|
||||
static Nan::Persistent<v8::Function> constructor;
|
||||
|
||||
static v8::Persistent<v8::FunctionTemplate> constructorTemplate;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Instance
|
||||
public:
|
||||
NodeRequest(NodeFileSource* source, const mbgl::Resource& resource);
|
||||
~NodeRequest();
|
||||
|
||||
|
||||
@@ -147,9 +147,9 @@ test('Map', function(t) {
|
||||
|
||||
t.test('.render', function(t) {
|
||||
var options = {
|
||||
request: function(req) {
|
||||
request: function(req, callback) {
|
||||
fs.readFile(path.join(__dirname, '..', req.url), function(err, data) {
|
||||
req.respond(err, { data: data });
|
||||
callback(err, { data: data });
|
||||
});
|
||||
},
|
||||
ratio: 1
|
||||
@@ -266,18 +266,14 @@ test('Map', function(t) {
|
||||
render();
|
||||
});
|
||||
|
||||
t.skip('throws if called in parallel', function(t) {
|
||||
var completed = 0;
|
||||
var remaining = 10;
|
||||
var start = +new Date;
|
||||
|
||||
t.test('throws if called in parallel', function(t) {
|
||||
var map = new mbgl.Map(options);
|
||||
map.load(style);
|
||||
|
||||
t.throws(function() {
|
||||
map.render({}, function() {});
|
||||
map.render({}, function() {});
|
||||
});
|
||||
}, /Map is currently rendering an image/);
|
||||
|
||||
map.release();
|
||||
t.end();
|
||||
|
||||
@@ -13,9 +13,9 @@ if (process.argv[1] === __filename && process.argv.length > 2) {
|
||||
suite.run('native', {tests: tests}, function (style, options, callback) {
|
||||
var map = new mbgl.Map({
|
||||
ratio: options.pixelRatio,
|
||||
request: function (req) {
|
||||
request: function(req, callback) {
|
||||
request(req.url, {encoding: null}, function (err, response, body) {
|
||||
req.respond(err, {data: body});
|
||||
callback(err, {data: body});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -39,16 +39,20 @@ if [ ! -z "${AWS_ACCESS_KEY_ID}" ] && [ ! -z "${AWS_SECRET_ACCESS_KEY}" ] ; then
|
||||
|
||||
S3_PREFIX=s3://mapbox/mapbox-gl-native/android/build/${TRAVIS_JOB_NUMBER}
|
||||
APK_OUTPUTS=./android/java/MapboxGLAndroidSDKTestApp/build/outputs/apk
|
||||
JNILIB=`mason env JNIDIR`
|
||||
|
||||
# Upload either the debug or the release build
|
||||
if [ ${BUILDTYPE} == "Debug" ] ; then
|
||||
aws s3 cp \
|
||||
${APK_OUTPUTS}/MapboxGLAndroidSDKTestApp-debug.apk \
|
||||
${S3_PREFIX}/MapboxGLAndroidSDKTestApp-debug.apk
|
||||
elif [ ${BUILDTYPE} == "Release" ] ; then
|
||||
aws s3 cp \
|
||||
${APK_OUTPUTS}/MapboxGLAndroidSDKTestApp-release-unsigned.apk \
|
||||
${S3_PREFIX}/MapboxGLAndroidSDKTestApp-release-unsigned.apk
|
||||
# ARM64 does not build APK for now
|
||||
if [ ${JNIDIR} != "arm64-v8a" ] ; then
|
||||
# Upload either the debug or the release build
|
||||
if [ ${BUILDTYPE} == "Debug" ] ; then
|
||||
aws s3 cp \
|
||||
${APK_OUTPUTS}/MapboxGLAndroidSDKTestApp-${JNILIB}-debug.apk \
|
||||
${S3_PREFIX}/MapboxGLAndroidSDKTestApp-debug.apk
|
||||
elif [ ${BUILDTYPE} == "Release" ] ; then
|
||||
aws s3 cp \
|
||||
${APK_OUTPUTS}/MapboxGLAndroidSDKTestApp-${JNILIB}-release-unsigned.apk \
|
||||
${S3_PREFIX}/MapboxGLAndroidSDKTestApp-release-unsigned.apk
|
||||
fi
|
||||
fi
|
||||
|
||||
mapbox_time_finish
|
||||
|
||||
@@ -34,11 +34,13 @@ def write_header():
|
||||
#ifndef MBGL_SHADER_SHADERS
|
||||
#define MBGL_SHADER_SHADERS
|
||||
|
||||
#include <mbgl/platform/gl.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
struct shader_source {
|
||||
const char *vertex;
|
||||
const char *fragment;
|
||||
const GLchar *vertex;
|
||||
const GLchar *fragment;
|
||||
};
|
||||
|
||||
enum {
|
||||
|
||||
@@ -6,7 +6,7 @@ set -u
|
||||
|
||||
#
|
||||
# iOS release tag format is `vX.Y.Z`; `X.Y.Z` gets passed in
|
||||
# In the case of symbolicated builds, we also append the `style`.
|
||||
# In the case of symbolicated builds, we also append the `-symbols`.
|
||||
#
|
||||
PUBLISH_VERSION="$1"
|
||||
|
||||
|
||||
@@ -4,8 +4,11 @@ set -e
|
||||
set -o pipefail
|
||||
set -u
|
||||
|
||||
xctool \
|
||||
xcodebuild \
|
||||
-project ./test/ios/ios-tests.xcodeproj \
|
||||
-scheme 'Mapbox GL Tests' \
|
||||
-sdk iphonesimulator8.4 \
|
||||
test
|
||||
-sdk iphonesimulator \
|
||||
-destination 'platform=iOS Simulator,name=iPhone 6,OS=latest' \
|
||||
-destination 'platform=iOS Simulator,name=iPad 2,OS=latest' \
|
||||
test \
|
||||
| xcpretty
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
namespace mbgl {
|
||||
|
||||
template <
|
||||
size_t item_size,
|
||||
int bufferType = GL_ARRAY_BUFFER,
|
||||
size_t defaultLength = 8192,
|
||||
GLsizei item_size,
|
||||
GLenum bufferType = GL_ARRAY_BUFFER,
|
||||
GLsizei defaultLength = 8192,
|
||||
bool retainAfterUpload = false
|
||||
>
|
||||
class Buffer : private util::noncopyable {
|
||||
@@ -31,8 +31,8 @@ public:
|
||||
|
||||
// Returns the number of elements in this buffer. This is not the number of
|
||||
// bytes, but rather the number of coordinates with associated information.
|
||||
inline size_t index() const {
|
||||
return pos / itemSize;
|
||||
inline GLsizei index() const {
|
||||
return static_cast<GLsizei>(pos / itemSize);
|
||||
}
|
||||
|
||||
inline bool empty() const {
|
||||
@@ -110,10 +110,10 @@ public:
|
||||
|
||||
private:
|
||||
// CPU buffer
|
||||
void *array = nullptr;
|
||||
GLvoid *array = nullptr;
|
||||
|
||||
// Byte position where we are writing.
|
||||
size_t pos = 0;
|
||||
GLsizeiptr pos = 0;
|
||||
|
||||
// Number of bytes that are valid in this buffer.
|
||||
size_t length = 0;
|
||||
|
||||
@@ -10,16 +10,16 @@
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
template <int count>
|
||||
template <GLsizei count>
|
||||
struct ElementGroup : public util::noncopyable {
|
||||
std::array<VertexArrayObject, count> array;
|
||||
uint32_t vertex_length;
|
||||
uint32_t elements_length;
|
||||
GLsizei vertex_length;
|
||||
GLsizei elements_length;
|
||||
|
||||
ElementGroup() : vertex_length(0), elements_length(0) {}
|
||||
ElementGroup(uint32_t vertex_length_, uint32_t elements_length_)
|
||||
: vertex_length(vertex_length_),
|
||||
elements_length(elements_length_) {
|
||||
ElementGroup(GLsizei vertex_length_ = 0, GLsizei elements_length_ = 0)
|
||||
: vertex_length(vertex_length_)
|
||||
, elements_length(elements_length_)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
#include <mbgl/platform/gl.hpp>
|
||||
#include <mbgl/platform/log.hpp>
|
||||
#include <mbgl/platform/platform.hpp>
|
||||
#include <mbgl/util/gl_object_store.hpp>
|
||||
#include <mbgl/util/thread_context.hpp>
|
||||
|
||||
#include <cassert>
|
||||
#include <algorithm>
|
||||
@@ -20,6 +22,15 @@ GlyphAtlas::GlyphAtlas(uint16_t width_, uint16_t height_)
|
||||
dirty(true) {
|
||||
}
|
||||
|
||||
GlyphAtlas::~GlyphAtlas() {
|
||||
assert(util::ThreadContext::currentlyOn(util::ThreadType::Map));
|
||||
|
||||
if (texture) {
|
||||
mbgl::util::ThreadContext::getGLObjectStore()->abandonTexture(texture);
|
||||
texture = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void GlyphAtlas::addGlyphs(uintptr_t tileUID,
|
||||
const std::u32string& text,
|
||||
const std::string& stackName,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <mbgl/geometry/binpack.hpp>
|
||||
#include <mbgl/text/glyph_store.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/platform/gl.hpp>
|
||||
|
||||
#include <string>
|
||||
#include <set>
|
||||
@@ -16,6 +17,7 @@ namespace mbgl {
|
||||
class GlyphAtlas : public util::noncopyable {
|
||||
public:
|
||||
GlyphAtlas(uint16_t width, uint16_t height);
|
||||
~GlyphAtlas();
|
||||
|
||||
void addGlyphs(uintptr_t tileUID,
|
||||
const std::u32string& text,
|
||||
@@ -31,8 +33,8 @@ public:
|
||||
// the texture is only bound when the data is out of date (=dirty).
|
||||
void upload();
|
||||
|
||||
const uint16_t width = 0;
|
||||
const uint16_t height = 0;
|
||||
const GLsizei width;
|
||||
const GLsizei height;
|
||||
|
||||
private:
|
||||
struct GlyphValue {
|
||||
@@ -51,7 +53,7 @@ private:
|
||||
std::map<std::string, std::map<uint32_t, GlyphValue>> index;
|
||||
const std::unique_ptr<uint8_t[]> data;
|
||||
std::atomic<bool> dirty;
|
||||
uint32_t texture = 0;
|
||||
GLuint texture = 0;
|
||||
};
|
||||
|
||||
};
|
||||
|
||||
@@ -12,10 +12,10 @@
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
LineAtlas::LineAtlas(uint16_t w, uint16_t h)
|
||||
LineAtlas::LineAtlas(GLsizei w, GLsizei h)
|
||||
: width(w),
|
||||
height(h),
|
||||
data(std::make_unique<uint8_t[]>(w * h)),
|
||||
data(std::make_unique<GLbyte[]>(w * h)),
|
||||
dirty(true) {
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#ifndef MBGL_GEOMETRY_LINE_ATLAS
|
||||
#define MBGL_GEOMETRY_LINE_ATLAS
|
||||
|
||||
#include <mbgl/platform/gl.hpp>
|
||||
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
@@ -15,7 +17,7 @@ typedef struct {
|
||||
|
||||
class LineAtlas {
|
||||
public:
|
||||
LineAtlas(uint16_t width, uint16_t height);
|
||||
LineAtlas(GLsizei width, GLsizei height);
|
||||
~LineAtlas();
|
||||
|
||||
// Binds the atlas texture to the GPU, and uploads data if it is out of date.
|
||||
@@ -28,13 +30,13 @@ public:
|
||||
LinePatternPos getDashPosition(const std::vector<float>&, bool);
|
||||
LinePatternPos addDash(const std::vector<float> &dasharray, bool round);
|
||||
|
||||
const int width;
|
||||
const int height;
|
||||
const GLsizei width;
|
||||
const GLsizei height;
|
||||
|
||||
private:
|
||||
const std::unique_ptr<uint8_t[]> data;
|
||||
const std::unique_ptr<GLbyte[]> data;
|
||||
bool dirty;
|
||||
uint32_t texture = 0;
|
||||
GLuint texture = 0;
|
||||
int nextRow = 0;
|
||||
std::map<size_t, LinePatternPos> positions;
|
||||
};
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
|
||||
using namespace mbgl;
|
||||
|
||||
size_t LineVertexBuffer::add(vertex_type x, vertex_type y, float ex, float ey, int8_t tx, int8_t ty, int32_t linesofar) {
|
||||
size_t idx = index();
|
||||
GLsizei LineVertexBuffer::add(vertex_type x, vertex_type y, float ex, float ey, int8_t tx, int8_t ty, int32_t linesofar) {
|
||||
GLsizei idx = index();
|
||||
void *data = addElement();
|
||||
|
||||
int16_t *coords = static_cast<int16_t *>(data);
|
||||
|
||||
@@ -30,7 +30,7 @@ public:
|
||||
* @param {number} tx texture normal
|
||||
* @param {number} ty texture normal
|
||||
*/
|
||||
size_t add(vertex_type x, vertex_type y, float ex, float ey, int8_t tx, int8_t ty, int32_t linesofar = 0);
|
||||
GLsizei add(vertex_type x, vertex_type y, float ex, float ey, int8_t tx, int8_t ty, int32_t linesofar = 0);
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
#define MBGL_GEOMETRY_SPRITE_ATLAS
|
||||
|
||||
#include <mbgl/geometry/binpack.hpp>
|
||||
|
||||
#include <mbgl/platform/gl.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/util/ptr.hpp>
|
||||
|
||||
@@ -69,7 +69,7 @@ public:
|
||||
inline const uint32_t* getData() const { return data.get(); }
|
||||
|
||||
private:
|
||||
const dimension width, height;
|
||||
const GLsizei width, height;
|
||||
const dimension pixelWidth, pixelHeight;
|
||||
const float pixelRatio;
|
||||
|
||||
@@ -93,7 +93,7 @@ private:
|
||||
const std::unique_ptr<uint32_t[]> data;
|
||||
std::atomic<bool> dirty;
|
||||
bool fullUploadRequired = true;
|
||||
uint32_t texture = 0;
|
||||
GLuint texture = 0;
|
||||
uint32_t filter = 0;
|
||||
static const int buffer = 1;
|
||||
};
|
||||
|
||||
@@ -69,7 +69,7 @@ void VertexArrayObject::bindVertexArrayObject() {
|
||||
}
|
||||
|
||||
void VertexArrayObject::verifyBinding(Shader &shader, GLuint vertexBuffer, GLuint elementsBuffer,
|
||||
char *offset) {
|
||||
GLbyte *offset) {
|
||||
if (bound_shader != shader.getID()) {
|
||||
throw std::runtime_error(std::string("trying to rebind VAO to another shader from " +
|
||||
util::toString(bound_shader) + "(" + bound_shader_name + ") to " +
|
||||
@@ -84,7 +84,7 @@ void VertexArrayObject::verifyBinding(Shader &shader, GLuint vertexBuffer, GLuin
|
||||
}
|
||||
|
||||
void VertexArrayObject::storeBinding(Shader &shader, GLuint vertexBuffer, GLuint elementsBuffer,
|
||||
char *offset) {
|
||||
GLbyte *offset) {
|
||||
bound_shader = shader.getID();
|
||||
bound_shader_name = shader.name;
|
||||
bound_offset = offset;
|
||||
|
||||
@@ -18,7 +18,7 @@ public:
|
||||
~VertexArrayObject();
|
||||
|
||||
template <typename Shader, typename VertexBuffer>
|
||||
inline void bind(Shader& shader, VertexBuffer &vertexBuffer, char *offset) {
|
||||
inline void bind(Shader& shader, VertexBuffer &vertexBuffer, GLbyte *offset) {
|
||||
bindVertexArrayObject();
|
||||
if (bound_shader == 0) {
|
||||
vertexBuffer.bind();
|
||||
@@ -32,7 +32,7 @@ public:
|
||||
}
|
||||
|
||||
template <typename Shader, typename VertexBuffer, typename ElementsBuffer>
|
||||
inline void bind(Shader& shader, VertexBuffer &vertexBuffer, ElementsBuffer &elementsBuffer, char *offset) {
|
||||
inline void bind(Shader& shader, VertexBuffer &vertexBuffer, ElementsBuffer &elementsBuffer, GLbyte *offset) {
|
||||
bindVertexArrayObject();
|
||||
if (bound_shader == 0) {
|
||||
vertexBuffer.bind();
|
||||
@@ -52,8 +52,8 @@ public:
|
||||
|
||||
private:
|
||||
void bindVertexArrayObject();
|
||||
void storeBinding(Shader &shader, GLuint vertexBuffer, GLuint elementsBuffer, char *offset);
|
||||
void verifyBinding(Shader &shader, GLuint vertexBuffer, GLuint elementsBuffer, char *offset);
|
||||
void storeBinding(Shader &shader, GLuint vertexBuffer, GLuint elementsBuffer, GLbyte *offset);
|
||||
void verifyBinding(Shader &shader, GLuint vertexBuffer, GLuint elementsBuffer, GLbyte *offset);
|
||||
|
||||
GLuint vao = 0;
|
||||
|
||||
@@ -63,7 +63,7 @@ private:
|
||||
const char *bound_shader_name = "";
|
||||
GLuint bound_vertex_buffer = 0;
|
||||
GLuint bound_elements_buffer = 0;
|
||||
char *bound_offset = 0;
|
||||
GLbyte *bound_offset = 0;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -89,166 +89,118 @@ AnnotationManager::addTileFeature(const uint32_t annotationID,
|
||||
assert(type != AnnotationType::Any);
|
||||
|
||||
// track the annotation global ID and its original geometry
|
||||
auto anno_it = annotations.emplace(annotationID,
|
||||
std::make_unique<Annotation>(type, segments, styleProperties));
|
||||
|
||||
std::unordered_set<TileID, TileID::Hash> affectedTiles;
|
||||
annotations.emplace(annotationID, std::make_unique<Annotation>(type, segments, styleProperties));
|
||||
|
||||
if (type == AnnotationType::Shape) {
|
||||
|
||||
orderedShapeAnnotations.push_back(annotationID);
|
||||
|
||||
using namespace mapbox::util::geojsonvt;
|
||||
|
||||
const uint32_t z2 = 1 << maxZoom;
|
||||
const double baseTolerance = 3;
|
||||
const uint16_t extent = 4096;
|
||||
|
||||
const double tolerance = baseTolerance / (z2 * extent);
|
||||
|
||||
ProjectedGeometryContainer rings;
|
||||
|
||||
std::vector<LonLat> points;
|
||||
|
||||
for (size_t i = 0; i < segments[0].size(); ++i) { // first segment for now (no holes)
|
||||
const double constraintedLatitude = ::fmin(::fmax(segments[0][i].latitude, -util::LATITUDE_MAX), util::LATITUDE_MAX);
|
||||
points.push_back(LonLat(segments[0][i].longitude, constraintedLatitude));
|
||||
}
|
||||
|
||||
ProjectedFeatureType featureType;
|
||||
|
||||
if (styleProperties.is<FillProperties>()) {
|
||||
featureType = ProjectedFeatureType::Polygon;
|
||||
|
||||
if (points.front().lon != points.back().lon || points.front().lat != points.back().lat) {
|
||||
points.push_back(LonLat(points.front().lon, points.front().lat));
|
||||
}
|
||||
} else {
|
||||
featureType = ProjectedFeatureType::LineString;
|
||||
}
|
||||
|
||||
ProjectedGeometryContainer ring = Convert::project(points, tolerance);
|
||||
|
||||
rings.members.push_back(ring);
|
||||
|
||||
std::vector<ProjectedFeature> features;
|
||||
|
||||
features.push_back(Convert::create(Tags(), featureType, rings));
|
||||
|
||||
shapeTilers.emplace(annotationID, std::make_unique<GeoJSONVT>(features, maxZoom, 4, 100, 10));
|
||||
|
||||
return addShapeFeature(annotationID, segments, styleProperties, maxZoom);
|
||||
} else {
|
||||
return addPointFeature(annotationID, projectedFeature, featureProperties, maxZoom);
|
||||
}
|
||||
}
|
||||
|
||||
// side length of map at max zoom
|
||||
uint32_t z2 = 1 << maxZoom;
|
||||
std::unordered_set<TileID, TileID::Hash>
|
||||
AnnotationManager::addShapeFeature(const uint32_t annotationID,
|
||||
const AnnotationSegments& segments,
|
||||
const StyleProperties& styleProperties,
|
||||
const uint8_t maxZoom) {
|
||||
// Currently unused.
|
||||
std::unordered_set<TileID, TileID::Hash> affectedTiles;
|
||||
|
||||
const uint16_t extent = 4096;
|
||||
orderedShapeAnnotations.push_back(annotationID);
|
||||
|
||||
uint32_t x = 0;
|
||||
uint32_t y = 0;
|
||||
using namespace mapbox::util::geojsonvt;
|
||||
|
||||
for (int8_t z = maxZoom; z >= 0; z--) {
|
||||
const uint32_t z2 = 1 << maxZoom;
|
||||
const double baseTolerance = 3;
|
||||
const uint16_t extent = 4096;
|
||||
|
||||
std::unordered_map<TileID, GeometryCollection, TileID::Hash> featureTiles;
|
||||
const double tolerance = baseTolerance / (z2 * extent);
|
||||
|
||||
if (type == AnnotationType::Point) {
|
||||
auto& pp = projectedFeature[0][0];
|
||||
ProjectedGeometryContainer rings;
|
||||
|
||||
x = pp.x * z2;
|
||||
y = pp.y * z2;
|
||||
std::vector<LonLat> points;
|
||||
|
||||
const Coordinate coordinate(extent * (pp.x * z2 - x), extent * (pp.y * z2 - y));
|
||||
for (size_t i = 0; i < segments[0].size(); ++i) { // first segment for now (no holes)
|
||||
const double constraintedLatitude = ::fmin(::fmax(segments[0][i].latitude, -util::LATITUDE_MAX), util::LATITUDE_MAX);
|
||||
points.push_back(LonLat(segments[0][i].longitude, constraintedLatitude));
|
||||
}
|
||||
|
||||
GeometryCollection geometries = {{ {{ coordinate }} }};
|
||||
ProjectedFeatureType featureType;
|
||||
|
||||
featureTiles.emplace(TileID(z, x, y, z), geometries);
|
||||
} else {
|
||||
for (size_t l = 0; l < projectedFeature.size(); ++l) {
|
||||
for (size_t p = 0; p < projectedFeature[l].size(); ++p) {
|
||||
|
||||
auto& pp = projectedFeature[l][p];
|
||||
|
||||
x = pp.x * z2;
|
||||
y = pp.y * z2;
|
||||
|
||||
const Coordinate coordinate(extent * (pp.x * z2 - x), extent * (pp.y * z2 - y));
|
||||
|
||||
auto tile_it = featureTiles.find(TileID(z, x, y, z));
|
||||
|
||||
if (tile_it != featureTiles.end()) {
|
||||
GeometryCollection& geometries = featureTiles.find(TileID(z, x, y, z))->second;
|
||||
if (!geometries.empty()) {
|
||||
geometries.back().push_back(coordinate);
|
||||
} else {
|
||||
geometries.push_back({{ coordinate }});
|
||||
}
|
||||
} else {
|
||||
GeometryCollection geometries = {{ {{ coordinate }} }};
|
||||
featureTiles.emplace(TileID(z, x, y, z), geometries);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& featureTile : featureTiles) {
|
||||
// determine feature type
|
||||
FeatureType featureType;
|
||||
if (type == AnnotationType::Point) {
|
||||
featureType = FeatureType::Point;
|
||||
} else if (styleProperties.is<LineProperties>()) {
|
||||
featureType = FeatureType::LineString;
|
||||
} else if (styleProperties.is<FillProperties>()) {
|
||||
featureType = FeatureType::Polygon;
|
||||
} else {
|
||||
throw std::runtime_error("Invalid feature type");
|
||||
}
|
||||
|
||||
// create tile feature
|
||||
auto feature = std::make_shared<const LiveTileFeature>(
|
||||
featureType,
|
||||
featureTile.second,
|
||||
featureProperties
|
||||
);
|
||||
|
||||
// check for tile & create if necessary
|
||||
auto tile_pos = tiles.emplace(featureTile.first,
|
||||
std::make_pair(std::unordered_set<uint32_t>({ annotationID }),
|
||||
std::make_unique<LiveTile>()));
|
||||
|
||||
// check for annotation layer & create if necessary
|
||||
util::ptr<LiveTileLayer> layer;
|
||||
std::string layerID = "";
|
||||
if (type == AnnotationType::Point) {
|
||||
layerID = PointLayerID;
|
||||
} else {
|
||||
layerID = ShapeLayerID + "." + util::toString(annotationID);
|
||||
}
|
||||
if (tile_pos.second || tile_pos.first->second.second->getMutableLayer(layerID) == nullptr) {
|
||||
layer = std::make_shared<LiveTileLayer>();
|
||||
tile_pos.first->second.second->addLayer(layerID, layer);
|
||||
} else {
|
||||
layer = tile_pos.first->second.second->getMutableLayer(layerID);
|
||||
|
||||
// associate annotation with tile
|
||||
tile_pos.first->second.first.insert(annotationID);
|
||||
}
|
||||
|
||||
// add feature to layer
|
||||
layer->addFeature(feature);
|
||||
|
||||
// Record annotation association with tile and tile feature. This is used to determine stale tiles,
|
||||
// as well as to remove the feature from the tile upon annotation deletion.
|
||||
anno_it.first->second->tilePointFeatures.emplace(featureTile.first, std::weak_ptr<const LiveTileFeature>(feature));
|
||||
|
||||
// track affected tile
|
||||
affectedTiles.insert(featureTile.first);
|
||||
}
|
||||
|
||||
// get ready for the next-lower zoom number
|
||||
z2 /= 2;
|
||||
x /= 2;
|
||||
y /= 2;
|
||||
if (styleProperties.is<FillProperties>()) {
|
||||
featureType = ProjectedFeatureType::Polygon;
|
||||
|
||||
if (points.front().lon != points.back().lon || points.front().lat != points.back().lat) {
|
||||
points.push_back(LonLat(points.front().lon, points.front().lat));
|
||||
}
|
||||
} else {
|
||||
featureType = ProjectedFeatureType::LineString;
|
||||
}
|
||||
|
||||
ProjectedGeometryContainer ring = Convert::project(points, tolerance);
|
||||
rings.members.push_back(ring);
|
||||
|
||||
std::vector<ProjectedFeature> features;
|
||||
features.push_back(Convert::create(Tags(), featureType, rings));
|
||||
|
||||
shapeTilers.emplace(annotationID, std::make_unique<GeoJSONVT>(features, maxZoom, 4, 100, 10));
|
||||
|
||||
return affectedTiles;
|
||||
}
|
||||
|
||||
std::unordered_set<mbgl::TileID, mbgl::TileID::Hash>
|
||||
AnnotationManager::addPointFeature(const uint32_t annotationID,
|
||||
const std::vector<std::vector<vec2<double>>>& projectedFeature,
|
||||
const std::unordered_map<std::string, std::string>& featureProperties,
|
||||
const uint8_t maxZoom) {
|
||||
std::unordered_set<TileID, TileID::Hash> affectedTiles;
|
||||
|
||||
auto anno_it = annotations.find(annotationID);
|
||||
assert(anno_it != annotations.end());
|
||||
|
||||
const uint16_t extent = 4096;
|
||||
auto& pp = projectedFeature[0][0];
|
||||
|
||||
for (int8_t z = maxZoom; z >= 0; z--) {
|
||||
uint32_t z2 = 1 << z;
|
||||
uint32_t x = pp.x * z2;
|
||||
uint32_t y = pp.y * z2;
|
||||
|
||||
const Coordinate coordinate(extent * (pp.x * z2 - x), extent * (pp.y * z2 - y));
|
||||
|
||||
GeometryCollection geometries = {{ {{ coordinate }} }};
|
||||
TileID featureTileID = TileID(z, x, y, z);
|
||||
|
||||
auto feature = std::make_shared<const LiveTileFeature>(FeatureType::Point, geometries, featureProperties);
|
||||
|
||||
// check for tile & create if necessary
|
||||
auto tile_pos = tiles.emplace(featureTileID,
|
||||
std::make_pair(std::unordered_set<uint32_t>({ annotationID }),
|
||||
std::make_unique<LiveTile>()));
|
||||
|
||||
// check for annotation layer & create if necessary
|
||||
util::ptr<LiveTileLayer> layer;
|
||||
std::string layerID = PointLayerID;
|
||||
|
||||
if (tile_pos.second || tile_pos.first->second.second->getMutableLayer(layerID) == nullptr) {
|
||||
layer = std::make_shared<LiveTileLayer>();
|
||||
tile_pos.first->second.second->addLayer(layerID, layer);
|
||||
} else {
|
||||
layer = tile_pos.first->second.second->getMutableLayer(layerID);
|
||||
|
||||
// associate annotation with tile
|
||||
tile_pos.first->second.first.insert(annotationID);
|
||||
}
|
||||
|
||||
// add feature to layer
|
||||
layer->addFeature(feature);
|
||||
|
||||
// Record annotation association with tile and tile feature. This is used to determine stale tiles,
|
||||
// as well as to remove the feature from the tile upon annotation deletion.
|
||||
anno_it->second->tilePointFeatures.emplace(featureTileID, std::weak_ptr<const LiveTileFeature>(feature));
|
||||
|
||||
// track affected tile
|
||||
affectedTiles.insert(featureTileID);
|
||||
}
|
||||
|
||||
return affectedTiles;
|
||||
|
||||
@@ -80,14 +80,27 @@ public:
|
||||
private:
|
||||
inline uint32_t nextID();
|
||||
static vec2<double> projectPoint(const LatLng& point);
|
||||
std::unordered_set<TileID, TileID::Hash> addTileFeature(
|
||||
const uint32_t annotationID,
|
||||
const AnnotationSegments&,
|
||||
const std::vector<std::vector<vec2<double>>>& projectedFeature,
|
||||
const AnnotationType&,
|
||||
const StyleProperties&,
|
||||
const std::unordered_map<std::string, std::string>& featureProperties,
|
||||
const uint8_t maxZoom);
|
||||
|
||||
std::unordered_set<TileID, TileID::Hash>
|
||||
addTileFeature(const uint32_t annotationID,
|
||||
const AnnotationSegments&,
|
||||
const std::vector<std::vector<vec2<double>>>& projectedFeature,
|
||||
const AnnotationType&,
|
||||
const StyleProperties&,
|
||||
const std::unordered_map<std::string, std::string>& featureProperties,
|
||||
const uint8_t maxZoom);
|
||||
|
||||
std::unordered_set<TileID, TileID::Hash>
|
||||
addShapeFeature(const uint32_t annotationID,
|
||||
const AnnotationSegments& segments,
|
||||
const StyleProperties& styleProperties,
|
||||
const uint8_t maxZoom);
|
||||
|
||||
std::unordered_set<TileID, TileID::Hash>
|
||||
addPointFeature(const uint32_t annotationID,
|
||||
const std::vector<std::vector<vec2<double>>>& projectedFeature,
|
||||
const std::unordered_map<std::string, std::string>& featureProperties,
|
||||
const uint8_t maxZoom);
|
||||
|
||||
private:
|
||||
std::string defaultPointAnnotationSymbol;
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
#ifndef MBGL_RENDERER_BUCKET
|
||||
#define MBGL_RENDERER_BUCKET
|
||||
|
||||
#include <mbgl/platform/gl.hpp>
|
||||
#include <mbgl/renderer/render_pass.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/util/mat4.hpp>
|
||||
|
||||
#include <atomic>
|
||||
|
||||
#define BUFFER_OFFSET(i) ((char*)nullptr + (i))
|
||||
#define BUFFER_OFFSET_0 ((GLbyte*)nullptr)
|
||||
#define BUFFER_OFFSET(i) ((BUFFER_OFFSET_0) + (i))
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
|
||||
@@ -35,11 +35,15 @@ bool CircleBucket::hasData() const {
|
||||
}
|
||||
|
||||
void CircleBucket::addGeometry(const GeometryCollection& geometryCollection) {
|
||||
const int extent = 4096;
|
||||
for (auto& circle : geometryCollection) {
|
||||
for(auto & geometry : circle) {
|
||||
auto x = geometry.x;
|
||||
auto y = geometry.y;
|
||||
|
||||
// Do not include points that are outside the tile boundaries.
|
||||
if (x < 0 || x >= extent || y < 0 || y >= extent) continue;
|
||||
|
||||
// this geometry will be of the Point type, and we'll derive
|
||||
// two triangles from it.
|
||||
//
|
||||
@@ -74,8 +78,8 @@ void CircleBucket::addGeometry(const GeometryCollection& geometryCollection) {
|
||||
}
|
||||
|
||||
void CircleBucket::drawCircles(CircleShader& shader) {
|
||||
char* vertexIndex = BUFFER_OFFSET(vertexStart_ * vertexBuffer_.itemSize);
|
||||
char* elementsIndex = BUFFER_OFFSET(elementsStart_ * elementsBuffer_.itemSize);
|
||||
GLbyte *vertexIndex = BUFFER_OFFSET(vertexStart_ * vertexBuffer_.itemSize);
|
||||
GLbyte *elementsIndex = BUFFER_OFFSET(elementsStart_ * elementsBuffer_.itemSize);
|
||||
|
||||
for (auto& group : triangleGroups_) {
|
||||
assert(group);
|
||||
|
||||
@@ -35,8 +35,8 @@ private:
|
||||
CircleVertexBuffer& vertexBuffer_;
|
||||
TriangleElementsBuffer& elementsBuffer_;
|
||||
|
||||
const size_t vertexStart_;
|
||||
const size_t elementsStart_;
|
||||
const GLsizei vertexStart_;
|
||||
const GLsizei elementsStart_;
|
||||
|
||||
std::vector<std::unique_ptr<TriangleGroup>> triangleGroups_;
|
||||
};
|
||||
|
||||
@@ -23,11 +23,11 @@ void DebugBucket::render(Painter& painter, const StyleLayer&, const TileID&, con
|
||||
}
|
||||
|
||||
void DebugBucket::drawLines(PlainShader& shader) {
|
||||
array.bind(shader, fontBuffer, BUFFER_OFFSET(0));
|
||||
array.bind(shader, fontBuffer, BUFFER_OFFSET_0);
|
||||
MBGL_CHECK_ERROR(glDrawArrays(GL_LINES, 0, (GLsizei)(fontBuffer.index())));
|
||||
}
|
||||
|
||||
void DebugBucket::drawPoints(PlainShader& shader) {
|
||||
array.bind(shader, fontBuffer, BUFFER_OFFSET(0));
|
||||
array.bind(shader, fontBuffer, BUFFER_OFFSET_0);
|
||||
MBGL_CHECK_ERROR(glDrawArrays(GL_POINTS, 0, (GLsizei)(fontBuffer.index())));
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ void FillBucket::tessellate() {
|
||||
return;
|
||||
}
|
||||
|
||||
size_t total_vertex_count = 0;
|
||||
GLsizei total_vertex_count = 0;
|
||||
for (const auto& polygon : polygons) {
|
||||
total_vertex_count += polygon.size();
|
||||
}
|
||||
@@ -107,10 +107,10 @@ void FillBucket::tessellate() {
|
||||
|
||||
assert(lineGroups.back());
|
||||
LineGroup& lineGroup = *lineGroups.back();
|
||||
uint32_t lineIndex = lineGroup.vertex_length;
|
||||
GLsizei lineIndex = lineGroup.vertex_length;
|
||||
|
||||
for (const auto& polygon : polygons) {
|
||||
const size_t group_count = polygon.size();
|
||||
const GLsizei group_count = static_cast<GLsizei>(polygon.size());
|
||||
assert(group_count >= 3);
|
||||
|
||||
std::vector<TESSreal> clipped_line;
|
||||
@@ -120,8 +120,8 @@ void FillBucket::tessellate() {
|
||||
vertexBuffer.add(pt.X, pt.Y);
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < group_count; i++) {
|
||||
const size_t prev_i = (i == 0 ? group_count : i) - 1;
|
||||
for (GLsizei i = 0; i < group_count; i++) {
|
||||
const GLsizei prev_i = (i == 0 ? group_count : i) - 1;
|
||||
lineElementsBuffer.add(lineIndex + prev_i, lineIndex + i);
|
||||
}
|
||||
|
||||
@@ -134,12 +134,12 @@ void FillBucket::tessellate() {
|
||||
|
||||
if (tessTesselate(tesselator, TESS_WINDING_ODD, TESS_POLYGONS, vertices_per_group, vertexSize, 0)) {
|
||||
const TESSreal *vertices = tessGetVertices(tesselator);
|
||||
const size_t vertex_count = tessGetVertexCount(tesselator);
|
||||
const GLsizei vertex_count = tessGetVertexCount(tesselator);
|
||||
TESSindex *vertex_indices = const_cast<TESSindex *>(tessGetVertexIndices(tesselator));
|
||||
const TESSindex *elements = tessGetElements(tesselator);
|
||||
const int triangle_count = tessGetElementCount(tesselator);
|
||||
|
||||
for (size_t i = 0; i < vertex_count; ++i) {
|
||||
for (GLsizei i = 0; i < vertex_count; ++i) {
|
||||
if (vertex_indices[i] == TESS_UNDEF) {
|
||||
vertexBuffer.add(::round(vertices[i * 2]), ::round(vertices[i * 2 + 1]));
|
||||
vertex_indices[i] = (TESSindex)total_vertex_count;
|
||||
@@ -156,7 +156,7 @@ void FillBucket::tessellate() {
|
||||
// coordinate in this polygon.
|
||||
assert(triangleGroups.back());
|
||||
TriangleGroup& triangleGroup = *triangleGroups.back();
|
||||
uint32_t triangleIndex = triangleGroup.vertex_length;
|
||||
GLsizei triangleIndex = triangleGroup.vertex_length;
|
||||
|
||||
for (int i = 0; i < triangle_count; ++i) {
|
||||
const TESSindex *element_group = &elements[i * vertices_per_group];
|
||||
@@ -216,8 +216,8 @@ bool FillBucket::hasData() const {
|
||||
}
|
||||
|
||||
void FillBucket::drawElements(PlainShader& shader) {
|
||||
char *vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
char *elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);
|
||||
GLbyte *vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
GLbyte *elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);
|
||||
for (auto& group : triangleGroups) {
|
||||
assert(group);
|
||||
group->array[0].bind(shader, vertexBuffer, triangleElementsBuffer, vertex_index);
|
||||
@@ -228,8 +228,8 @@ void FillBucket::drawElements(PlainShader& shader) {
|
||||
}
|
||||
|
||||
void FillBucket::drawElements(PatternShader& shader) {
|
||||
char *vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
char *elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);
|
||||
GLbyte *vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
GLbyte *elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);
|
||||
for (auto& group : triangleGroups) {
|
||||
assert(group);
|
||||
group->array[1].bind(shader, vertexBuffer, triangleElementsBuffer, vertex_index);
|
||||
@@ -240,8 +240,8 @@ void FillBucket::drawElements(PatternShader& shader) {
|
||||
}
|
||||
|
||||
void FillBucket::drawVertices(OutlineShader& shader) {
|
||||
char *vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
char *elements_index = BUFFER_OFFSET(line_elements_start * lineElementsBuffer.itemSize);
|
||||
GLbyte *vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
GLbyte *elements_index = BUFFER_OFFSET(line_elements_start * lineElementsBuffer.itemSize);
|
||||
for (auto& group : lineGroups) {
|
||||
assert(group);
|
||||
group->array[0].bind(shader, vertexBuffer, lineElementsBuffer, vertex_index);
|
||||
|
||||
@@ -54,9 +54,9 @@ private:
|
||||
LineElementsBuffer& lineElementsBuffer;
|
||||
|
||||
// hold information on where the vertices are located in the FillBuffer
|
||||
const size_t vertex_start;
|
||||
const size_t triangle_elements_start;
|
||||
const size_t line_elements_start;
|
||||
const GLsizei vertex_start;
|
||||
const GLsizei triangle_elements_start;
|
||||
const GLsizei line_elements_start;
|
||||
|
||||
std::vector<std::unique_ptr<TriangleGroup>> triangleGroups;
|
||||
std::vector<std::unique_ptr<LineGroup>> lineGroups;
|
||||
|
||||
@@ -32,8 +32,8 @@ void LineBucket::addGeometry(const GeometryCollection& geometryCollection) {
|
||||
}
|
||||
|
||||
void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
|
||||
const auto len = [&vertices] {
|
||||
auto l = vertices.size();
|
||||
const GLsizei len = [&vertices] {
|
||||
GLsizei l = static_cast<GLsizei>(vertices.size());
|
||||
// If the line has duplicate vertices at the end, adjust length to remove them.
|
||||
while (l > 2 && vertices[l - 1] == vertices[l - 2]) {
|
||||
l--;
|
||||
@@ -75,10 +75,10 @@ void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
|
||||
nextNormal = util::perp(util::unit(vec2<double>(firstVertex - currentVertex)));
|
||||
}
|
||||
|
||||
const int32_t startVertex = (int32_t)vertexBuffer.index();
|
||||
const GLint startVertex = vertexBuffer.index();
|
||||
std::vector<TriangleElement> triangleStore;
|
||||
|
||||
for (size_t i = 0; i < len; ++i) {
|
||||
for (GLsizei i = 0; i < len; ++i) {
|
||||
if (closed && i == len - 1) {
|
||||
// if the line is closed, we treat the last vertex like the first
|
||||
nextVertex = vertices[1];
|
||||
@@ -303,8 +303,8 @@ void LineBucket::addGeometry(const std::vector<Coordinate>& vertices) {
|
||||
startOfLine = false;
|
||||
}
|
||||
|
||||
const size_t endVertex = vertexBuffer.index();
|
||||
const size_t vertexCount = endVertex - startVertex;
|
||||
const GLsizei endVertex = vertexBuffer.index();
|
||||
const GLsizei vertexCount = endVertex - startVertex;
|
||||
|
||||
// Store the triangle/line groups.
|
||||
{
|
||||
@@ -333,16 +333,15 @@ void LineBucket::addCurrentVertex(const Coordinate& currentVertex,
|
||||
float endLeft,
|
||||
float endRight,
|
||||
bool round,
|
||||
int32_t startVertex,
|
||||
GLint startVertex,
|
||||
std::vector<TriangleElement>& triangleStore) {
|
||||
int8_t tx = round ? 1 : 0;
|
||||
|
||||
vec2<double> extrude = normal * flip;
|
||||
if (endLeft)
|
||||
extrude = extrude - (util::perp(normal) * endLeft);
|
||||
e3 = (int32_t)vertexBuffer.add(currentVertex.x, currentVertex.y, extrude.x, extrude.y, tx, 0,
|
||||
distance) -
|
||||
startVertex;
|
||||
e3 = vertexBuffer.add(currentVertex.x, currentVertex.y, extrude.x, extrude.y, tx, 0, distance)
|
||||
- startVertex;
|
||||
if (e1 >= 0 && e2 >= 0) {
|
||||
triangleStore.emplace_back(e1, e2, e3);
|
||||
}
|
||||
@@ -352,9 +351,8 @@ void LineBucket::addCurrentVertex(const Coordinate& currentVertex,
|
||||
extrude = normal * (-flip);
|
||||
if (endRight)
|
||||
extrude = extrude - (util::perp(normal) * endRight);
|
||||
e3 = (int32_t)vertexBuffer.add(currentVertex.x, currentVertex.y, extrude.x, extrude.y, tx, 1,
|
||||
distance) -
|
||||
startVertex;
|
||||
e3 = vertexBuffer.add(currentVertex.x, currentVertex.y, extrude.x, extrude.y, tx, 1, distance)
|
||||
- startVertex;
|
||||
if (e1 >= 0 && e2 >= 0) {
|
||||
triangleStore.emplace_back(e1, e2, e3);
|
||||
}
|
||||
@@ -367,13 +365,13 @@ void LineBucket::addPieSliceVertex(const Coordinate& currentVertex,
|
||||
double distance,
|
||||
const vec2<double>& extrude,
|
||||
bool lineTurnsLeft,
|
||||
int32_t startVertex,
|
||||
GLint startVertex,
|
||||
std::vector<TriangleElement>& triangleStore) {
|
||||
int8_t ty = lineTurnsLeft;
|
||||
|
||||
auto flippedExtrude = extrude * (flip * (lineTurnsLeft ? -1 : 1));
|
||||
e3 = (int32_t)vertexBuffer.add(currentVertex.x, currentVertex.y, flippedExtrude.x, flippedExtrude.y, 0, ty,
|
||||
distance) - startVertex;
|
||||
e3 = vertexBuffer.add(currentVertex.x, currentVertex.y, flippedExtrude.x, flippedExtrude.y, 0, ty, distance)
|
||||
- startVertex;
|
||||
if (e1 >= 0 && e2 >= 0) {
|
||||
triangleStore.emplace_back(e1, e2, e3);
|
||||
}
|
||||
@@ -405,8 +403,8 @@ bool LineBucket::hasData() const {
|
||||
}
|
||||
|
||||
void LineBucket::drawLines(LineShader& shader) {
|
||||
char* vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
char* elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);
|
||||
GLbyte* vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
GLbyte* elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);
|
||||
for (auto& group : triangleGroups) {
|
||||
assert(group);
|
||||
if (!group->elements_length) {
|
||||
@@ -421,8 +419,8 @@ void LineBucket::drawLines(LineShader& shader) {
|
||||
}
|
||||
|
||||
void LineBucket::drawLineSDF(LineSDFShader& shader) {
|
||||
char* vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
char* elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);
|
||||
GLbyte* vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
GLbyte* elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);
|
||||
for (auto& group : triangleGroups) {
|
||||
assert(group);
|
||||
if (!group->elements_length) {
|
||||
@@ -437,8 +435,8 @@ void LineBucket::drawLineSDF(LineSDFShader& shader) {
|
||||
}
|
||||
|
||||
void LineBucket::drawLinePatterns(LinepatternShader& shader) {
|
||||
char* vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
char* elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);
|
||||
GLbyte* vertex_index = BUFFER_OFFSET(vertex_start * vertexBuffer.itemSize);
|
||||
GLbyte* elements_index = BUFFER_OFFSET(triangle_elements_start * triangleElementsBuffer.itemSize);
|
||||
for (auto& group : triangleGroups) {
|
||||
assert(group);
|
||||
if (!group->elements_length) {
|
||||
|
||||
@@ -46,9 +46,9 @@ private:
|
||||
};
|
||||
void addCurrentVertex(const Coordinate& currentVertex, float flip, double distance,
|
||||
const vec2<double>& normal, float endLeft, float endRight, bool round,
|
||||
int32_t startVertex, std::vector<LineBucket::TriangleElement>& triangleStore);
|
||||
GLint startVertex, std::vector<LineBucket::TriangleElement>& triangleStore);
|
||||
void addPieSliceVertex(const Coordinate& currentVertex, float flip, double distance,
|
||||
const vec2<double>& extrude, bool lineTurnsLeft, int32_t startVertex,
|
||||
const vec2<double>& extrude, bool lineTurnsLeft, GLint startVertex,
|
||||
std::vector<TriangleElement>& triangleStore);
|
||||
|
||||
public:
|
||||
@@ -58,12 +58,12 @@ private:
|
||||
LineVertexBuffer& vertexBuffer;
|
||||
TriangleElementsBuffer& triangleElementsBuffer;
|
||||
|
||||
const size_t vertex_start;
|
||||
const size_t triangle_elements_start;
|
||||
const GLsizei vertex_start;
|
||||
const GLsizei triangle_elements_start;
|
||||
|
||||
int32_t e1;
|
||||
int32_t e2;
|
||||
int32_t e3;
|
||||
GLint e1;
|
||||
GLint e2;
|
||||
GLint e3;
|
||||
|
||||
std::vector<std::unique_ptr<TriangleGroup>> triangleGroups;
|
||||
};
|
||||
|
||||
@@ -117,14 +117,14 @@ void Painter::setDebug(bool enabled) {
|
||||
debug = enabled;
|
||||
}
|
||||
|
||||
void Painter::useProgram(uint32_t program) {
|
||||
void Painter::useProgram(GLuint program) {
|
||||
if (gl_program != program) {
|
||||
MBGL_CHECK_ERROR(glUseProgram(program));
|
||||
gl_program = program;
|
||||
}
|
||||
}
|
||||
|
||||
void Painter::lineWidth(float line_width) {
|
||||
void Painter::lineWidth(GLfloat line_width) {
|
||||
if (gl_lineWidth != line_width) {
|
||||
MBGL_CHECK_ERROR(glLineWidth(line_width));
|
||||
gl_lineWidth = line_width;
|
||||
@@ -235,7 +235,7 @@ void Painter::render(const Style& style, TransformState state_, const FrameData&
|
||||
// Make a second pass, rendering translucent objects. This time, we render bottom-to-top.
|
||||
renderPass(RenderPass::Translucent,
|
||||
order.begin(), order.end(),
|
||||
order.size() - 1, -1);
|
||||
static_cast<GLsizei>(order.size()) - 1, -1);
|
||||
|
||||
if (debug::renderTree) { Log::Info(Event::Render, "}"); indent--; }
|
||||
|
||||
@@ -266,7 +266,7 @@ void Painter::render(const Style& style, TransformState state_, const FrameData&
|
||||
template <class Iterator>
|
||||
void Painter::renderPass(RenderPass pass_,
|
||||
Iterator it, Iterator end,
|
||||
std::size_t i, int8_t increment) {
|
||||
GLsizei i, int8_t increment) {
|
||||
pass = pass_;
|
||||
|
||||
MBGL_DEBUG_GROUP(pass == RenderPass::Opaque ? "opaque" : "translucent");
|
||||
|
||||
@@ -143,7 +143,7 @@ private:
|
||||
template <class Iterator>
|
||||
void renderPass(RenderPass,
|
||||
Iterator it, Iterator end,
|
||||
std::size_t i, int8_t increment);
|
||||
GLsizei i, int8_t increment);
|
||||
|
||||
void prepareTile(const Tile& tile);
|
||||
|
||||
@@ -161,8 +161,8 @@ private:
|
||||
void setDepthSublayer(int n);
|
||||
|
||||
public:
|
||||
void useProgram(uint32_t program);
|
||||
void lineWidth(float lineWidth);
|
||||
void useProgram(GLuint program);
|
||||
void lineWidth(GLfloat lineWidth);
|
||||
|
||||
public:
|
||||
mat4 projMatrix;
|
||||
@@ -194,14 +194,14 @@ private:
|
||||
|
||||
gl::Config config;
|
||||
|
||||
uint32_t gl_program = 0;
|
||||
float gl_lineWidth = 0;
|
||||
GLuint gl_program = 0;
|
||||
GLfloat gl_lineWidth = 0;
|
||||
std::array<uint16_t, 2> gl_viewport = {{ 0, 0 }};
|
||||
RenderPass pass = RenderPass::Opaque;
|
||||
Color background = {{ 0, 0, 0, 0 }};
|
||||
|
||||
int numSublayers = 3;
|
||||
size_t currentLayer;
|
||||
GLsizei currentLayer;
|
||||
float depthRangeSize;
|
||||
const float depthEpsilon = 1.0f / (1 << 16);
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ void Painter::drawClippingMasks(const std::set<Source*>& sources) {
|
||||
config.colorMask = { false, false, false, false };
|
||||
config.depthRange = { 1.0f, 1.0f };
|
||||
|
||||
coveringPlainArray.bind(*plainShader, tileStencilBuffer, BUFFER_OFFSET(0));
|
||||
coveringPlainArray.bind(*plainShader, tileStencilBuffer, BUFFER_OFFSET_0);
|
||||
|
||||
for (const auto& source : sources) {
|
||||
source->drawClippingMasks(*this);
|
||||
|
||||
@@ -59,7 +59,7 @@ void Painter::renderDebugFrame(const mat4 &matrix) {
|
||||
plainShader->u_matrix = matrix;
|
||||
|
||||
// draw tile outline
|
||||
tileBorderArray.bind(*plainShader, tileBorderBuffer, BUFFER_OFFSET(0));
|
||||
tileBorderArray.bind(*plainShader, tileBorderBuffer, BUFFER_OFFSET_0);
|
||||
plainShader->u_color = {{ 1.0f, 0.0f, 0.0f, 1.0f }};
|
||||
lineWidth(4.0f * data.pixelRatio);
|
||||
MBGL_CHECK_ERROR(glDrawArrays(GL_LINE_STRIP, 0, (GLsizei)tileBorderBuffer.index()));
|
||||
|
||||
@@ -30,7 +30,7 @@ bool RasterBucket::setImage(std::unique_ptr<util::Image> image) {
|
||||
void RasterBucket::drawRaster(RasterShader& shader, StaticVertexBuffer &vertices, VertexArrayObject &array) {
|
||||
raster.bind(true);
|
||||
shader.u_image = 0;
|
||||
array.bind(shader, vertices, BUFFER_OFFSET(0));
|
||||
array.bind(shader, vertices, BUFFER_OFFSET_0);
|
||||
MBGL_CHECK_ERROR(glDrawArrays(GL_TRIANGLES, 0, (GLsizei)vertices.index()));
|
||||
}
|
||||
|
||||
|
||||
@@ -103,7 +103,8 @@ bool SymbolBucket::needsDependencies(const GeometryTileLayer& layer,
|
||||
// Determine and load glyph ranges
|
||||
std::set<GlyphRange> ranges;
|
||||
|
||||
for (std::size_t i = 0; i < layer.featureCount(); i++) {
|
||||
const GLsizei featureCount = static_cast<GLsizei>(layer.featureCount());
|
||||
for (GLsizei i = 0; i < featureCount; i++) {
|
||||
auto feature = layer.getFeature(i);
|
||||
|
||||
GeometryTileFeatureExtractor extractor(*feature);
|
||||
@@ -488,7 +489,7 @@ void SymbolBucket::addSymbols(Buffer &buffer, const SymbolQuads &symbols, float
|
||||
// coordinate in this polygon.
|
||||
assert(buffer.groups.back());
|
||||
auto &triangleGroup = *buffer.groups.back();
|
||||
uint32_t triangleIndex = triangleGroup.vertex_length;
|
||||
GLsizei triangleIndex = triangleGroup.vertex_length;
|
||||
|
||||
// coordinates (2 triangles)
|
||||
buffer.vertices.add(anchorPoint.x, anchorPoint.y, tl.x, tl.y, tex.x, tex.y, minZoom,
|
||||
@@ -565,8 +566,8 @@ void SymbolBucket::swapRenderData() {
|
||||
}
|
||||
|
||||
void SymbolBucket::drawGlyphs(SDFShader &shader) {
|
||||
char *vertex_index = BUFFER_OFFSET(0);
|
||||
char *elements_index = BUFFER_OFFSET(0);
|
||||
GLbyte *vertex_index = BUFFER_OFFSET_0;
|
||||
GLbyte *elements_index = BUFFER_OFFSET_0;
|
||||
auto& text = renderData->text;
|
||||
for (auto &group : text.groups) {
|
||||
assert(group);
|
||||
@@ -578,8 +579,8 @@ void SymbolBucket::drawGlyphs(SDFShader &shader) {
|
||||
}
|
||||
|
||||
void SymbolBucket::drawIcons(SDFShader &shader) {
|
||||
char *vertex_index = BUFFER_OFFSET(0);
|
||||
char *elements_index = BUFFER_OFFSET(0);
|
||||
GLbyte *vertex_index = BUFFER_OFFSET_0;
|
||||
GLbyte *elements_index = BUFFER_OFFSET_0;
|
||||
auto& icon = renderData->icon;
|
||||
for (auto &group : icon.groups) {
|
||||
assert(group);
|
||||
@@ -591,8 +592,8 @@ void SymbolBucket::drawIcons(SDFShader &shader) {
|
||||
}
|
||||
|
||||
void SymbolBucket::drawIcons(IconShader &shader) {
|
||||
char *vertex_index = BUFFER_OFFSET(0);
|
||||
char *elements_index = BUFFER_OFFSET(0);
|
||||
GLbyte *vertex_index = BUFFER_OFFSET_0;
|
||||
GLbyte *elements_index = BUFFER_OFFSET_0;
|
||||
auto& icon = renderData->icon;
|
||||
for (auto &group : icon.groups) {
|
||||
assert(group);
|
||||
@@ -604,7 +605,7 @@ void SymbolBucket::drawIcons(IconShader &shader) {
|
||||
}
|
||||
|
||||
void SymbolBucket::drawCollisionBoxes(CollisionBoxShader &shader) {
|
||||
char *vertex_index = BUFFER_OFFSET(0);
|
||||
GLbyte *vertex_index = BUFFER_OFFSET_0;
|
||||
auto& collisionBox = renderData->collisionBox;
|
||||
for (auto &group : collisionBox.groups) {
|
||||
group->array[0].bind(shader, collisionBox.vertices, vertex_index);
|
||||
|
||||
@@ -12,13 +12,12 @@ CollisionBoxShader::CollisionBoxShader()
|
||||
shaders[BOX_SHADER].vertex,
|
||||
shaders[BOX_SHADER].fragment
|
||||
) {
|
||||
a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos"));
|
||||
a_extrude = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_extrude"));
|
||||
a_data = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_data"));
|
||||
}
|
||||
|
||||
void CollisionBoxShader::bind(char *offset) {
|
||||
const int stride = 12;
|
||||
void CollisionBoxShader::bind(GLbyte *offset) {
|
||||
const GLint stride = 12;
|
||||
|
||||
MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos));
|
||||
MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, stride, offset + 0));
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#include <mbgl/shader/shader.hpp>
|
||||
#include <mbgl/shader/uniform.hpp>
|
||||
#include <mbgl/platform/gl.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
|
||||
@@ -10,19 +11,18 @@ class CollisionBoxShader : public Shader {
|
||||
public:
|
||||
CollisionBoxShader();
|
||||
|
||||
void bind(char *offset);
|
||||
void bind(GLbyte *offset) final;
|
||||
|
||||
UniformMatrix<4> u_matrix = {"u_matrix", *this};
|
||||
Uniform<float> u_scale = {"u_scale", *this};
|
||||
Uniform<float> u_zoom = {"u_zoom", *this};
|
||||
Uniform<float> u_maxzoom = {"u_maxzoom", *this};
|
||||
Uniform<GLfloat> u_scale = {"u_scale", *this};
|
||||
Uniform<GLfloat> u_zoom = {"u_zoom", *this};
|
||||
Uniform<GLfloat> u_maxzoom = {"u_maxzoom", *this};
|
||||
|
||||
protected:
|
||||
int32_t a_pos = -1;
|
||||
int32_t a_extrude = -1;
|
||||
int32_t a_data = -1;
|
||||
GLint a_extrude = -1;
|
||||
GLint a_data = -1;
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace mbgl
|
||||
|
||||
#endif
|
||||
#endif // MBGL_SHADER_BOX_SHADER
|
||||
|
||||
@@ -12,10 +12,9 @@ CircleShader::CircleShader()
|
||||
shaders[CIRCLE_SHADER].vertex,
|
||||
shaders[CIRCLE_SHADER].fragment
|
||||
) {
|
||||
a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos"));
|
||||
}
|
||||
|
||||
void CircleShader::bind(char *offset) {
|
||||
void CircleShader::bind(GLbyte *offset) {
|
||||
MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos));
|
||||
MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, 4, offset));
|
||||
}
|
||||
|
||||
@@ -10,16 +10,13 @@ class CircleShader : public Shader {
|
||||
public:
|
||||
CircleShader();
|
||||
|
||||
void bind(char *offset);
|
||||
void bind(GLbyte *offset) final;
|
||||
|
||||
UniformMatrix<4> u_matrix = {"u_matrix", *this};
|
||||
UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this};
|
||||
Uniform<std::array<float, 4>> u_color = {"u_color", *this};
|
||||
Uniform<float> u_size = {"u_size", *this};
|
||||
Uniform<float> u_blur = {"u_blur", *this};
|
||||
|
||||
private:
|
||||
int32_t a_pos = -1;
|
||||
UniformMatrix<4> u_matrix = {"u_matrix", *this};
|
||||
UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this};
|
||||
Uniform<std::array<GLfloat, 4>> u_color = {"u_color", *this};
|
||||
Uniform<GLfloat> u_size = {"u_size", *this};
|
||||
Uniform<GLfloat> u_blur = {"u_blur", *this};
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user