diff --git a/.gitignore b/.gitignore index 123bf8cba..bd6707ba9 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/.mason b/.mason index d8597d944..36dc9282d 160000 --- a/.mason +++ b/.mason @@ -1 +1 @@ -Subproject commit d8597d944533dbb5e28d08dfdba22a82c93171b7 +Subproject commit 36dc9282d7b79b4533c511529d6f83fe5719f673 diff --git a/.travis.yml b/.travis.yml index 091fd1e8f..f9d22b51e 100644 --- a/.travis.yml +++ b/.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 diff --git a/CHANGELOG.md b/CHANGELOG.md index c1b3e3003..f2a33b100 100644 --- a/CHANGELOG.md +++ b/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. diff --git a/INSTALL.md b/INSTALL.md index fcc5d90c6..cb72c55a9 100644 --- a/INSTALL.md +++ b/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": + +![image](https://cloud.githubusercontent.com/assets/98601/9915837/289f398e-5c6e-11e5-9a84-ed4d08d52d1f.png) + 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": + +![image](https://cloud.githubusercontent.com/assets/98601/9915837/289f398e-5c6e-11e5-9a84-ed4d08d52d1f.png) + 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 diff --git a/Makefile b/Makefile index c69e426dd..9f727abc2 100644 --- a/Makefile +++ b/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 diff --git a/README.md b/README.md index c54afa28f..00432f17c 100644 --- a/README.md +++ b/README.md @@ -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 -- diff --git a/android/cpp/jni.cpp b/android/cpp/jni.cpp index 5ed0a730c..dcf64eed2 100644 --- a/android/cpp/jni.cpp +++ b/android/cpp/jni.cpp @@ -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(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(&nativePause)}, {"nativeResume", "(J)V", reinterpret_cast(&nativeResume)}, {"nativeUpdate", "(J)V", reinterpret_cast(&nativeUpdate)}, - {"nativeOnInvalidate", "(J)V", reinterpret_cast(&nativeOnInvalidate)}, + {"nativeRenderSync", "(J)V", reinterpret_cast(&nativeRenderSync)}, {"nativeViewResize", "(JII)V", reinterpret_cast(static_cast(&nativeViewResize))}, diff --git a/android/cpp/native_map_view.cpp b/android/cpp/native_map_view.cpp index cc04f089e..31fb5453a 100644 --- a/android/cpp/native_map_view.cpp +++ b/android/cpp/native_map_view.cpp @@ -78,6 +78,16 @@ NativeMapView::NativeMapView(JNIEnv *env, jobject obj_, float pixelRatio_, int a fileSource = std::make_unique(fileCache.get()); map = std::make_unique(*this, *fileSource, MapMode::Continuous); + float zoomFactor = map->getMaxZoom() - map->getMinZoom() + 1; + float cpuFactor = availableProcessors; + float memoryFactor = static_cast(totalMemory) / 1000.0f / 1000.0f / 1000.0f; + float sizeFactor = (static_cast(map->getWidth()) / mbgl::util::tileSize) * + (static_cast(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(totalMemory) / 1000.0f / 1000.0f / 1000.0f; - float sizeFactor = (static_cast(map->getWidth()) / mbgl::util::tileSize) * - (static_cast(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) { diff --git a/android/java/.gitignore b/android/java/.gitignore index 866441810..626b99594 100644 --- a/android/java/.gitignore +++ b/android/java/.gitignore @@ -10,6 +10,10 @@ build/ *.so *.apk +# JNI +MapboxGLAndroidSDK/src/main/jniLibs/ +MapboxGLAndroidSDK/src/main/obj.target/ + # Lib assets MapboxGLAndroidSDK/src/main/assets/ diff --git a/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/MapView.java b/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/MapView.java index a3b53ae37..aeb744bbc 100644 --- a/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/MapView.java +++ b/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/MapView.java @@ -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 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) { diff --git a/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/NativeMapView.java b/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/NativeMapView.java index 3cf56a8de..1023fa1ff 100644 --- a/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/NativeMapView.java +++ b/android/java/MapboxGLAndroidSDK/src/main/java/com/mapbox/mapboxgl/views/NativeMapView.java @@ -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); diff --git a/android/java/MapboxGLAndroidSDKTestApp/README.md b/android/java/MapboxGLAndroidSDKTestApp/README.md new file mode 100644 index 000000000..646f29c4b --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/README.md @@ -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 +``` diff --git a/android/java/MapboxGLAndroidSDKTestApp/build.gradle b/android/java/MapboxGLAndroidSDKTestApp/build.gradle index 172f31d0f..a04279edd 100644 --- a/android/java/MapboxGLAndroidSDKTestApp/build.gradle +++ b/android/java/MapboxGLAndroidSDKTestApp/build.gradle @@ -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 { diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/BaseTest.java b/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/BaseTest.java new file mode 100644 index 000000000..f3ae2018c --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/BaseTest.java @@ -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); + } + }); + + } + +} diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/MainActivityScreenTest.java b/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/MainActivityScreenTest.java new file mode 100644 index 000000000..80dc0aa77 --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/MainActivityScreenTest.java @@ -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 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"); + } + +} diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/MainActivityTest.java b/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/MainActivityTest.java new file mode 100644 index 000000000..b880176fe --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/MainActivityTest.java @@ -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 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())); + } + +} diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/SecondMapActivityTest.java b/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/SecondMapActivityTest.java new file mode 100644 index 000000000..593b0b2ee --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/SecondMapActivityTest.java @@ -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 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())); + } + +} diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/utils/ScreenshotUtil.java b/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/utils/ScreenshotUtil.java new file mode 100644 index 000000000..258a38923 --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/androidTest/java/com/mapbox/mapboxgl/testapp/utils/ScreenshotUtil.java @@ -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 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 getAllTextureViews(View view) + { + List tilingViews = new ArrayList(); + 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; + } + +} diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/main/AndroidManifest.xml b/android/java/MapboxGLAndroidSDKTestApp/src/main/AndroidManifest.xml index 85be72bb7..f91c57e7e 100644 --- a/android/java/MapboxGLAndroidSDKTestApp/src/main/AndroidManifest.xml +++ b/android/java/MapboxGLAndroidSDKTestApp/src/main/AndroidManifest.xml @@ -17,6 +17,7 @@ + @@ -25,4 +26,5 @@ + diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/main/java/com/mapbox/mapboxgl/testapp/MainActivity.java b/android/java/MapboxGLAndroidSDKTestApp/src/main/java/com/mapbox/mapboxgl/testapp/MainActivity.java index f81717ae5..2f9b374e2 100644 --- a/android/java/MapboxGLAndroidSDKTestApp/src/main/java/com/mapbox/mapboxgl/testapp/MainActivity.java +++ b/android/java/MapboxGLAndroidSDKTestApp/src/main/java/com/mapbox/mapboxgl/testapp/MainActivity.java @@ -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); diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/main/java/com/mapbox/mapboxgl/testapp/SecondMapActivity.java b/android/java/MapboxGLAndroidSDKTestApp/src/main/java/com/mapbox/mapboxgl/testapp/SecondMapActivity.java new file mode 100644 index 000000000..976140ffc --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/main/java/com/mapbox/mapboxgl/testapp/SecondMapActivity.java @@ -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); + } + } +} diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-hdpi/ic_looks_two_white_24dp.png b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-hdpi/ic_looks_two_white_24dp.png new file mode 100644 index 000000000..2c9cf5b3a Binary files /dev/null and b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-hdpi/ic_looks_two_white_24dp.png differ diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-mdpi/ic_looks_two_white_24dp.png b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-mdpi/ic_looks_two_white_24dp.png new file mode 100644 index 000000000..e48d75421 Binary files /dev/null and b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-mdpi/ic_looks_two_white_24dp.png differ diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-xhdpi/ic_looks_two_white_24dp.png b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-xhdpi/ic_looks_two_white_24dp.png new file mode 100644 index 000000000..c9fc6633e Binary files /dev/null and b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-xhdpi/ic_looks_two_white_24dp.png differ diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-xxhdpi/ic_looks_two_white_24dp.png b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-xxhdpi/ic_looks_two_white_24dp.png new file mode 100644 index 000000000..f8ab38aa6 Binary files /dev/null and b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-xxhdpi/ic_looks_two_white_24dp.png differ diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-xxxhdpi/ic_looks_two_white_24dp.png b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-xxxhdpi/ic_looks_two_white_24dp.png new file mode 100644 index 000000000..bb2f2e434 Binary files /dev/null and b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/drawable-xxxhdpi/ic_looks_two_white_24dp.png differ diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/main/res/layout/activity_second.xml b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/layout/activity_second.xml new file mode 100644 index 000000000..2ffda1daa --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/layout/activity_second.xml @@ -0,0 +1,21 @@ + + + + + + + + diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/main/res/menu/menu_drawer.xml b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/menu/menu_drawer.xml index a374ab18d..ff537aaf3 100644 --- a/android/java/MapboxGLAndroidSDKTestApp/src/main/res/menu/menu_drawer.xml +++ b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/menu/menu_drawer.xml @@ -19,18 +19,24 @@ android:checkable="true" /> - + diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/main/res/values/strings.xml b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/values/strings.xml index 403da277c..836951cc5 100644 --- a/android/java/MapboxGLAndroidSDKTestApp/src/main/res/values/strings.xml +++ b/android/java/MapboxGLAndroidSDKTestApp/src/main/res/values/strings.xml @@ -3,6 +3,8 @@ Mapbox GL + Second Activity + Toggle GPS location Disable tracking Use follow tracking mode @@ -10,6 +12,7 @@ Toggle compass Toggle debug mode Toggle point annotations + Launch 2nd Map FPS: diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/test/java/BoundingBoxTest.java b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/BoundingBoxTest.java new file mode 100644 index 000000000..a94bbc773 --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/BoundingBoxTest.java @@ -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); + } + +} diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/test/java/CoordinateRegionTest.java b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/CoordinateRegionTest.java new file mode 100644 index 000000000..9672d9da5 --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/CoordinateRegionTest.java @@ -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); + } + +} diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/test/java/CoordinateSpanTest.java b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/CoordinateSpanTest.java new file mode 100644 index 000000000..0ccb76624 --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/CoordinateSpanTest.java @@ -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); + } + +} diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/test/java/LatLngTest.java b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/LatLngTest.java new file mode 100644 index 000000000..a3065789b --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/LatLngTest.java @@ -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); + } + +} diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/test/java/LatLngZoomTest.java b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/LatLngZoomTest.java new file mode 100644 index 000000000..7b6dfbde7 --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/LatLngZoomTest.java @@ -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); + } + +} diff --git a/android/java/MapboxGLAndroidSDKTestApp/src/test/java/ProjectedMetersTest.java b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/ProjectedMetersTest.java new file mode 100644 index 000000000..39655bdf3 --- /dev/null +++ b/android/java/MapboxGLAndroidSDKTestApp/src/test/java/ProjectedMetersTest.java @@ -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); + } + +} diff --git a/android/mapboxgl-app.gypi b/android/mapboxgl-app.gypi index e32775ff7..74415df7b 100644 --- a/android/mapboxgl-app.gypi +++ b/android/mapboxgl-app.gypi @@ -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': [ diff --git a/bin/render.cpp b/bin/render.cpp index 3da0c9358..2248d8603 100644 --- a/bin/render.cpp +++ b/bin/render.cpp @@ -9,13 +9,17 @@ #include #include +#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 #pragma GCC diagnostic pop +#pragma clang diagnostic pop namespace po = boost::program_options; diff --git a/gyp/platform-ios.gypi b/gyp/platform-ios.gypi index 6234f4d88..f639051c6 100644 --- a/gyp/platform-ios.gypi +++ b/gyp/platform-ios.gypi @@ -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', diff --git a/include/mbgl/android/native_map_view.hpp b/include/mbgl/android/native_map_view.hpp index fe619ba6f..0908f7563 100644 --- a/include/mbgl/android/native_map_view.hpp +++ b/include/mbgl/android/native_map_view.hpp @@ -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 fileCache; std::unique_ptr fileSource; std::unique_ptr map; - - std::atomic_flag clean = ATOMIC_FLAG_INIT; }; } } diff --git a/include/mbgl/ios/MGLGeometry.h b/include/mbgl/ios/MGLGeometry.h index 6226af1d0..847b7cc04 100644 --- a/include/mbgl/ios/MGLGeometry.h +++ b/include/mbgl/ios/MGLGeometry.h @@ -3,6 +3,7 @@ #import "MGLTypes.h" #import +#import 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 diff --git a/include/mbgl/ios/MGLPolyline.h b/include/mbgl/ios/MGLPolyline.h index 7cbbadeca..07c5286c8 100644 --- a/include/mbgl/ios/MGLPolyline.h +++ b/include/mbgl/ios/MGLPolyline.h @@ -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 -/** 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. */ diff --git a/ios/Mapbox-iOS-SDK.podspec b/ios/Mapbox-iOS-SDK.podspec index 099a84c8a..139ad655f 100644 --- a/ios/Mapbox-iOS-SDK.podspec +++ b/ios/Mapbox-iOS-SDK.podspec @@ -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.' diff --git a/ios/app/MBXViewController.mm b/ios/app/MBXViewController.mm index b32371770..bb35a0791 100644 --- a/ios/app/MBXViewController.mm +++ b/ios/app/MBXViewController.mm @@ -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"]; } } diff --git a/ios/app/app-info.plist b/ios/app/app-info.plist index 665324693..d497d09e7 100644 --- a/ios/app/app-info.plist +++ b/ios/app/app-info.plist @@ -60,5 +60,7 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight + NSLocationAlwaysUsageDescription + The map will ALWAYS display the user's location. diff --git a/macosx/main.mm b/macosx/main.mm index 24251e6d4..7698773e7 100644 --- a/macosx/main.mm +++ b/macosx/main.mm @@ -12,13 +12,17 @@ #import +#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 #pragma GCC diagnostic pop +#pragma clang diagnostic pop #include diff --git a/package.json b/package.json index 0fd6887ba..69f75a4fc 100644 --- a/package.json +++ b/package.json @@ -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" }, diff --git a/platform/default/headless_view.cpp b/platform/default/headless_view.cpp index a582ed579..0e688163a 100644 --- a/platform/default/headless_view.cpp +++ b/platform/default/headless_view.cpp @@ -202,7 +202,7 @@ void HeadlessView::clearBuffers() { } if (fboColor) { - MBGL_CHECK_ERROR(glDeleteTextures(1, &fboColor)); + MBGL_CHECK_ERROR(glDeleteRenderbuffersEXT(1, &fboColor)); fboColor = 0; } diff --git a/platform/ios/MGLFileCache.h b/platform/ios/MGLFileCache.h deleted file mode 100644 index 082cec69a..000000000 --- a/platform/ios/MGLFileCache.h +++ /dev/null @@ -1,14 +0,0 @@ -#import "MGLTypes.h" - -#include - -NS_ASSUME_NONNULL_BEGIN - -@interface MGLFileCache : NSObject - -+ (mbgl::SQLiteCache *)obtainSharedCacheWithObject:(NSObject *)object; -+ (void)releaseSharedCacheForObject:(NSObject *)object; - -@end - -NS_ASSUME_NONNULL_END diff --git a/platform/ios/MGLFileCache.mm b/platform/ios/MGLFileCache.mm deleted file mode 100644 index 3303b395f..000000000 --- a/platform/ios/MGLFileCache.mm +++ /dev/null @@ -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 diff --git a/platform/ios/MGLMapView.mm b/platform/ios/MGLMapView.mm index e509b5c8d..a2f67c7bb 100644 --- a/platform/ios/MGLMapView.mm +++ b/platform/ios/MGLMapView.mm @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -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 _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; diff --git a/platform/ios/MGLUserLocationAnnotationView.m b/platform/ios/MGLUserLocationAnnotationView.m index 7733674e6..b477b1088 100644 --- a/platform/ios/MGLUserLocationAnnotationView.m +++ b/platform/ios/MGLUserLocationAnnotationView.m @@ -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; } diff --git a/platform/node/CHANGELOG.md b/platform/node/CHANGELOG.md index 6d6486bd2..d4b0abd49 100644 --- a/platform/node/CHANGELOG.md +++ b/platform/node/CHANGELOG.md @@ -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 diff --git a/platform/node/README.md b/platform/node/README.md index 72a08e853..dfe5d909f 100644 --- a/platform/node/README.md +++ b/platform/node/README.md @@ -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)); } }); }, diff --git a/platform/node/src/node_file_source.cpp b/platform/node/src/node_file_source.cpp index 204e85a12..b4828e768 100644 --- a/platform/node/src/node_file_source.cpp +++ b/platform/node/src/node_file_source.cpp @@ -11,7 +11,7 @@ struct NodeFileSource::Action { mbgl::Resource const resource; }; -NodeFileSource::NodeFileSource(v8::Handle options_) : +NodeFileSource::NodeFileSource(v8::Local 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 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(NodeRequest::Create(this, resource)); + auto requestHandle = NodeRequest::Create(this, resource)->ToObject(); + pending.emplace(resource, requestHandle); - v8::Persistent requestPersistent; - NanAssignPersistent(requestPersistent, requestHandle); - pending.emplace(resource, std::move(requestPersistent)); + auto callback = Nan::GetFunction(Nan::New(NodeRequest::Respond, requestHandle)).ToLocalChecked(); + callback->SetName(Nan::New("respond").ToLocalChecked()); -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - auto requestFunction = v8::Local::New(v8::Isolate::GetCurrent(), options)->Get(NanNew("request")).As(); -#else - auto requestFunction = options->Get(NanNew("request")).As(); -#endif - - v8::Local argv[] = { requestHandle }; - NanMakeCallback(NanGetCurrentContext()->Global(), requestFunction, 1, argv); + v8::Local 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::New(v8::Isolate::GetCurrent(), it->second); + v8::Local requestHandle = Nan::New(it->second); it->second.Reset(); -#else - auto requestHandle = NanNew(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::New(v8::Isolate::GetCurrent(), options); - if (optionsObject->Has(NanNew("cancel"))) { - auto cancelFunction = optionsObject->Get(NanNew("cancel")).As(); -#else - if (options->Has(NanNew("cancel"))) { - auto cancelFunction = options->Get(NanNew("cancel")).As(); -#endif + if (Nan::Has(Nan::New(options), Nan::New("cancel").ToLocalChecked()).FromJust()) { v8::Local 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(requestHandle)->cancel(); + Nan::ObjectWrap::Unwrap(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. diff --git a/platform/node/src/node_file_source.hpp b/platform/node/src/node_file_source.hpp index f412bdee1..038765cb2 100644 --- a/platform/node/src/node_file_source.hpp +++ b/platform/node/src/node_file_source.hpp @@ -5,8 +5,6 @@ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wshadow" -#include -#include #include #pragma GCC diagnostic pop @@ -20,7 +18,7 @@ namespace util { template class AsyncQueue; } class NodeFileSource : public mbgl::FileSource { public: - NodeFileSource(v8::Handle); + NodeFileSource(v8::Local); ~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 options; + Nan::Persistent options; private: -#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) - std::unordered_map>, mbgl::Resource::Hash> pending; -#else - std::unordered_map, mbgl::Resource::Hash> pending; -#endif + std::unordered_map, 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 diff --git a/platform/node/src/node_log.cpp b/platform/node/src/node_log.cpp index 637534807..8230bb36c 100644 --- a/platform/node/src/node_log.cpp +++ b/platform/node/src/node_log.cpp @@ -16,27 +16,35 @@ struct NodeLogObserver::LogMessage { text(text_) {} }; -NodeLogObserver::NodeLogObserver(v8::Handle target) +NodeLogObserver::NodeLogObserver(v8::Local target) : queue(new Queue(uv_default_loop(), [this](LogMessage &message) { - NanScope(); + Nan::HandleScope scope; + + auto msg = Nan::New(); + + 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(); - 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(message.code)); - } - if (!message.text.empty()) { - msg->Set(NanNew("text"), NanNew(message.text)); + Nan::Set(msg, Nan::New("code").ToLocalChecked(), + Nan::New(message.code)); } - v8::Local argv[] = { NanNew("message"), msg }; - auto handle = NanNew(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 argv[] = { Nan::New("message").ToLocalChecked(), msg }; + auto handle = Nan::New(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 target) NodeLogObserver::~NodeLogObserver() { queue->stop(); + module.Reset(); } bool NodeLogObserver::onRecord(mbgl::EventSeverity severity, mbgl::Event event, int64_t code, const std::string &text) { diff --git a/platform/node/src/node_log.hpp b/platform/node/src/node_log.hpp index 5c0048d26..d29e4e28e 100644 --- a/platform/node/src/node_log.hpp +++ b/platform/node/src/node_log.hpp @@ -5,7 +5,6 @@ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wshadow" -#include #include #pragma GCC diagnostic pop @@ -15,14 +14,14 @@ namespace util { template class AsyncQueue; } class NodeLogObserver : public mbgl::Log::Observer { public: - NodeLogObserver(v8::Handle target); + NodeLogObserver(v8::Local 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 module; + Nan::Persistent module; struct LogMessage; using Queue = util::AsyncQueue; diff --git a/platform/node/src/node_map.cpp b/platform/node/src/node_map.cpp index b624e32e6..f1abf4806 100644 --- a/platform/node/src/node_map.cpp +++ b/platform/node/src/node_map.cpp @@ -21,7 +21,7 @@ struct NodeMap::RenderOptions { //////////////////////////////////////////////////////////////////////////////////////////////// // Static Node Methods -v8::Persistent NodeMap::constructorTemplate; +Nan::Persistent NodeMap::constructor; static std::shared_ptr sharedDisplay() { static auto display = std::make_shared(); @@ -32,127 +32,137 @@ const static char* releasedMessage() { return "Map resources have already been released"; } -void NodeMap::Init(v8::Handle target) { - NanScope(); +NAN_MODULE_INIT(NodeMap::Init) { + v8::Local tpl = Nan::New(New); - v8::Local t = NanNew(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 styleHandle) { - NanScope(); +const std::string StringifyStyle(v8::Local styleHandle) { + Nan::HandleScope scope; - auto JSON = NanGetCurrentContext()->Global()->Get(NanNew("JSON"))->ToObject(); - auto stringify = v8::Handle::Cast(JSON->Get(NanNew("stringify"))); + v8::Local 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(info.Holder()); - auto nodeMap = node::ObjectWrap::Unwrap(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::ParseOptions(v8::Local obj) { - NanScope(); + Nan::HandleScope scope; auto options = std::make_unique(); - 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(); - 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(); + 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(); + 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(); 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::ParseOptions(v8::Local(info.Holder()); - auto nodeMap = node::ObjectWrap::Unwrap(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(new NanCallback(args[1].As())); + nodeMap->callback = std::make_unique(info[1].As()); 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 options) { @@ -221,7 +233,7 @@ void NodeMap::startRender(std::unique_ptr 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(async)); @@ -249,7 +261,7 @@ void NodeMap::renderFinished() { } v8::Local 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 pixels = NanNewBufferHandle( + v8::Local pixels = Nan::NewBuffer( reinterpret_cast(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(hint); }, const_cast(img.get()) - ); + ).ToLocalChecked(); img.release(); v8::Local argv[] = { - NanNull(), - pixels, + Nan::Null(), + pixels }; cb->Call(2, argv); } else { v8::Local 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(info.Holder()); - auto nodeMap = node::ObjectWrap::Unwrap(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 options) : - view(sharedDisplay(), options->Get(NanNew("ratio"))->NumberValue()), +NodeMap::NodeMap(v8::Local options) : + view(sharedDisplay(), [&] { + Nan::HandleScope scope; + return Nan::Get(options, Nan::New("ratio").ToLocalChecked()).ToLocalChecked()->NumberValue(); + }()), fs(options), map(std::make_unique(view, fs, mbgl::MapMode::Still)), async(new uv_async_t) { diff --git a/platform/node/src/node_map.hpp b/platform/node/src/node_map.hpp index 2c87900d4..90edf44f7 100644 --- a/platform/node/src/node_map.hpp +++ b/platform/node/src/node_map.hpp @@ -8,7 +8,6 @@ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wshadow" -#include #include #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 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 ParseOptions(v8::Local obj); + static std::unique_ptr ParseOptions(v8::Local); + static Nan::Persistent constructor; - static v8::Persistent constructorTemplate; - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Instance private: - NodeMap(v8::Handle); + NodeMap(v8::Local); ~NodeMap(); -private: mbgl::HeadlessView view; NodeFileSource fs; std::unique_ptr map; std::exception_ptr error; std::unique_ptr image; - std::unique_ptr callback; + std::unique_ptr callback; // Async for delivering the notifications of render completion. uv_async_t *async; diff --git a/platform/node/src/node_mapbox_gl_native.cpp b/platform/node/src/node_mapbox_gl_native.cpp index 14a0c9ad2..c0fb47d14 100644 --- a/platform/node/src/node_mapbox_gl_native.cpp +++ b/platform/node/src/node_mapbox_gl_native.cpp @@ -9,30 +9,57 @@ #include "node_log.hpp" #include "node_request.hpp" -void RegisterModule(v8::Handle 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::ReadOnly | v8::DontDelete); - auto resource = NanNew(); - 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 resource = Nan::New(); - // 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(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 process = Nan::Get( + Nan::GetCurrentContext()->Global(), + Nan::New("process").ToLocalChecked()).ToLocalChecked()->ToObject(); + + v8::Local 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(target->ToObject())); } NODE_MODULE(mapbox_gl_native, RegisterModule) diff --git a/platform/node/src/node_request.cpp b/platform/node/src/node_request.cpp index ea9fc4d73..76cafacbd 100644 --- a/platform/node/src/node_request.cpp +++ b/platform/node/src/node_request.cpp @@ -11,112 +11,109 @@ namespace node_mbgl { //////////////////////////////////////////////////////////////////////////////////////////////// // Static Node Methods -v8::Persistent NodeRequest::constructorTemplate; +Nan::Persistent NodeRequest::constructor; -void NodeRequest::Init(v8::Handle target) { - NanScope(); +NAN_MODULE_INIT(NodeRequest::Init) { + v8::Local tpl = Nan::New(New); - v8::Local t = NanNew(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(args[0].As()->Value()); - auto resource = reinterpret_cast(args[1].As()->Value()); + auto source = reinterpret_cast(info[0].As()->Value()); + auto resource = reinterpret_cast(info[1].As()->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 NodeRequest::Create(NodeFileSource* source, const mbgl::Resource& resource) { - NanEscapableScope(); + Nan::EscapableHandleScope scope; - v8::Local argv[] = { NanNew(const_cast(source)), - NanNew(const_cast(&resource)) }; - auto instance = NanNew(constructorTemplate)->GetFunction()->NewInstance(2, argv); + v8::Local argv[] = { + Nan::New(const_cast(source)), + Nan::New(const_cast(&resource)) + }; + auto instance = Nan::New(constructor)->NewInstance(2, argv); - instance->ForceSet(NanNew("url"), NanNew(resource.url), v8::ReadOnly); - instance->ForceSet(NanNew("kind"), NanNew(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(int(resource.kind))); - return NanEscapeScope(instance); + return scope.Escape(instance); } NAN_METHOD(NodeRequest::Respond) { - auto nodeRequest = ObjectWrap::Unwrap(args.Holder()); + auto nodeRequest = Nan::ObjectWrap::Unwrap(info.Data().As()); // 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(); 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(); - 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(); } //////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/platform/node/src/node_request.hpp b/platform/node/src/node_request.hpp index a690904ef..35bb8e520 100644 --- a/platform/node/src/node_request.hpp +++ b/platform/node/src/node_request.hpp @@ -3,7 +3,6 @@ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wshadow" -#include #include #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 target); + static NAN_MODULE_INIT(Init); + static NAN_METHOD(New); static NAN_METHOD(Respond); static v8::Handle Create(NodeFileSource*, const mbgl::Resource&); + static Nan::Persistent constructor; - static v8::Persistent constructorTemplate; - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Instance -public: NodeRequest(NodeFileSource* source, const mbgl::Resource& resource); ~NodeRequest(); diff --git a/platform/node/test/js/map.test.js b/platform/node/test/js/map.test.js index b3934e4fd..1581d15cb 100644 --- a/platform/node/test/js/map.test.js +++ b/platform/node/test/js/map.test.js @@ -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(); diff --git a/platform/node/test/render.test.js b/platform/node/test/render.test.js index 2050677e9..c36600157 100644 --- a/platform/node/test/render.test.js +++ b/platform/node/test/render.test.js @@ -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}); }); } }); diff --git a/scripts/android/run.sh b/scripts/android/run.sh index 2ef0c40c9..73ffc4c5c 100755 --- a/scripts/android/run.sh +++ b/scripts/android/run.sh @@ -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 diff --git a/scripts/build-shaders.py b/scripts/build-shaders.py index c1d7f7f28..3f3b77671 100755 --- a/scripts/build-shaders.py +++ b/scripts/build-shaders.py @@ -34,11 +34,13 @@ def write_header(): #ifndef MBGL_SHADER_SHADERS #define MBGL_SHADER_SHADERS +#include + namespace mbgl { struct shader_source { - const char *vertex; - const char *fragment; + const GLchar *vertex; + const GLchar *fragment; }; enum { diff --git a/scripts/ios/publish.sh b/scripts/ios/publish.sh index 61270fb45..c914fcacc 100755 --- a/scripts/ios/publish.sh +++ b/scripts/ios/publish.sh @@ -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" diff --git a/scripts/ios/test.sh b/scripts/ios/test.sh index 170aa0f64..60ccc76a9 100755 --- a/scripts/ios/test.sh +++ b/scripts/ios/test.sh @@ -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 diff --git a/src/mbgl/geometry/buffer.hpp b/src/mbgl/geometry/buffer.hpp index c696b5b86..d54ee18c7 100644 --- a/src/mbgl/geometry/buffer.hpp +++ b/src/mbgl/geometry/buffer.hpp @@ -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(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; diff --git a/src/mbgl/geometry/elements_buffer.hpp b/src/mbgl/geometry/elements_buffer.hpp index 24753ebaf..5e642f06d 100644 --- a/src/mbgl/geometry/elements_buffer.hpp +++ b/src/mbgl/geometry/elements_buffer.hpp @@ -10,16 +10,16 @@ namespace mbgl { -template +template struct ElementGroup : public util::noncopyable { std::array 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_) + { } }; diff --git a/src/mbgl/geometry/glyph_atlas.cpp b/src/mbgl/geometry/glyph_atlas.cpp index 43ea58553..b90444e58 100644 --- a/src/mbgl/geometry/glyph_atlas.cpp +++ b/src/mbgl/geometry/glyph_atlas.cpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include #include @@ -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, diff --git a/src/mbgl/geometry/glyph_atlas.hpp b/src/mbgl/geometry/glyph_atlas.hpp index 8bc21da09..120530183 100644 --- a/src/mbgl/geometry/glyph_atlas.hpp +++ b/src/mbgl/geometry/glyph_atlas.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -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> index; const std::unique_ptr data; std::atomic dirty; - uint32_t texture = 0; + GLuint texture = 0; }; }; diff --git a/src/mbgl/geometry/line_atlas.cpp b/src/mbgl/geometry/line_atlas.cpp index aeac3067e..bbda2dce6 100644 --- a/src/mbgl/geometry/line_atlas.cpp +++ b/src/mbgl/geometry/line_atlas.cpp @@ -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(w * h)), + data(std::make_unique(w * h)), dirty(true) { } diff --git a/src/mbgl/geometry/line_atlas.hpp b/src/mbgl/geometry/line_atlas.hpp index 3c3b90f75..a8663cb82 100644 --- a/src/mbgl/geometry/line_atlas.hpp +++ b/src/mbgl/geometry/line_atlas.hpp @@ -1,6 +1,8 @@ #ifndef MBGL_GEOMETRY_LINE_ATLAS #define MBGL_GEOMETRY_LINE_ATLAS +#include + #include #include #include @@ -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&, bool); LinePatternPos addDash(const std::vector &dasharray, bool round); - const int width; - const int height; + const GLsizei width; + const GLsizei height; private: - const std::unique_ptr data; + const std::unique_ptr data; bool dirty; - uint32_t texture = 0; + GLuint texture = 0; int nextRow = 0; std::map positions; }; diff --git a/src/mbgl/geometry/line_buffer.cpp b/src/mbgl/geometry/line_buffer.cpp index f475c63b2..77a134b46 100644 --- a/src/mbgl/geometry/line_buffer.cpp +++ b/src/mbgl/geometry/line_buffer.cpp @@ -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(data); diff --git a/src/mbgl/geometry/line_buffer.hpp b/src/mbgl/geometry/line_buffer.hpp index 1c217b59d..7174fa291 100644 --- a/src/mbgl/geometry/line_buffer.hpp +++ b/src/mbgl/geometry/line_buffer.hpp @@ -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); }; diff --git a/src/mbgl/geometry/sprite_atlas.hpp b/src/mbgl/geometry/sprite_atlas.hpp index bfe4f843d..2e794f651 100644 --- a/src/mbgl/geometry/sprite_atlas.hpp +++ b/src/mbgl/geometry/sprite_atlas.hpp @@ -2,7 +2,7 @@ #define MBGL_GEOMETRY_SPRITE_ATLAS #include - +#include #include #include @@ -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 data; std::atomic dirty; bool fullUploadRequired = true; - uint32_t texture = 0; + GLuint texture = 0; uint32_t filter = 0; static const int buffer = 1; }; diff --git a/src/mbgl/geometry/vao.cpp b/src/mbgl/geometry/vao.cpp index ef4cb26db..1330a057f 100644 --- a/src/mbgl/geometry/vao.cpp +++ b/src/mbgl/geometry/vao.cpp @@ -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; diff --git a/src/mbgl/geometry/vao.hpp b/src/mbgl/geometry/vao.hpp index e512a3e48..bd845b1e3 100644 --- a/src/mbgl/geometry/vao.hpp +++ b/src/mbgl/geometry/vao.hpp @@ -18,7 +18,7 @@ public: ~VertexArrayObject(); template - 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 - 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; }; } diff --git a/src/mbgl/map/annotation.cpp b/src/mbgl/map/annotation.cpp index 874459797..9cfb857bc 100644 --- a/src/mbgl/map/annotation.cpp +++ b/src/mbgl/map/annotation.cpp @@ -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(type, segments, styleProperties)); - - std::unordered_set affectedTiles; + annotations.emplace(annotationID, std::make_unique(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 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()) { - 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 features; - - features.push_back(Convert::create(Tags(), featureType, rings)); - - shapeTilers.emplace(annotationID, std::make_unique(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 +AnnotationManager::addShapeFeature(const uint32_t annotationID, + const AnnotationSegments& segments, + const StyleProperties& styleProperties, + const uint8_t maxZoom) { + // Currently unused. + std::unordered_set 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 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 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()) { - featureType = FeatureType::LineString; - } else if (styleProperties.is()) { - featureType = FeatureType::Polygon; - } else { - throw std::runtime_error("Invalid feature type"); - } - - // create tile feature - auto feature = std::make_shared( - featureType, - featureTile.second, - featureProperties - ); - - // check for tile & create if necessary - auto tile_pos = tiles.emplace(featureTile.first, - std::make_pair(std::unordered_set({ annotationID }), - std::make_unique())); - - // check for annotation layer & create if necessary - util::ptr 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(); - 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(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()) { + 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 features; + features.push_back(Convert::create(Tags(), featureType, rings)); + + shapeTilers.emplace(annotationID, std::make_unique(features, maxZoom, 4, 100, 10)); + + return affectedTiles; +} + +std::unordered_set +AnnotationManager::addPointFeature(const uint32_t annotationID, + const std::vector>>& projectedFeature, + const std::unordered_map& featureProperties, + const uint8_t maxZoom) { + std::unordered_set 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(FeatureType::Point, geometries, featureProperties); + + // check for tile & create if necessary + auto tile_pos = tiles.emplace(featureTileID, + std::make_pair(std::unordered_set({ annotationID }), + std::make_unique())); + + // check for annotation layer & create if necessary + util::ptr layer; + std::string layerID = PointLayerID; + + if (tile_pos.second || tile_pos.first->second.second->getMutableLayer(layerID) == nullptr) { + layer = std::make_shared(); + 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(feature)); + + // track affected tile + affectedTiles.insert(featureTileID); } return affectedTiles; diff --git a/src/mbgl/map/annotation.hpp b/src/mbgl/map/annotation.hpp index 5adec162f..7691e4508 100644 --- a/src/mbgl/map/annotation.hpp +++ b/src/mbgl/map/annotation.hpp @@ -80,14 +80,27 @@ public: private: inline uint32_t nextID(); static vec2 projectPoint(const LatLng& point); - std::unordered_set addTileFeature( - const uint32_t annotationID, - const AnnotationSegments&, - const std::vector>>& projectedFeature, - const AnnotationType&, - const StyleProperties&, - const std::unordered_map& featureProperties, - const uint8_t maxZoom); + + std::unordered_set + addTileFeature(const uint32_t annotationID, + const AnnotationSegments&, + const std::vector>>& projectedFeature, + const AnnotationType&, + const StyleProperties&, + const std::unordered_map& featureProperties, + const uint8_t maxZoom); + + std::unordered_set + addShapeFeature(const uint32_t annotationID, + const AnnotationSegments& segments, + const StyleProperties& styleProperties, + const uint8_t maxZoom); + + std::unordered_set + addPointFeature(const uint32_t annotationID, + const std::vector>>& projectedFeature, + const std::unordered_map& featureProperties, + const uint8_t maxZoom); private: std::string defaultPointAnnotationSymbol; diff --git a/src/mbgl/renderer/bucket.hpp b/src/mbgl/renderer/bucket.hpp index eb02f32eb..a1dbdeeed 100644 --- a/src/mbgl/renderer/bucket.hpp +++ b/src/mbgl/renderer/bucket.hpp @@ -1,13 +1,15 @@ #ifndef MBGL_RENDERER_BUCKET #define MBGL_RENDERER_BUCKET +#include #include #include #include #include -#define BUFFER_OFFSET(i) ((char*)nullptr + (i)) +#define BUFFER_OFFSET_0 ((GLbyte*)nullptr) +#define BUFFER_OFFSET(i) ((BUFFER_OFFSET_0) + (i)) namespace mbgl { diff --git a/src/mbgl/renderer/circle_bucket.cpp b/src/mbgl/renderer/circle_bucket.cpp index fde04df29..ae8eeef9d 100644 --- a/src/mbgl/renderer/circle_bucket.cpp +++ b/src/mbgl/renderer/circle_bucket.cpp @@ -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); diff --git a/src/mbgl/renderer/circle_bucket.hpp b/src/mbgl/renderer/circle_bucket.hpp index 727b9fa37..d25cbdad3 100644 --- a/src/mbgl/renderer/circle_bucket.hpp +++ b/src/mbgl/renderer/circle_bucket.hpp @@ -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> triangleGroups_; }; diff --git a/src/mbgl/renderer/debug_bucket.cpp b/src/mbgl/renderer/debug_bucket.cpp index 1d9b9fb6d..161412f0d 100644 --- a/src/mbgl/renderer/debug_bucket.cpp +++ b/src/mbgl/renderer/debug_bucket.cpp @@ -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()))); } diff --git a/src/mbgl/renderer/fill_bucket.cpp b/src/mbgl/renderer/fill_bucket.cpp index 151e4c4a4..38263b3a4 100644 --- a/src/mbgl/renderer/fill_bucket.cpp +++ b/src/mbgl/renderer/fill_bucket.cpp @@ -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(polygon.size()); assert(group_count >= 3); std::vector 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(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); diff --git a/src/mbgl/renderer/fill_bucket.hpp b/src/mbgl/renderer/fill_bucket.hpp index 2ff86ba9a..1e0285254 100644 --- a/src/mbgl/renderer/fill_bucket.hpp +++ b/src/mbgl/renderer/fill_bucket.hpp @@ -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> triangleGroups; std::vector> lineGroups; diff --git a/src/mbgl/renderer/line_bucket.cpp b/src/mbgl/renderer/line_bucket.cpp index 24bda6d0a..9f4d060fc 100644 --- a/src/mbgl/renderer/line_bucket.cpp +++ b/src/mbgl/renderer/line_bucket.cpp @@ -32,8 +32,8 @@ void LineBucket::addGeometry(const GeometryCollection& geometryCollection) { } void LineBucket::addGeometry(const std::vector& vertices) { - const auto len = [&vertices] { - auto l = vertices.size(); + const GLsizei len = [&vertices] { + GLsizei l = static_cast(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& vertices) { nextNormal = util::perp(util::unit(vec2(firstVertex - currentVertex))); } - const int32_t startVertex = (int32_t)vertexBuffer.index(); + const GLint startVertex = vertexBuffer.index(); std::vector 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& 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& triangleStore) { int8_t tx = round ? 1 : 0; vec2 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& extrude, bool lineTurnsLeft, - int32_t startVertex, + GLint startVertex, std::vector& 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) { diff --git a/src/mbgl/renderer/line_bucket.hpp b/src/mbgl/renderer/line_bucket.hpp index cd5fce3cb..2be0cf392 100644 --- a/src/mbgl/renderer/line_bucket.hpp +++ b/src/mbgl/renderer/line_bucket.hpp @@ -46,9 +46,9 @@ private: }; void addCurrentVertex(const Coordinate& currentVertex, float flip, double distance, const vec2& normal, float endLeft, float endRight, bool round, - int32_t startVertex, std::vector& triangleStore); + GLint startVertex, std::vector& triangleStore); void addPieSliceVertex(const Coordinate& currentVertex, float flip, double distance, - const vec2& extrude, bool lineTurnsLeft, int32_t startVertex, + const vec2& extrude, bool lineTurnsLeft, GLint startVertex, std::vector& 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> triangleGroups; }; diff --git a/src/mbgl/renderer/painter.cpp b/src/mbgl/renderer/painter.cpp index e757d682a..abb08f28b 100644 --- a/src/mbgl/renderer/painter.cpp +++ b/src/mbgl/renderer/painter.cpp @@ -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(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 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"); diff --git a/src/mbgl/renderer/painter.hpp b/src/mbgl/renderer/painter.hpp index 9c0f5db8c..07bd4c4d3 100644 --- a/src/mbgl/renderer/painter.hpp +++ b/src/mbgl/renderer/painter.hpp @@ -143,7 +143,7 @@ private: template 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 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); diff --git a/src/mbgl/renderer/painter_clipping.cpp b/src/mbgl/renderer/painter_clipping.cpp index 332d2876f..59e40fefe 100644 --- a/src/mbgl/renderer/painter_clipping.cpp +++ b/src/mbgl/renderer/painter_clipping.cpp @@ -16,7 +16,7 @@ void Painter::drawClippingMasks(const std::set& 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); diff --git a/src/mbgl/renderer/painter_debug.cpp b/src/mbgl/renderer/painter_debug.cpp index f4f3a19cb..bc4055324 100644 --- a/src/mbgl/renderer/painter_debug.cpp +++ b/src/mbgl/renderer/painter_debug.cpp @@ -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())); diff --git a/src/mbgl/renderer/raster_bucket.cpp b/src/mbgl/renderer/raster_bucket.cpp index 70cc1065d..cf72f860a 100644 --- a/src/mbgl/renderer/raster_bucket.cpp +++ b/src/mbgl/renderer/raster_bucket.cpp @@ -30,7 +30,7 @@ bool RasterBucket::setImage(std::unique_ptr 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())); } diff --git a/src/mbgl/renderer/symbol_bucket.cpp b/src/mbgl/renderer/symbol_bucket.cpp index 7665fd9a6..dabffa14f 100644 --- a/src/mbgl/renderer/symbol_bucket.cpp +++ b/src/mbgl/renderer/symbol_bucket.cpp @@ -103,7 +103,8 @@ bool SymbolBucket::needsDependencies(const GeometryTileLayer& layer, // Determine and load glyph ranges std::set ranges; - for (std::size_t i = 0; i < layer.featureCount(); i++) { + const GLsizei featureCount = static_cast(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); diff --git a/src/mbgl/shader/box_shader.cpp b/src/mbgl/shader/box_shader.cpp index 2676223a9..beb5e15f9 100644 --- a/src/mbgl/shader/box_shader.cpp +++ b/src/mbgl/shader/box_shader.cpp @@ -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)); diff --git a/src/mbgl/shader/box_shader.hpp b/src/mbgl/shader/box_shader.hpp index 5c84d8906..19df2ca82 100644 --- a/src/mbgl/shader/box_shader.hpp +++ b/src/mbgl/shader/box_shader.hpp @@ -3,6 +3,7 @@ #include #include +#include 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 u_scale = {"u_scale", *this}; - Uniform u_zoom = {"u_zoom", *this}; - Uniform u_maxzoom = {"u_maxzoom", *this}; + Uniform u_scale = {"u_scale", *this}; + Uniform u_zoom = {"u_zoom", *this}; + Uniform 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 diff --git a/src/mbgl/shader/circle_shader.cpp b/src/mbgl/shader/circle_shader.cpp index 074f92d68..8fa10191b 100644 --- a/src/mbgl/shader/circle_shader.cpp +++ b/src/mbgl/shader/circle_shader.cpp @@ -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)); } diff --git a/src/mbgl/shader/circle_shader.hpp b/src/mbgl/shader/circle_shader.hpp index 545a0baad..84f4ef99a 100644 --- a/src/mbgl/shader/circle_shader.hpp +++ b/src/mbgl/shader/circle_shader.hpp @@ -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> u_color = {"u_color", *this}; - Uniform u_size = {"u_size", *this}; - Uniform 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> u_color = {"u_color", *this}; + Uniform u_size = {"u_size", *this}; + Uniform u_blur = {"u_blur", *this}; }; } diff --git a/src/mbgl/shader/dot_shader.cpp b/src/mbgl/shader/dot_shader.cpp index 57a60cc51..baec3678b 100644 --- a/src/mbgl/shader/dot_shader.cpp +++ b/src/mbgl/shader/dot_shader.cpp @@ -12,10 +12,9 @@ DotShader::DotShader() shaders[DOT_SHADER].vertex, shaders[DOT_SHADER].fragment ) { - a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); } -void DotShader::bind(char *offset) { +void DotShader::bind(GLbyte *offset) { MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos)); MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, 8, offset)); } diff --git a/src/mbgl/shader/dot_shader.hpp b/src/mbgl/shader/dot_shader.hpp index 2c4176f36..fe1541cf7 100644 --- a/src/mbgl/shader/dot_shader.hpp +++ b/src/mbgl/shader/dot_shader.hpp @@ -10,15 +10,12 @@ class DotShader : public Shader { public: DotShader(); - void bind(char *offset); + void bind(GLbyte *offset) final; - UniformMatrix<4> u_matrix = {"u_matrix", *this}; - Uniform> u_color = {"u_color", *this}; - Uniform u_size = {"u_size", *this}; - Uniform u_blur = {"u_blur", *this}; - -private: - int32_t a_pos = -1; + UniformMatrix<4> u_matrix = {"u_matrix", *this}; + Uniform> u_color = {"u_color", *this}; + Uniform u_size = {"u_size", *this}; + Uniform u_blur = {"u_blur", *this}; }; } diff --git a/src/mbgl/shader/icon_shader.cpp b/src/mbgl/shader/icon_shader.cpp index 0f626ec9e..a9b4be23e 100644 --- a/src/mbgl/shader/icon_shader.cpp +++ b/src/mbgl/shader/icon_shader.cpp @@ -12,14 +12,13 @@ IconShader::IconShader() shaders[ICON_SHADER].vertex, shaders[ICON_SHADER].fragment ) { - a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); a_offset = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_offset")); a_data1 = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_data1")); a_data2 = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_data2")); } -void IconShader::bind(char *offset) { - const int stride = 16; +void IconShader::bind(GLbyte *offset) { + const GLsizei stride = 16; MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos)); MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, stride, offset + 0)); diff --git a/src/mbgl/shader/icon_shader.hpp b/src/mbgl/shader/icon_shader.hpp index 18b0fce37..437fd859b 100644 --- a/src/mbgl/shader/icon_shader.hpp +++ b/src/mbgl/shader/icon_shader.hpp @@ -10,25 +10,24 @@ class IconShader : public Shader { public: IconShader(); - void bind(char *offset); + void bind(GLbyte *offset) final; - UniformMatrix<4> u_matrix = {"u_matrix", *this}; - UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this}; - Uniform u_zoom = {"u_zoom", *this}; - Uniform u_fadedist = {"u_fadedist", *this}; - Uniform u_minfadezoom = {"u_minfadezoom", *this}; - Uniform u_maxfadezoom = {"u_maxfadezoom", *this}; - Uniform u_fadezoom = {"u_fadezoom", *this}; - Uniform u_opacity = {"u_opacity", *this}; - Uniform> u_texsize = {"u_texsize", *this}; - Uniform u_skewed = {"u_skewed", *this}; - Uniform u_extra = {"u_extra", *this}; + UniformMatrix<4> u_matrix = {"u_matrix", *this}; + UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this}; + Uniform u_zoom = {"u_zoom", *this}; + Uniform u_fadedist = {"u_fadedist", *this}; + Uniform u_minfadezoom = {"u_minfadezoom", *this}; + Uniform u_maxfadezoom = {"u_maxfadezoom", *this}; + Uniform u_fadezoom = {"u_fadezoom", *this}; + Uniform u_opacity = {"u_opacity", *this}; + Uniform> u_texsize = {"u_texsize", *this}; + Uniform u_skewed = {"u_skewed", *this}; + Uniform u_extra = {"u_extra", *this}; -private: - int32_t a_pos = -1; - int32_t a_offset = -1; - int32_t a_data1 = -1; - int32_t a_data2 = -1; +protected: + GLint a_offset = -1; + GLint a_data1 = -1; + GLint a_data2 = -1; }; } diff --git a/src/mbgl/shader/line_shader.cpp b/src/mbgl/shader/line_shader.cpp index c2364c9be..1e2306939 100644 --- a/src/mbgl/shader/line_shader.cpp +++ b/src/mbgl/shader/line_shader.cpp @@ -12,11 +12,10 @@ LineShader::LineShader() shaders[LINE_SHADER].vertex, shaders[LINE_SHADER].fragment ) { - a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); a_data = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_data")); } -void LineShader::bind(char *offset) { +void LineShader::bind(GLbyte *offset) { MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos)); MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, 8, offset + 0)); diff --git a/src/mbgl/shader/line_shader.hpp b/src/mbgl/shader/line_shader.hpp index 0572cac88..580035a07 100644 --- a/src/mbgl/shader/line_shader.hpp +++ b/src/mbgl/shader/line_shader.hpp @@ -10,20 +10,19 @@ class LineShader : public Shader { public: LineShader(); - void bind(char *offset); + void bind(GLbyte *offset) final; - UniformMatrix<4> u_matrix = {"u_matrix", *this}; - UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this}; - Uniform> u_color = {"u_color", *this}; - Uniform> u_linewidth = {"u_linewidth", *this}; - Uniform u_ratio = {"u_ratio", *this}; - Uniform u_blur = {"u_blur", *this}; - Uniform u_extra = {"u_extra", *this}; - UniformMatrix<2> u_antialiasingmatrix = {"u_antialiasingmatrix", *this}; + UniformMatrix<4> u_matrix = {"u_matrix", *this}; + UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this}; + Uniform> u_color = {"u_color", *this}; + Uniform> u_linewidth = {"u_linewidth", *this}; + Uniform u_ratio = {"u_ratio", *this}; + Uniform u_blur = {"u_blur", *this}; + Uniform u_extra = {"u_extra", *this}; + UniformMatrix<2> u_antialiasingmatrix = {"u_antialiasingmatrix", *this}; private: - int32_t a_pos = -1; - int32_t a_data = -1; + GLint a_data = -1; }; diff --git a/src/mbgl/shader/linepattern_shader.cpp b/src/mbgl/shader/linepattern_shader.cpp index 7bfd1412d..4d416d506 100644 --- a/src/mbgl/shader/linepattern_shader.cpp +++ b/src/mbgl/shader/linepattern_shader.cpp @@ -12,11 +12,10 @@ LinepatternShader::LinepatternShader() shaders[LINEPATTERN_SHADER].vertex, shaders[LINEPATTERN_SHADER].fragment ) { - a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); a_data = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_data")); } -void LinepatternShader::bind(char *offset) { +void LinepatternShader::bind(GLbyte *offset) { MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos)); MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, 8, offset + 0)); diff --git a/src/mbgl/shader/linepattern_shader.hpp b/src/mbgl/shader/linepattern_shader.hpp index dce065a0d..f2189d471 100644 --- a/src/mbgl/shader/linepattern_shader.hpp +++ b/src/mbgl/shader/linepattern_shader.hpp @@ -10,28 +10,27 @@ class LinepatternShader : public Shader { public: LinepatternShader(); - void bind(char *offset); + void bind(GLbyte *offset) final; - UniformMatrix<4> u_matrix = {"u_matrix", *this}; - UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this}; - Uniform> u_linewidth = {"u_linewidth", *this}; - Uniform> u_pattern_size_a = {"u_pattern_size_a", *this}; - Uniform> u_pattern_tl_a = {"u_pattern_tl_a", *this}; - Uniform> u_pattern_br_a = {"u_pattern_br_a", *this}; - Uniform> u_pattern_size_b = {"u_pattern_size_b", *this}; - Uniform> u_pattern_tl_b = {"u_pattern_tl_b", *this}; - Uniform> u_pattern_br_b = {"u_pattern_br_b", *this}; - Uniform u_ratio = {"u_ratio", *this}; - Uniform u_point = {"u_point", *this}; - Uniform u_blur = {"u_blur", *this}; - Uniform u_fade = {"u_fade", *this}; - Uniform u_opacity = {"u_opacity", *this}; - Uniform u_extra = {"u_extra", *this}; - UniformMatrix<2> u_antialiasingmatrix = {"u_antialiasingmatrix", *this}; + UniformMatrix<4> u_matrix = {"u_matrix", *this}; + UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this}; + Uniform> u_linewidth = {"u_linewidth", *this}; + Uniform> u_pattern_size_a = {"u_pattern_size_a", *this}; + Uniform> u_pattern_tl_a = {"u_pattern_tl_a", *this}; + Uniform> u_pattern_br_a = {"u_pattern_br_a", *this}; + Uniform> u_pattern_size_b = {"u_pattern_size_b", *this}; + Uniform> u_pattern_tl_b = {"u_pattern_tl_b", *this}; + Uniform> u_pattern_br_b = {"u_pattern_br_b", *this}; + Uniform u_ratio = {"u_ratio", *this}; + Uniform u_point = {"u_point", *this}; + Uniform u_blur = {"u_blur", *this}; + Uniform u_fade = {"u_fade", *this}; + Uniform u_opacity = {"u_opacity", *this}; + Uniform u_extra = {"u_extra", *this}; + UniformMatrix<2> u_antialiasingmatrix = {"u_antialiasingmatrix", *this}; private: - int32_t a_pos = -1; - int32_t a_data = -1; + GLint a_data = -1; }; } diff --git a/src/mbgl/shader/linesdf_shader.cpp b/src/mbgl/shader/linesdf_shader.cpp index bd2137de3..1a56bb106 100644 --- a/src/mbgl/shader/linesdf_shader.cpp +++ b/src/mbgl/shader/linesdf_shader.cpp @@ -12,11 +12,10 @@ LineSDFShader::LineSDFShader() shaders[LINESDF_SHADER].vertex, shaders[LINESDF_SHADER].fragment ) { - a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); a_data = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_data")); } -void LineSDFShader::bind(char *offset) { +void LineSDFShader::bind(GLbyte *offset) { MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos)); MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, 8, offset + 0)); diff --git a/src/mbgl/shader/linesdf_shader.hpp b/src/mbgl/shader/linesdf_shader.hpp index 9928d5b30..839494f79 100644 --- a/src/mbgl/shader/linesdf_shader.hpp +++ b/src/mbgl/shader/linesdf_shader.hpp @@ -10,27 +10,26 @@ class LineSDFShader : public Shader { public: LineSDFShader(); - void bind(char *offset); + void bind(GLbyte *offset) final; - UniformMatrix<4> u_matrix = {"u_matrix", *this}; - UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this}; - Uniform> u_color = {"u_color", *this}; - Uniform> u_linewidth = {"u_linewidth", *this}; - Uniform u_ratio = {"u_ratio", *this}; - Uniform u_blur = {"u_blur", *this}; - Uniform> u_patternscale_a = { "u_patternscale_a", *this }; - Uniform u_tex_y_a = {"u_tex_y_a", *this}; - Uniform> u_patternscale_b = { "u_patternscale_b", *this }; - Uniform u_tex_y_b = {"u_tex_y_b", *this}; - Uniform u_image = {"u_image", *this}; - Uniform u_sdfgamma = {"u_sdfgamma", *this}; - Uniform u_mix = {"u_mix", *this}; - Uniform u_extra = {"u_extra", *this}; - UniformMatrix<2> u_antialiasingmatrix = {"u_antialiasingmatrix", *this}; + UniformMatrix<4> u_matrix = {"u_matrix", *this}; + UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this}; + Uniform> u_color = {"u_color", *this}; + Uniform> u_linewidth = {"u_linewidth", *this}; + Uniform u_ratio = {"u_ratio", *this}; + Uniform u_blur = {"u_blur", *this}; + Uniform> u_patternscale_a = { "u_patternscale_a", *this}; + Uniform u_tex_y_a = {"u_tex_y_a", *this}; + Uniform> u_patternscale_b = { "u_patternscale_b", *this}; + Uniform u_tex_y_b = {"u_tex_y_b", *this}; + Uniform u_image = {"u_image", *this}; + Uniform u_sdfgamma = {"u_sdfgamma", *this}; + Uniform u_mix = {"u_mix", *this}; + Uniform u_extra = {"u_extra", *this}; + UniformMatrix<2> u_antialiasingmatrix = {"u_antialiasingmatrix", *this}; private: - int32_t a_pos = -1; - int32_t a_data = -1; + GLint a_data = -1; }; diff --git a/src/mbgl/shader/outline_shader.cpp b/src/mbgl/shader/outline_shader.cpp index ee2a6bcd4..74453468b 100644 --- a/src/mbgl/shader/outline_shader.cpp +++ b/src/mbgl/shader/outline_shader.cpp @@ -12,10 +12,9 @@ OutlineShader::OutlineShader() shaders[OUTLINE_SHADER].vertex, shaders[OUTLINE_SHADER].fragment ) { - a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); } -void OutlineShader::bind(char *offset) { +void OutlineShader::bind(GLbyte *offset) { MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos)); MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, 0, offset)); } diff --git a/src/mbgl/shader/outline_shader.hpp b/src/mbgl/shader/outline_shader.hpp index f3e8175fd..2cd4b1dc3 100644 --- a/src/mbgl/shader/outline_shader.hpp +++ b/src/mbgl/shader/outline_shader.hpp @@ -10,14 +10,11 @@ class OutlineShader : public Shader { public: OutlineShader(); - void bind(char *offset); + void bind(GLbyte *offset) final; - UniformMatrix<4> u_matrix = {"u_matrix", *this}; - Uniform> u_color = {"u_color", *this}; - Uniform> u_world = {"u_world", *this}; - -private: - int32_t a_pos = -1; + UniformMatrix<4> u_matrix = {"u_matrix", *this}; + Uniform> u_color = {"u_color", *this}; + Uniform> u_world = {"u_world", *this}; }; } diff --git a/src/mbgl/shader/pattern_shader.cpp b/src/mbgl/shader/pattern_shader.cpp index 66369d528..d6ddab8e2 100644 --- a/src/mbgl/shader/pattern_shader.cpp +++ b/src/mbgl/shader/pattern_shader.cpp @@ -12,10 +12,9 @@ PatternShader::PatternShader() shaders[PATTERN_SHADER].vertex, shaders[PATTERN_SHADER].fragment ) { - a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); } -void PatternShader::bind(char *offset) { +void PatternShader::bind(GLbyte *offset) { MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos)); MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, 0, offset)); } diff --git a/src/mbgl/shader/pattern_shader.hpp b/src/mbgl/shader/pattern_shader.hpp index 9fc8dcfa0..3dd3daa46 100644 --- a/src/mbgl/shader/pattern_shader.hpp +++ b/src/mbgl/shader/pattern_shader.hpp @@ -10,21 +10,18 @@ class PatternShader : public Shader { public: PatternShader(); - void bind(char *offset); + void bind(GLbyte *offset) final; - UniformMatrix<4> u_matrix = {"u_matrix", *this}; - Uniform> u_pattern_tl_a = {"u_pattern_tl_a", *this}; - Uniform> u_pattern_br_a = {"u_pattern_br_a", *this}; - Uniform> u_pattern_tl_b = {"u_pattern_tl_b", *this}; - Uniform> u_pattern_br_b = {"u_pattern_br_b", *this}; - Uniform u_opacity = {"u_opacity", *this}; - Uniform u_mix = {"u_mix", *this}; - Uniform u_image = {"u_image", *this}; - UniformMatrix<3> u_patternmatrix_a = {"u_patternmatrix_a", *this}; - UniformMatrix<3> u_patternmatrix_b = {"u_patternmatrix_b", *this}; - -private: - int32_t a_pos = -1; + UniformMatrix<4> u_matrix = {"u_matrix", *this}; + Uniform> u_pattern_tl_a = {"u_pattern_tl_a", *this}; + Uniform> u_pattern_br_a = {"u_pattern_br_a", *this}; + Uniform> u_pattern_tl_b = {"u_pattern_tl_b", *this}; + Uniform> u_pattern_br_b = {"u_pattern_br_b", *this}; + Uniform u_opacity = {"u_opacity", *this}; + Uniform u_mix = {"u_mix", *this}; + Uniform u_image = {"u_image", *this}; + UniformMatrix<3> u_patternmatrix_a = {"u_patternmatrix_a", *this}; + UniformMatrix<3> u_patternmatrix_b = {"u_patternmatrix_b", *this}; }; } diff --git a/src/mbgl/shader/plain_shader.cpp b/src/mbgl/shader/plain_shader.cpp index 93dbb42a5..52fef07c0 100644 --- a/src/mbgl/shader/plain_shader.cpp +++ b/src/mbgl/shader/plain_shader.cpp @@ -12,10 +12,9 @@ PlainShader::PlainShader() shaders[PLAIN_SHADER].vertex, shaders[PLAIN_SHADER].fragment ) { - a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); } -void PlainShader::bind(char *offset) { +void PlainShader::bind(GLbyte *offset) { MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos)); MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, 0, offset)); } diff --git a/src/mbgl/shader/plain_shader.hpp b/src/mbgl/shader/plain_shader.hpp index 051501c3c..ee0528e9e 100644 --- a/src/mbgl/shader/plain_shader.hpp +++ b/src/mbgl/shader/plain_shader.hpp @@ -10,13 +10,10 @@ class PlainShader : public Shader { public: PlainShader(); - void bind(char *offset); + void bind(GLbyte *offset) final; - UniformMatrix<4> u_matrix = {"u_matrix", *this}; - Uniform> u_color = {"u_color", *this}; - -private: - int32_t a_pos = -1; + UniformMatrix<4> u_matrix = {"u_matrix", *this}; + Uniform> u_color = {"u_color", *this}; }; } diff --git a/src/mbgl/shader/raster_shader.cpp b/src/mbgl/shader/raster_shader.cpp index 2d6954920..b8496230b 100644 --- a/src/mbgl/shader/raster_shader.cpp +++ b/src/mbgl/shader/raster_shader.cpp @@ -12,10 +12,9 @@ RasterShader::RasterShader() shaders[RASTER_SHADER].vertex, shaders[RASTER_SHADER].fragment ) { - a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); } -void RasterShader::bind(char *offset) { +void RasterShader::bind(GLbyte *offset) { MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos)); MBGL_CHECK_ERROR(glVertexAttribPointer(a_pos, 2, GL_SHORT, false, 0, offset)); } diff --git a/src/mbgl/shader/raster_shader.hpp b/src/mbgl/shader/raster_shader.hpp index 8cf97055a..af51b4ba4 100644 --- a/src/mbgl/shader/raster_shader.hpp +++ b/src/mbgl/shader/raster_shader.hpp @@ -10,20 +10,17 @@ class RasterShader : public Shader { public: RasterShader(); - void bind(char *offset); + void bind(GLbyte *offset) final; - UniformMatrix<4> u_matrix = {"u_matrix", *this}; - Uniform u_image = {"u_image", *this}; - Uniform u_opacity = {"u_opacity", *this}; - Uniform u_buffer = {"u_buffer", *this}; - Uniform u_brightness_low = {"u_brightness_low", *this}; - Uniform u_brightness_high = {"u_brightness_high", *this}; - Uniform u_saturation_factor = {"u_saturation_factor", *this}; - Uniform u_contrast_factor = {"u_contrast_factor", *this}; - Uniform> u_spin_weights = {"u_spin_weights", *this}; - -private: - int32_t a_pos = -1; + UniformMatrix<4> u_matrix = {"u_matrix", *this}; + Uniform u_image = {"u_image", *this}; + Uniform u_opacity = {"u_opacity", *this}; + Uniform u_buffer = {"u_buffer", *this}; + Uniform u_brightness_low = {"u_brightness_low", *this}; + Uniform u_brightness_high = {"u_brightness_high", *this}; + Uniform u_saturation_factor = {"u_saturation_factor", *this}; + Uniform u_contrast_factor = {"u_contrast_factor", *this}; + Uniform> u_spin_weights = {"u_spin_weights", *this}; }; } diff --git a/src/mbgl/shader/sdf_shader.cpp b/src/mbgl/shader/sdf_shader.cpp index ca1dab58d..144ba6c47 100644 --- a/src/mbgl/shader/sdf_shader.cpp +++ b/src/mbgl/shader/sdf_shader.cpp @@ -12,13 +12,12 @@ SDFShader::SDFShader() shaders[SDF_SHADER].vertex, shaders[SDF_SHADER].fragment ) { - a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); a_offset = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_offset")); a_data1 = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_data1")); a_data2 = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_data2")); } -void SDFGlyphShader::bind(char *offset) { +void SDFGlyphShader::bind(GLbyte *offset) { const int stride = 16; MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos)); @@ -34,7 +33,7 @@ void SDFGlyphShader::bind(char *offset) { MBGL_CHECK_ERROR(glVertexAttribPointer(a_data2, 4, GL_UNSIGNED_BYTE, false, stride, offset + 12)); } -void SDFIconShader::bind(char *offset) { +void SDFIconShader::bind(GLbyte *offset) { const int stride = 16; MBGL_CHECK_ERROR(glEnableVertexAttribArray(a_pos)); diff --git a/src/mbgl/shader/sdf_shader.hpp b/src/mbgl/shader/sdf_shader.hpp index 181788ab1..fcb2e15d1 100644 --- a/src/mbgl/shader/sdf_shader.hpp +++ b/src/mbgl/shader/sdf_shader.hpp @@ -10,37 +10,34 @@ class SDFShader : public Shader { public: SDFShader(); - virtual void bind(char *offset) = 0; - - UniformMatrix<4> u_matrix = {"u_matrix", *this}; - UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this}; - Uniform> u_color = {"u_color", *this}; - Uniform> u_texsize = {"u_texsize", *this}; - Uniform u_buffer = {"u_buffer", *this}; - Uniform u_gamma = {"u_gamma", *this}; - Uniform u_zoom = {"u_zoom", *this}; - Uniform u_fadedist = {"u_fadedist", *this}; - Uniform u_minfadezoom = {"u_minfadezoom", *this}; - Uniform u_maxfadezoom = {"u_maxfadezoom", *this}; - Uniform u_fadezoom = {"u_fadezoom", *this}; - Uniform u_skewed = {"u_skewed", *this}; - Uniform u_extra = {"u_extra", *this}; + UniformMatrix<4> u_matrix = {"u_matrix", *this}; + UniformMatrix<4> u_exmatrix = {"u_exmatrix", *this}; + Uniform> u_color = {"u_color", *this}; + Uniform> u_texsize = {"u_texsize", *this}; + Uniform u_buffer = {"u_buffer", *this}; + Uniform u_gamma = {"u_gamma", *this}; + Uniform u_zoom = {"u_zoom", *this}; + Uniform u_fadedist = {"u_fadedist", *this}; + Uniform u_minfadezoom = {"u_minfadezoom", *this}; + Uniform u_maxfadezoom = {"u_maxfadezoom", *this}; + Uniform u_fadezoom = {"u_fadezoom", *this}; + Uniform u_skewed = {"u_skewed", *this}; + Uniform u_extra = {"u_extra", *this}; protected: - int32_t a_pos = -1; - int32_t a_offset = -1; - int32_t a_data1 = -1; - int32_t a_data2 = -1; + GLint a_offset = -1; + GLint a_data1 = -1; + GLint a_data2 = -1; }; class SDFGlyphShader : public SDFShader { public: - void bind(char *offset); + void bind(GLbyte *offset) final; }; class SDFIconShader : public SDFShader { public: - void bind(char *offset); + void bind(GLbyte *offset) final; }; } diff --git a/src/mbgl/shader/shader.cpp b/src/mbgl/shader/shader.cpp index 6210c1c32..e8deefc8f 100644 --- a/src/mbgl/shader/shader.cpp +++ b/src/mbgl/shader/shader.cpp @@ -14,22 +14,21 @@ using namespace mbgl; Shader::Shader(const char *name_, const GLchar *vertSource, const GLchar *fragSource) - : name(name_), - program(0) { + : name(name_) + , program(0) +{ util::stopwatch stopwatch("shader compilation", Event::Shader); program = MBGL_CHECK_ERROR(glCreateProgram()); - GLuint vertShader = 0; - GLuint fragShader = 0; - if (!compileShader(&vertShader, GL_VERTEX_SHADER, vertSource)) { + if (!compileShader(&vertShader, GL_VERTEX_SHADER, &vertSource)) { Log::Error(Event::Shader, "Vertex shader %s failed to compile: %s", name, vertSource); MBGL_CHECK_ERROR(glDeleteProgram(program)); program = 0; throw util::ShaderException(std::string { "Vertex shader " } + name + " failed to compile"); } - if (!compileShader(&fragShader, GL_FRAGMENT_SHADER, fragSource)) { + if (!compileShader(&fragShader, GL_FRAGMENT_SHADER, &fragSource)) { Log::Error(Event::Shader, "Fragment shader %s failed to compile: %s", name, fragSource); MBGL_CHECK_ERROR(glDeleteShader(vertShader)); vertShader = 0; @@ -67,46 +66,16 @@ Shader::Shader(const char *name_, const GLchar *vertSource, const GLchar *fragSo } } - { - // Validate program - GLint status; - MBGL_CHECK_ERROR(glValidateProgram(program)); - - MBGL_CHECK_ERROR(glGetProgramiv(program, GL_VALIDATE_STATUS, &status)); - if (status == 0) { - GLint logLength; - MBGL_CHECK_ERROR(glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength)); - const auto log = std::make_unique(logLength); - if (logLength > 0) { - MBGL_CHECK_ERROR(glGetProgramInfoLog(program, logLength, &logLength, log.get())); - Log::Error(Event::Shader, "Program failed to validate: %s", log.get()); - } - - MBGL_CHECK_ERROR(glDeleteShader(vertShader)); - vertShader = 0; - MBGL_CHECK_ERROR(glDeleteShader(fragShader)); - fragShader = 0; - MBGL_CHECK_ERROR(glDeleteProgram(program)); - program = 0; - throw util::ShaderException(std::string { "Program " } + name + " failed to link: " + log.get()); - } - } - - // Remove the compiled shaders; they are now part of the program. - MBGL_CHECK_ERROR(glDetachShader(program, vertShader)); - MBGL_CHECK_ERROR(glDeleteShader(vertShader)); - MBGL_CHECK_ERROR(glDetachShader(program, fragShader)); - MBGL_CHECK_ERROR(glDeleteShader(fragShader)); + a_pos = MBGL_CHECK_ERROR(glGetAttribLocation(program, "a_pos")); } -bool Shader::compileShader(GLuint *shader, GLenum type, const GLchar *source) { +bool Shader::compileShader(GLuint *shader, GLenum type, const GLchar *source[]) { GLint status; *shader = MBGL_CHECK_ERROR(glCreateShader(type)); - const GLchar *strings[] = { source }; - const GLsizei lengths[] = { static_cast(std::strlen(source)) }; - MBGL_CHECK_ERROR(glShaderSource(*shader, 1, strings, lengths)); + const GLsizei lengths = static_cast(std::strlen(*source)); + MBGL_CHECK_ERROR(glShaderSource(*shader, 1, source, &lengths)); MBGL_CHECK_ERROR(glCompileShader(*shader)); @@ -138,7 +107,13 @@ bool Shader::compileShader(GLuint *shader, GLenum type, const GLchar *source) { Shader::~Shader() { if (program) { + MBGL_CHECK_ERROR(glDetachShader(program, vertShader)); + MBGL_CHECK_ERROR(glDetachShader(program, fragShader)); MBGL_CHECK_ERROR(glDeleteProgram(program)); program = 0; + MBGL_CHECK_ERROR(glDeleteShader(vertShader)); + vertShader = 0; + MBGL_CHECK_ERROR(glDeleteShader(fragShader)); + fragShader = 0; } } diff --git a/src/mbgl/shader/shader.hpp b/src/mbgl/shader/shader.hpp index b3d9b4e46..1de56da87 100644 --- a/src/mbgl/shader/shader.hpp +++ b/src/mbgl/shader/shader.hpp @@ -1,26 +1,37 @@ #ifndef MBGL_RENDERER_SHADER #define MBGL_RENDERER_SHADER +#include +#include + #include #include #include -#include namespace mbgl { class Shader : private util::noncopyable { public: - Shader(const char *name, const char *vertex, const char *fragment); - ~Shader(); - const char *name; - uint32_t program; + Shader(const GLchar *name, const GLchar *vertex, const GLchar *fragment); - inline uint32_t getID() const { + ~Shader(); + const GLchar *name; + GLuint program; + + inline GLuint getID() const { return program; } + virtual void bind(GLbyte *offset) = 0; + +protected: + GLint a_pos = -1; + private: - bool compileShader(uint32_t *shader, uint32_t type, const char *source); + bool compileShader(GLuint *shader, GLenum type, const GLchar *source[]); + + GLuint vertShader = 0; + GLuint fragShader = 0; }; } diff --git a/src/mbgl/shader/uniform.cpp b/src/mbgl/shader/uniform.cpp index c013699bf..eca1a99d1 100644 --- a/src/mbgl/shader/uniform.cpp +++ b/src/mbgl/shader/uniform.cpp @@ -3,42 +3,42 @@ namespace mbgl { template <> -void Uniform::bind(const float& t) { +void Uniform::bind(const GLfloat& t) { MBGL_CHECK_ERROR(glUniform1f(location, t)); } template <> -void Uniform::bind(const int32_t& t) { +void Uniform::bind(const GLint& t) { MBGL_CHECK_ERROR(glUniform1i(location, t)); } template <> -void Uniform>::bind(const std::array& t) { +void Uniform>::bind(const std::array& t) { MBGL_CHECK_ERROR(glUniform2fv(location, 1, t.data())); } template <> -void Uniform>::bind(const std::array& t) { +void Uniform>::bind(const std::array& t) { MBGL_CHECK_ERROR(glUniform3fv(location, 1, t.data())); } template <> -void Uniform>::bind(const std::array& t) { +void Uniform>::bind(const std::array& t) { MBGL_CHECK_ERROR(glUniform4fv(location, 1, t.data())); } template <> -void UniformMatrix<2>::bind(const std::array& t) { +void UniformMatrix<2>::bind(const std::array& t) { MBGL_CHECK_ERROR(glUniformMatrix2fv(location, 1, GL_FALSE, t.data())); } template <> -void UniformMatrix<3>::bind(const std::array& t) { +void UniformMatrix<3>::bind(const std::array& t) { MBGL_CHECK_ERROR(glUniformMatrix3fv(location, 1, GL_FALSE, t.data())); } template <> -void UniformMatrix<4>::bind(const std::array& t) { +void UniformMatrix<4>::bind(const std::array& t) { MBGL_CHECK_ERROR(glUniformMatrix4fv(location, 1, GL_FALSE, t.data())); } diff --git a/src/mbgl/util/gl_object_store.cpp b/src/mbgl/util/gl_object_store.cpp index 269004f89..28a36e663 100644 --- a/src/mbgl/util/gl_object_store.cpp +++ b/src/mbgl/util/gl_object_store.cpp @@ -7,17 +7,17 @@ namespace mbgl { namespace util { -void GLObjectStore::abandonVAO(uint32_t vao) { +void GLObjectStore::abandonVAO(GLuint vao) { assert(ThreadContext::currentlyOn(ThreadType::Map)); abandonedVAOs.emplace_back(vao); } -void GLObjectStore::abandonBuffer(uint32_t buffer) { +void GLObjectStore::abandonBuffer(GLuint buffer) { assert(ThreadContext::currentlyOn(ThreadType::Map)); abandonedBuffers.emplace_back(buffer); } -void GLObjectStore::abandonTexture(uint32_t texture) { +void GLObjectStore::abandonTexture(GLuint texture) { assert(ThreadContext::currentlyOn(ThreadType::Map)); abandonedTextures.emplace_back(texture); } diff --git a/src/mbgl/util/gl_object_store.hpp b/src/mbgl/util/gl_object_store.hpp index 925ac1c05..d2929b518 100644 --- a/src/mbgl/util/gl_object_store.hpp +++ b/src/mbgl/util/gl_object_store.hpp @@ -1,6 +1,7 @@ #ifndef MBGL_MAP_UTIL_GL_OBJECT_STORE #define MBGL_MAP_UTIL_GL_OBJECT_STORE +#include #include #include @@ -14,18 +15,18 @@ public: GLObjectStore() = default; // Mark OpenGL objects for deletion - void abandonVAO(uint32_t vao); - void abandonBuffer(uint32_t buffer); - void abandonTexture(uint32_t texture); + void abandonVAO(GLuint vao); + void abandonBuffer(GLuint buffer); + void abandonTexture(GLuint texture); // Actually remove the objects we marked as abandoned with the above methods. // Only call this while the OpenGL context is exclusive to this thread. void performCleanup(); private: - std::vector abandonedVAOs; - std::vector abandonedBuffers; - std::vector abandonedTextures; + std::vector abandonedVAOs; + std::vector abandonedBuffers; + std::vector abandonedTextures; }; } diff --git a/src/mbgl/util/raster.cpp b/src/mbgl/util/raster.cpp index 9b8254089..1c277040c 100644 --- a/src/mbgl/util/raster.cpp +++ b/src/mbgl/util/raster.cpp @@ -50,7 +50,7 @@ void Raster::bind(bool linear) { MBGL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, texture)); } - GLuint new_filter = linear ? GL_LINEAR : GL_NEAREST; + GLint new_filter = linear ? GL_LINEAR : GL_NEAREST; if (new_filter != this->filter) { MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, new_filter)); MBGL_CHECK_ERROR(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, new_filter)); diff --git a/src/mbgl/util/raster.hpp b/src/mbgl/util/raster.hpp index 39ab26ffc..adf3b2cbf 100644 --- a/src/mbgl/util/raster.hpp +++ b/src/mbgl/util/raster.hpp @@ -1,6 +1,7 @@ #ifndef MBGL_UTIL_RASTER #define MBGL_UTIL_RASTER +#include #include #include #include @@ -32,13 +33,14 @@ public: public: // loaded image dimensions - uint32_t width = 0, height = 0; + GLsizei width = 0; + GLsizei height = 0; // has been uploaded to texture bool textured = false; // the uploaded texture - uint32_t texture = 0; + GLuint texture = 0; // texture opacity double opacity = 0; @@ -53,7 +55,7 @@ private: TexturePool& texturePool; // min/mag filter - uint32_t filter = 0; + GLint filter = 0; // the raw pixels std::unique_ptr img; diff --git a/src/mbgl/util/texture_pool.cpp b/src/mbgl/util/texture_pool.cpp index 84d24ac77..d4afb1f86 100644 --- a/src/mbgl/util/texture_pool.cpp +++ b/src/mbgl/util/texture_pool.cpp @@ -5,7 +5,7 @@ #include -const int TextureMax = 64; +const GLsizei TextureMax = 64; using namespace mbgl; @@ -13,7 +13,7 @@ GLuint TexturePool::getTextureID() { if (texture_ids.empty()) { GLuint new_texture_ids[TextureMax]; MBGL_CHECK_ERROR(glGenTextures(TextureMax, new_texture_ids)); - for (uint32_t id = 0; id < TextureMax; id++) { + for (GLuint id = 0; id < TextureMax; id++) { texture_ids.insert(new_texture_ids[id]); } } diff --git a/test/ios/App-Info.plist b/test/ios/App-Info.plist index f817ea1d9..ab5ac7ec8 100644 --- a/test/ios/App-Info.plist +++ b/test/ios/App-Info.plist @@ -9,7 +9,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - com.mapbox.${PRODUCT_NAME:rfc1034identifier} + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName @@ -28,6 +28,8 @@ pk.eyJ1IjoianVzdGluIiwiYSI6Ik9RX3RRQzAifQ.dmOg_BAp1ywuDZMM7YsXRg MGLMapboxMetricsEnabledSettingShownInApp + NSLocationAlwaysUsageDescription + Strictly for testing purposes, promise! UILaunchStoryboardName LaunchScreen UIRequiredDeviceCapabilities @@ -40,8 +42,6 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight - NSLocationAlwaysUsageDescription - Strictly for testing purposes, promise! UISupportedInterfaceOrientations~ipad UIInterfaceOrientationPortrait diff --git a/test/ios/Bundle-Info.plist b/test/ios/Bundle-Info.plist index 4ea0aed89..169b6f710 100644 --- a/test/ios/Bundle-Info.plist +++ b/test/ios/Bundle-Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - com.mapbox.${PRODUCT_NAME:rfc1034identifier} + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundlePackageType diff --git a/test/ios/KIF b/test/ios/KIF index 976aafa2e..21a137bc8 160000 --- a/test/ios/KIF +++ b/test/ios/KIF @@ -1 +1 @@ -Subproject commit 976aafa2e211dd095411bfef09da6c0919d70476 +Subproject commit 21a137bc8068f9fb738f835c6e285d44fe2ce4dd diff --git a/test/ios/MapViewTests.m b/test/ios/MapViewTests.m index f4ae501d7..1de31c6cc 100644 --- a/test/ios/MapViewTests.m +++ b/test/ios/MapViewTests.m @@ -46,7 +46,7 @@ 270, @"setting direction should take effect"); - [tester waitForTimeInterval:1]; + [tester waitForTimeInterval:2]; XCTAssertEqual(tester.compass.alpha, 1, @@ -66,7 +66,7 @@ [tester.compass tap]; - [tester waitForTimeInterval:1]; + [tester waitForTimeInterval:2]; XCTAssertEqual(tester.mapView.direction, 0, @@ -89,7 +89,7 @@ [tester.mapView resetNorth]; - [tester waitForTimeInterval:1]; + [tester waitForTimeInterval:2]; XCTAssertEqual(tester.mapView.direction, 0, @@ -220,6 +220,33 @@ @"panning map right should decrease center longitude"); } +- (void)testSetCenterCancelsTransitions { + XCTestExpectation *cameraIsInDCExpectation = [self expectationWithDescription:@"camera reset to DC"]; + + CLLocationCoordinate2D dc = CLLocationCoordinate2DMake(38.894368, -77.036487); + CLLocationCoordinate2D dc_west = CLLocationCoordinate2DMake(38.894368, -77.076487); + [tester.mapView setCenterCoordinate:dc animated:NO]; + [tester.mapView setCenterCoordinate:dc_west animated:YES]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.15 * NSEC_PER_SEC), + dispatch_get_main_queue(), + ^{ + [tester.mapView setCenterCoordinate:dc animated:NO]; + XCTAssertEqualWithAccuracy(dc.latitude, + tester.mapView.centerCoordinate.latitude, + 0.0005, + @"setting center coordinate should cancel transitions"); + XCTAssertEqualWithAccuracy(dc.longitude, + tester.mapView.centerCoordinate.longitude, + 0.0005, + @"setting center coordinate should cancel transitions"); + [cameraIsInDCExpectation fulfill]; + }); + + [self waitForExpectationsWithTimeout:1.0 handler:^(NSError *error) { + ; + }]; +} + - (void)testPanDisabled { tester.mapView.scrollEnabled = NO; CLLocationCoordinate2D centerCoordinate = tester.mapView.centerCoordinate; diff --git a/test/ios/ios-tests.xcodeproj/project.pbxproj b/test/ios/ios-tests.xcodeproj/project.pbxproj index 640837243..2807ee01b 100644 --- a/test/ios/ios-tests.xcodeproj/project.pbxproj +++ b/test/ios/ios-tests.xcodeproj/project.pbxproj @@ -41,6 +41,13 @@ /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ + DA3BDF011BA2326400553BD2 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = DDBD013A196DC3AE0033959E /* KIF.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 9CC9673B1AD4B1B600576D13; + remoteInfo = KIFFramework; + }; DDBD0143196DC3AE0033959E /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = DDBD013A196DC3AE0033959E /* KIF.xcodeproj */; @@ -48,13 +55,6 @@ remoteGlobalIDString = EABD46AA1857A0C700A5F081; remoteInfo = KIF; }; - DDBD0145196DC3AE0033959E /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = DDBD013A196DC3AE0033959E /* KIF.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = EB72047C1680DDAD00278DA2; - remoteInfo = "KIF-OCUnit"; - }; DDBD0147196DC3AE0033959E /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = DDBD013A196DC3AE0033959E /* KIF.xcodeproj */; @@ -69,13 +69,6 @@ remoteGlobalIDString = EABD46CD1857A0F300A5F081; remoteInfo = "KIF Tests"; }; - DDBD014B196DC3AE0033959E /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = DDBD013A196DC3AE0033959E /* KIF.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = EB60ECEB177F8DB3005A041A; - remoteInfo = "KIF Tests-OCUnit"; - }; DDBD0160196DC3D70033959E /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = DD04331B196DB9BC00E6F39D /* Project object */; @@ -327,10 +320,9 @@ isa = PBXGroup; children = ( DDBD0144196DC3AE0033959E /* libKIF.a */, - DDBD0146196DC3AE0033959E /* libKIF-OCUnit.a */, DDBD0148196DC3AE0033959E /* Test Host.app */, DDBD014A196DC3AE0033959E /* KIF Tests - XCTest.xctest */, - DDBD014C196DC3AE0033959E /* KIF Tests-OCUnit.octest */, + DA3BDF021BA2326400553BD2 /* KIF.framework */, ); name = Products; sourceTree = ""; @@ -396,7 +388,7 @@ isa = PBXProject; attributes = { CLASSPREFIX = MGLT; - LastUpgradeCheck = 0620; + LastUpgradeCheck = 0700; ORGANIZATIONNAME = Mapbox; TargetAttributes = { DDBD0151196DC3D70033959E = { @@ -430,6 +422,13 @@ /* End PBXProject section */ /* Begin PBXReferenceProxy section */ + DA3BDF021BA2326400553BD2 /* KIF.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = KIF.framework; + remoteRef = DA3BDF011BA2326400553BD2 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; DDBD0144196DC3AE0033959E /* libKIF.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; @@ -437,13 +436,6 @@ remoteRef = DDBD0143196DC3AE0033959E /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - DDBD0146196DC3AE0033959E /* libKIF-OCUnit.a */ = { - isa = PBXReferenceProxy; - fileType = archive.ar; - path = "libKIF-OCUnit.a"; - remoteRef = DDBD0145196DC3AE0033959E /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; DDBD0148196DC3AE0033959E /* Test Host.app */ = { isa = PBXReferenceProxy; fileType = wrapper.application; @@ -458,13 +450,6 @@ remoteRef = DDBD0149196DC3AE0033959E /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - DDBD014C196DC3AE0033959E /* KIF Tests-OCUnit.octest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = "KIF Tests-OCUnit.octest"; - remoteRef = DDBD014B196DC3AE0033959E /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; /* End PBXReferenceProxy section */ /* Begin PBXResourcesBuildPhase section */ @@ -547,6 +532,7 @@ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; @@ -618,6 +604,7 @@ ../../build/ios/pkg/static, ); OTHER_LDFLAGS = "-ObjC"; + PRODUCT_BUNDLE_IDENTIFIER = "com.mapbox.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; TARGETED_DEVICE_FAMILY = "1,2"; WRAPPER_EXTENSION = app; @@ -641,6 +628,7 @@ ../../build/ios/pkg/static, ); OTHER_LDFLAGS = "-ObjC"; + PRODUCT_BUNDLE_IDENTIFIER = "com.mapbox.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; TARGETED_DEVICE_FAMILY = "1,2"; WRAPPER_EXTENSION = app; @@ -651,12 +639,7 @@ isa = XCBuildConfiguration; buildSettings = { BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/Mapbox GL Tests.app/Mapbox GL Tests"; - FRAMEWORK_SEARCH_PATHS = ( - "$(SDKROOT)/Developer/Library/Frameworks", - "$(inherited)", - "$(DEVELOPER_FRAMEWORKS_DIR)", - "$(DEVELOPER_DIR)/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/Frameworks", - ); + FRAMEWORK_SEARCH_PATHS = ""; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", @@ -680,6 +663,7 @@ XCTest, "-ObjC", ); + PRODUCT_BUNDLE_IDENTIFIER = "com.mapbox.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; TEST_HOST = "$(BUNDLE_LOADER)"; WRAPPER_EXTENSION = xctest; @@ -690,12 +674,7 @@ isa = XCBuildConfiguration; buildSettings = { BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/Mapbox GL Tests.app/Mapbox GL Tests"; - FRAMEWORK_SEARCH_PATHS = ( - "$(SDKROOT)/Developer/Library/Frameworks", - "$(inherited)", - "$(DEVELOPER_FRAMEWORKS_DIR)", - "$(DEVELOPER_DIR)/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/Frameworks", - ); + FRAMEWORK_SEARCH_PATHS = ""; GCC_PREPROCESSOR_DEFINITIONS = "KIF_XCTEST=1"; HEADER_SEARCH_PATHS = ( "$(inherited)", @@ -715,6 +694,7 @@ XCTest, "-ObjC", ); + PRODUCT_BUNDLE_IDENTIFIER = "com.mapbox.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; TEST_HOST = "$(BUNDLE_LOADER)"; WRAPPER_EXTENSION = xctest; diff --git a/test/ios/ios-tests.xcodeproj/xcshareddata/xcschemes/Mapbox GL Tests.xcscheme b/test/ios/ios-tests.xcodeproj/xcshareddata/xcschemes/Mapbox GL Tests.xcscheme index 2737f5185..5f3f7f192 100644 --- a/test/ios/ios-tests.xcodeproj/xcshareddata/xcschemes/Mapbox GL Tests.xcscheme +++ b/test/ios/ios-tests.xcodeproj/xcshareddata/xcschemes/Mapbox GL Tests.xcscheme @@ -1,6 +1,6 @@ + + + + + + + + + +